diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/InlineContainerArea.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/InlineContainerArea.java index 0c538106a..da7e02fe7 100644 --- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/InlineContainerArea.java +++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/InlineContainerArea.java @@ -1,187 +1,194 @@ /*********************************************************************** * Copyright (c) 2009 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.report.engine.nLayout.area.impl; import java.util.ArrayList; import java.util.Iterator; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.content.ITextContent; import org.eclipse.birt.report.engine.nLayout.LayoutContext; import org.eclipse.birt.report.engine.nLayout.area.IContainerArea; import org.eclipse.birt.report.engine.nLayout.area.style.BoxStyle; public class InlineContainerArea extends InlineStackingArea implements IContainerArea { protected transient InlineStackingArea lineParent = null; protected transient int lineCount = 1; public InlineContainerArea( ContainerArea parent, LayoutContext context, IContent content ) { super( parent, context, content ); this.isInlineStacking = true; lineParent = (InlineStackingArea) parent; isInInlineStacking = parent.isInInlineStacking; } public InlineContainerArea( InlineContainerArea area ) { super( area ); } protected void close( boolean isLastLine ) throws BirtException { // TODO support specified height/width/alignment int contentWidth = currentIP; if ( lineCount == 1 ) { if ( specifiedWidth > contentWidth ) { contentWidth = specifiedWidth; } } setContentWidth( contentWidth ); int height = 0; Iterator iter = getChildren( ); while ( iter.hasNext( ) ) { AbstractArea child = (AbstractArea) iter.next( ); height = Math.max( height, child.getAllocatedHeight( ) ); } setContentHeight( height ); updateBackgroundImage( ); if ( children.size( ) > 0 ) { verticalAlign( ); } if ( isLastLine ) { checkPageBreak( ); parent.add( this ); parent.update( this ); this.finished = true; } else { checkPageBreak( ); InlineContainerArea area = cloneArea( ); addToExtension( area ); area.context = context; area.children = children; + // update the pareant of all children + Iterator childIter = area.children.iterator( ); + while ( childIter.hasNext( ) ) + { + AbstractArea childArea = (AbstractArea) childIter.next( ); + childArea.setParent( area ); + } area.setParent( parent ); children = new ArrayList( ); parent.addChild( area ); parent.update( area ); /*setPosition( parent.currentIP + parent.getOffsetX( ), parent .getOffsetY( ) + parent.currentBP );*/ area.finished = true; currentIP = 0; height = 0; } } protected void addToExtension( InlineContainerArea area ) { } public void close( ) throws BirtException { close( true ); finished = true; } public void initialize( ) throws BirtException { IStyle style = content.getStyle( ); calculateSpecifiedWidth( content ); if ( style == null || style.isEmpty( ) ) { hasStyle = false; boxStyle = BoxStyle.DEFAULT; localProperties = LocalProperties.DEFAULT; } else { buildProperties( content, context ); } maxAvaWidth = parent.getCurrentMaxContentWidth( ); bookmark = content.getBookmark( ); action = content.getHyperlinkAction( ); vAlign = style != null ? style.getProperty( IStyle.STYLE_VERTICAL_ALIGN ) : null; currentIP = 0; currentBP = 0; //parent.add( this ); } public InlineContainerArea cloneArea( ) { return new InlineContainerArea( this ); } public void endLine( boolean endParagraph ) throws BirtException { lineCount++; if ( getChildrenCount( ) > 0 ) { close( false ); } if ( lineParent != null ) { lineParent.endLine( endParagraph ); initialize( ); } } public int getMaxLineWidth( ) { return lineParent.getMaxLineWidth( ); } public boolean isEmptyLine( ) { if ( getChildrenCount( ) > 0 ) { return false; } return lineParent.isEmptyLine( ); } public void setTextIndent( ITextContent content ) { int ip = lineParent.getCurrentIP( ); lineParent.setTextIndent( content ); if ( ip != lineParent.getCurrentIP( ) ) { maxAvaWidth = parent.getCurrentMaxContentWidth( ); } } public SplitResult split( int height, boolean force ) throws BirtException { return SplitResult.SUCCEED_WITH_NULL; } public SplitResult splitLines( int lineCount ) throws BirtException { return SplitResult.SUCCEED_WITH_NULL; } }
true
true
protected void close( boolean isLastLine ) throws BirtException { // TODO support specified height/width/alignment int contentWidth = currentIP; if ( lineCount == 1 ) { if ( specifiedWidth > contentWidth ) { contentWidth = specifiedWidth; } } setContentWidth( contentWidth ); int height = 0; Iterator iter = getChildren( ); while ( iter.hasNext( ) ) { AbstractArea child = (AbstractArea) iter.next( ); height = Math.max( height, child.getAllocatedHeight( ) ); } setContentHeight( height ); updateBackgroundImage( ); if ( children.size( ) > 0 ) { verticalAlign( ); } if ( isLastLine ) { checkPageBreak( ); parent.add( this ); parent.update( this ); this.finished = true; } else { checkPageBreak( ); InlineContainerArea area = cloneArea( ); addToExtension( area ); area.context = context; area.children = children; area.setParent( parent ); children = new ArrayList( ); parent.addChild( area ); parent.update( area ); /*setPosition( parent.currentIP + parent.getOffsetX( ), parent .getOffsetY( ) + parent.currentBP );*/ area.finished = true; currentIP = 0; height = 0; } }
protected void close( boolean isLastLine ) throws BirtException { // TODO support specified height/width/alignment int contentWidth = currentIP; if ( lineCount == 1 ) { if ( specifiedWidth > contentWidth ) { contentWidth = specifiedWidth; } } setContentWidth( contentWidth ); int height = 0; Iterator iter = getChildren( ); while ( iter.hasNext( ) ) { AbstractArea child = (AbstractArea) iter.next( ); height = Math.max( height, child.getAllocatedHeight( ) ); } setContentHeight( height ); updateBackgroundImage( ); if ( children.size( ) > 0 ) { verticalAlign( ); } if ( isLastLine ) { checkPageBreak( ); parent.add( this ); parent.update( this ); this.finished = true; } else { checkPageBreak( ); InlineContainerArea area = cloneArea( ); addToExtension( area ); area.context = context; area.children = children; // update the pareant of all children Iterator childIter = area.children.iterator( ); while ( childIter.hasNext( ) ) { AbstractArea childArea = (AbstractArea) childIter.next( ); childArea.setParent( area ); } area.setParent( parent ); children = new ArrayList( ); parent.addChild( area ); parent.update( area ); /*setPosition( parent.currentIP + parent.getOffsetX( ), parent .getOffsetY( ) + parent.currentBP );*/ area.finished = true; currentIP = 0; height = 0; } }
diff --git a/nexus/nexus-configuration/src/main/java/org/sonatype/nexus/configuration/model/CRepositoryCoreConfiguration.java b/nexus/nexus-configuration/src/main/java/org/sonatype/nexus/configuration/model/CRepositoryCoreConfiguration.java index 1f8599782..30006c34e 100644 --- a/nexus/nexus-configuration/src/main/java/org/sonatype/nexus/configuration/model/CRepositoryCoreConfiguration.java +++ b/nexus/nexus-configuration/src/main/java/org/sonatype/nexus/configuration/model/CRepositoryCoreConfiguration.java @@ -1,29 +1,32 @@ package org.sonatype.nexus.configuration.model; import org.sonatype.nexus.configuration.ExternalConfiguration; public class CRepositoryCoreConfiguration extends AbstractCoreConfiguration { public CRepositoryCoreConfiguration( CRepository configuration ) { super( configuration ); } @Override protected void copyTransients( Object source, Object destination ) { ( (CRepository) destination ).setExternalConfiguration( ( (CRepository) source ).getExternalConfiguration() ); ( (CRepository) destination ).externalConfigurationImple = ( (CRepository) source ).externalConfigurationImple; // trick with RemoteStorage, which is an object, and XStream will not "overlap" it properly (ie. destionation != // null but source == null) - ( (CRepository) destination ).setRemoteStorage( ( (CRepository) source ).getRemoteStorage() ); + if ( ( (CRepository) source ).getRemoteStorage() == null ) + { + ( (CRepository) destination ).setRemoteStorage( null ); + } } public ExternalConfiguration getExternalConfiguration() { return ( (CRepository) getOriginalConfiguration() ).externalConfigurationImple; } }
true
true
protected void copyTransients( Object source, Object destination ) { ( (CRepository) destination ).setExternalConfiguration( ( (CRepository) source ).getExternalConfiguration() ); ( (CRepository) destination ).externalConfigurationImple = ( (CRepository) source ).externalConfigurationImple; // trick with RemoteStorage, which is an object, and XStream will not "overlap" it properly (ie. destionation != // null but source == null) ( (CRepository) destination ).setRemoteStorage( ( (CRepository) source ).getRemoteStorage() ); }
protected void copyTransients( Object source, Object destination ) { ( (CRepository) destination ).setExternalConfiguration( ( (CRepository) source ).getExternalConfiguration() ); ( (CRepository) destination ).externalConfigurationImple = ( (CRepository) source ).externalConfigurationImple; // trick with RemoteStorage, which is an object, and XStream will not "overlap" it properly (ie. destionation != // null but source == null) if ( ( (CRepository) source ).getRemoteStorage() == null ) { ( (CRepository) destination ).setRemoteStorage( null ); } }
diff --git a/library/src/com/viewpagerindicator/TitlePageIndicator.java b/library/src/com/viewpagerindicator/TitlePageIndicator.java index 1c91c26..c8a27b3 100644 --- a/library/src/com/viewpagerindicator/TitlePageIndicator.java +++ b/library/src/com/viewpagerindicator/TitlePageIndicator.java @@ -1,784 +1,785 @@ /* * Copyright (C) 2011 Jake Wharton * Copyright (C) 2011 Patrik Akerfeldt * Copyright (C) 2011 Francisco Figueiredo Jr. * * 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.viewpagerindicator; import java.util.ArrayList; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.graphics.Typeface; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewConfigurationCompat; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; /** * A TitlePageIndicator is a PageIndicator which displays the title of left view * (if exist), the title of the current select view (centered) and the title of * the right view (if exist). When the user scrolls the ViewPager then titles are * also scrolled. */ public class TitlePageIndicator extends View implements PageIndicator { /** * Percentage indicating what percentage of the screen width away from * center should the underline be fully faded. A value of 0.25 means that * halfway between the center of the screen and an edge. */ private static final float SELECTION_FADE_PERCENTAGE = 0.25f; /** * Percentage indicating what percentage of the screen width away from * center should the selected text bold turn off. A value of 0.05 means * that 10% between the center and an edge. */ private static final float BOLD_FADE_PERCENTAGE = 0.05f; /** * Interface for a callback when the center item has been clicked. */ public static interface OnCenterItemClickListener { /** * Callback when the center item has been clicked. * * @param position Position of the current center item. */ public void onCenterItemClick(int position); } public enum IndicatorStyle { None(0), Triangle(1), Underline(2); public final int value; private IndicatorStyle(int value) { this.value = value; } public static IndicatorStyle fromValue(int value) { for (IndicatorStyle style : IndicatorStyle.values()) { if (style.value == value) { return style; } } return null; } } private ViewPager mViewPager; private ViewPager.OnPageChangeListener mListener; private TitleProvider mTitleProvider; private int mCurrentPage; private int mCurrentOffset; private int mScrollState; private final Paint mPaintText = new Paint(); private boolean mBoldText; private int mColorText; private int mColorSelected; private Path mPath; private final Paint mPaintFooterLine = new Paint(); private IndicatorStyle mFooterIndicatorStyle; private final Paint mPaintFooterIndicator = new Paint(); private float mFooterIndicatorHeight; private float mFooterIndicatorUnderlinePadding; private float mFooterPadding; private float mTitlePadding; private float mTopPadding; /** Left and right side padding for not active view titles. */ private float mClipPadding; private float mFooterLineHeight; private static final int INVALID_POINTER = -1; private int mTouchSlop; private float mLastMotionX = -1; private int mActivePointerId = INVALID_POINTER; private boolean mIsDragging; private OnCenterItemClickListener mCenterItemClickListener; public TitlePageIndicator(Context context) { this(context, null); } public TitlePageIndicator(Context context, AttributeSet attrs) { this(context, attrs, R.attr.vpiTitlePageIndicatorStyle); } public TitlePageIndicator(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); //Load defaults from resources final Resources res = getResources(); final int defaultFooterColor = res.getColor(R.color.default_title_indicator_footer_color); final float defaultFooterLineHeight = res.getDimension(R.dimen.default_title_indicator_footer_line_height); final int defaultFooterIndicatorStyle = res.getInteger(R.integer.default_title_indicator_footer_indicator_style); final float defaultFooterIndicatorHeight = res.getDimension(R.dimen.default_title_indicator_footer_indicator_height); final float defaultFooterIndicatorUnderlinePadding = res.getDimension(R.dimen.default_title_indicator_footer_indicator_underline_padding); final float defaultFooterPadding = res.getDimension(R.dimen.default_title_indicator_footer_padding); final int defaultSelectedColor = res.getColor(R.color.default_title_indicator_selected_color); final boolean defaultSelectedBold = res.getBoolean(R.bool.default_title_indicator_selected_bold); final int defaultTextColor = res.getColor(R.color.default_title_indicator_text_color); final float defaultTextSize = res.getDimension(R.dimen.default_title_indicator_text_size); final float defaultTitlePadding = res.getDimension(R.dimen.default_title_indicator_title_padding); final float defaultClipPadding = res.getDimension(R.dimen.default_title_indicator_clip_padding); final float defaultTopPadding = res.getDimension(R.dimen.default_title_indicator_top_padding); //Retrieve styles attributes TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TitlePageIndicator, defStyle, R.style.Widget_TitlePageIndicator); //Retrieve the colors to be used for this view and apply them. mFooterLineHeight = a.getDimension(R.styleable.TitlePageIndicator_footerLineHeight, defaultFooterLineHeight); mFooterIndicatorStyle = IndicatorStyle.fromValue(a.getInteger(R.styleable.TitlePageIndicator_footerIndicatorStyle, defaultFooterIndicatorStyle)); mFooterIndicatorHeight = a.getDimension(R.styleable.TitlePageIndicator_footerIndicatorHeight, defaultFooterIndicatorHeight); mFooterIndicatorUnderlinePadding = a.getDimension(R.styleable.TitlePageIndicator_footerIndicatorUnderlinePadding, defaultFooterIndicatorUnderlinePadding); mFooterPadding = a.getDimension(R.styleable.TitlePageIndicator_footerPadding, defaultFooterPadding); mTopPadding = a.getDimension(R.styleable.TitlePageIndicator_topPadding, defaultTopPadding); mTitlePadding = a.getDimension(R.styleable.TitlePageIndicator_titlePadding, defaultTitlePadding); mClipPadding = a.getDimension(R.styleable.TitlePageIndicator_clipPadding, defaultClipPadding); mColorSelected = a.getColor(R.styleable.TitlePageIndicator_selectedColor, defaultSelectedColor); mColorText = a.getColor(R.styleable.TitlePageIndicator_textColor, defaultTextColor); mBoldText = a.getBoolean(R.styleable.TitlePageIndicator_selectedBold, defaultSelectedBold); final float textSize = a.getDimension(R.styleable.TitlePageIndicator_textSize, defaultTextSize); final int footerColor = a.getColor(R.styleable.TitlePageIndicator_footerColor, defaultFooterColor); mPaintText.setTextSize(textSize); mPaintText.setAntiAlias(true); mPaintFooterLine.setStyle(Paint.Style.FILL_AND_STROKE); mPaintFooterLine.setStrokeWidth(mFooterLineHeight); mPaintFooterLine.setColor(footerColor); mPaintFooterIndicator.setStyle(Paint.Style.FILL_AND_STROKE); mPaintFooterIndicator.setColor(footerColor); a.recycle(); final ViewConfiguration configuration = ViewConfiguration.get(context); mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); } public int getFooterColor() { return mPaintFooterLine.getColor(); } public void setFooterColor(int footerColor) { mPaintFooterLine.setColor(footerColor); mPaintFooterIndicator.setColor(footerColor); invalidate(); } public float getFooterLineHeight() { return mFooterLineHeight; } public void setFooterLineHeight(float footerLineHeight) { mFooterLineHeight = footerLineHeight; mPaintFooterLine.setStrokeWidth(mFooterLineHeight); invalidate(); } public float getFooterIndicatorHeight() { return mFooterIndicatorHeight; } public void setFooterIndicatorHeight(float footerTriangleHeight) { mFooterIndicatorHeight = footerTriangleHeight; invalidate(); } public float getFooterIndicatorPadding() { return mFooterPadding; } public void setFooterIndicatorPadding(float footerIndicatorPadding) { mFooterPadding = footerIndicatorPadding; invalidate(); } public IndicatorStyle getFooterIndicatorStyle() { return mFooterIndicatorStyle; } public void setFooterIndicatorStyle(IndicatorStyle indicatorStyle) { mFooterIndicatorStyle = indicatorStyle; invalidate(); } public int getSelectedColor() { return mColorSelected; } public void setSelectedColor(int selectedColor) { mColorSelected = selectedColor; invalidate(); } public boolean isSelectedBold() { return mBoldText; } public void setSelectedBold(boolean selectedBold) { mBoldText = selectedBold; invalidate(); } public int getTextColor() { return mColorText; } public void setTextColor(int textColor) { mPaintText.setColor(textColor); mColorText = textColor; invalidate(); } public float getTextSize() { return mPaintText.getTextSize(); } public void setTextSize(float textSize) { mPaintText.setTextSize(textSize); invalidate(); } public float getTitlePadding() { return this.mTitlePadding; } public void setTitlePadding(float titlePadding) { mTitlePadding = titlePadding; invalidate(); } public float getTopPadding() { return this.mTopPadding; } public void setTopPadding(float topPadding) { mTopPadding = topPadding; invalidate(); } public float getClipPadding() { return this.mClipPadding; } public void setClipPadding(float clipPadding) { mClipPadding = clipPadding; invalidate(); } public void setTypeface(Typeface typeface) { mPaintText.setTypeface(typeface); invalidate(); } public Typeface getTypeface() { return mPaintText.getTypeface(); } /* * (non-Javadoc) * * @see android.view.View#onDraw(android.graphics.Canvas) */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mViewPager == null) { return; } final int count = mViewPager.getAdapter().getCount(); if (count == 0) { return; } //Calculate views bounds ArrayList<RectF> bounds = calculateAllBounds(mPaintText); + final int boundsSize = bounds.size(); //Make sure we're on a page that still exists - if (mCurrentPage >= bounds.size()) { - setCurrentItem(bounds.size()-1); + if (mCurrentPage >= boundsSize) { + setCurrentItem(boundsSize - 1); } final int countMinusOne = count - 1; final float halfWidth = getWidth() / 2f; final int left = getLeft(); final float leftClip = left + mClipPadding; final int width = getWidth(); final int height = getHeight(); final int right = left + width; final float rightClip = right - mClipPadding; int page = mCurrentPage; float offsetPercent; if (mCurrentOffset <= halfWidth) { offsetPercent = 1.0f * mCurrentOffset / width; } else { page += 1; offsetPercent = 1.0f * (width - mCurrentOffset) / width; } final boolean currentSelected = (offsetPercent <= SELECTION_FADE_PERCENTAGE); final boolean currentBold = (offsetPercent <= BOLD_FADE_PERCENTAGE); final float selectedPercent = (SELECTION_FADE_PERCENTAGE - offsetPercent) / SELECTION_FADE_PERCENTAGE; //Verify if the current view must be clipped to the screen RectF curPageBound = bounds.get(mCurrentPage); float curPageWidth = curPageBound.right - curPageBound.left; if (curPageBound.left < leftClip) { //Try to clip to the screen (left side) clipViewOnTheLeft(curPageBound, curPageWidth, left); } if (curPageBound.right > rightClip) { //Try to clip to the screen (right side) clipViewOnTheRight(curPageBound, curPageWidth, right); } //Left views starting from the current position if (mCurrentPage > 0) { for (int i = mCurrentPage - 1; i >= 0; i--) { RectF bound = bounds.get(i); //Is left side is outside the screen if (bound.left < leftClip) { float w = bound.right - bound.left; //Try to clip to the screen (left side) clipViewOnTheLeft(bound, w, left); //Except if there's an intersection with the right view RectF rightBound = bounds.get(i + 1); //Intersection if (bound.right + mTitlePadding > rightBound.left) { bound.left = rightBound.left - w - mTitlePadding; bound.right = bound.left + w; } } } } //Right views starting from the current position if (mCurrentPage < countMinusOne) { for (int i = mCurrentPage + 1 ; i < count; i++) { RectF bound = bounds.get(i); //If right side is outside the screen if (bound.right > rightClip) { float w = bound.right - bound.left; //Try to clip to the screen (right side) clipViewOnTheRight(bound, w, right); //Except if there's an intersection with the left view RectF leftBound = bounds.get(i - 1); //Intersection if (bound.left - mTitlePadding < leftBound.right) { bound.left = leftBound.right + mTitlePadding; bound.right = bound.left + w; } } } } //Now draw views int colorTextAlpha = mColorText >>> 24; for (int i = 0; i < count; i++) { //Get the title RectF bound = bounds.get(i); //Only if one side is visible if ((bound.left > left && bound.left < right) || (bound.right > left && bound.right < right)) { final boolean currentPage = (i == page); //Only set bold if we are within bounds mPaintText.setFakeBoldText(currentPage && currentBold && mBoldText); //Draw text as unselected mPaintText.setColor(mColorText); if(currentPage && currentSelected) { //Fade out/in unselected text as the selected text fades in/out mPaintText.setAlpha(colorTextAlpha - (int)(colorTextAlpha * selectedPercent)); } canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom + mTopPadding, mPaintText); //If we are within the selected bounds draw the selected text if (currentPage && currentSelected) { mPaintText.setColor(mColorSelected); mPaintText.setAlpha((int)((mColorSelected >>> 24) * selectedPercent)); canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom + mTopPadding, mPaintText); } } } //Draw the footer line mPath = new Path(); mPath.moveTo(0, height - mFooterLineHeight / 2f); mPath.lineTo(width, height - mFooterLineHeight / 2f); mPath.close(); canvas.drawPath(mPath, mPaintFooterLine); switch (mFooterIndicatorStyle) { case Triangle: mPath = new Path(); mPath.moveTo(halfWidth, height - mFooterLineHeight - mFooterIndicatorHeight); mPath.lineTo(halfWidth + mFooterIndicatorHeight, height - mFooterLineHeight); mPath.lineTo(halfWidth - mFooterIndicatorHeight, height - mFooterLineHeight); mPath.close(); canvas.drawPath(mPath, mPaintFooterIndicator); break; case Underline: - if (!currentSelected) { + if (!currentSelected || page >= boundsSize) { break; } RectF underlineBounds = bounds.get(page); mPath = new Path(); mPath.moveTo(underlineBounds.left - mFooterIndicatorUnderlinePadding, height - mFooterLineHeight); mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding, height - mFooterLineHeight); mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding, height - mFooterLineHeight - mFooterIndicatorHeight); mPath.lineTo(underlineBounds.left - mFooterIndicatorUnderlinePadding, height - mFooterLineHeight - mFooterIndicatorHeight); mPath.close(); mPaintFooterIndicator.setAlpha((int)(0xFF * selectedPercent)); canvas.drawPath(mPath, mPaintFooterIndicator); mPaintFooterIndicator.setAlpha(0xFF); break; } } public boolean onTouchEvent(android.view.MotionEvent ev) { if (super.onTouchEvent(ev)) { return true; } if ((mViewPager == null) || (mViewPager.getAdapter().getCount() == 0)) { return false; } final int action = ev.getAction(); switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_DOWN: mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mLastMotionX = ev.getX(); break; case MotionEvent.ACTION_MOVE: { final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, activePointerIndex); final float deltaX = x - mLastMotionX; if (!mIsDragging) { if (Math.abs(deltaX) > mTouchSlop) { mIsDragging = true; } } if (mIsDragging) { if (!mViewPager.isFakeDragging()) { mViewPager.beginFakeDrag(); } mLastMotionX = x; mViewPager.fakeDragBy(deltaX); } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: if (!mIsDragging) { final int count = mViewPager.getAdapter().getCount(); final int width = getWidth(); final float halfWidth = width / 2f; final float sixthWidth = width / 6f; final float leftThird = halfWidth - sixthWidth; final float rightThird = halfWidth + sixthWidth; final float eventX = ev.getX(); if (eventX < leftThird) { if (mCurrentPage > 0) { mViewPager.setCurrentItem(mCurrentPage - 1); return true; } } else if (eventX > rightThird) { if (mCurrentPage < count - 1) { mViewPager.setCurrentItem(mCurrentPage + 1); return true; } } else { //Middle third if (mCenterItemClickListener != null) { mCenterItemClickListener.onCenterItemClick(mCurrentPage); } } } mIsDragging = false; mActivePointerId = INVALID_POINTER; if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag(); break; case MotionEventCompat.ACTION_POINTER_DOWN: { final int index = MotionEventCompat.getActionIndex(ev); final float x = MotionEventCompat.getX(ev, index); mLastMotionX = x; mActivePointerId = MotionEventCompat.getPointerId(ev, index); break; } case MotionEventCompat.ACTION_POINTER_UP: final int pointerIndex = MotionEventCompat.getActionIndex(ev); final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); } mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId)); break; } return true; }; /** * Set bounds for the right textView including clip padding. * * @param curViewBound * current bounds. * @param curViewWidth * width of the view. */ private void clipViewOnTheRight(RectF curViewBound, float curViewWidth, int right) { curViewBound.right = right - mClipPadding; curViewBound.left = curViewBound.right - curViewWidth; } /** * Set bounds for the left textView including clip padding. * * @param curViewBound * current bounds. * @param curViewWidth * width of the view. */ private void clipViewOnTheLeft(RectF curViewBound, float curViewWidth, int left) { curViewBound.left = left + mClipPadding; curViewBound.right = mClipPadding + curViewWidth; } /** * Calculate views bounds and scroll them according to the current index * * @param paint * @param currentIndex * @return */ private ArrayList<RectF> calculateAllBounds(Paint paint) { ArrayList<RectF> list = new ArrayList<RectF>(); //For each views (If no values then add a fake one) final int count = mViewPager.getAdapter().getCount(); final int width = getWidth(); final int halfWidth = width / 2; for (int i = 0; i < count; i++) { RectF bounds = calcBounds(i, paint); float w = (bounds.right - bounds.left); float h = (bounds.bottom - bounds.top); bounds.left = (halfWidth) - (w / 2) - mCurrentOffset + ((i - mCurrentPage) * width); bounds.right = bounds.left + w; bounds.top = 0; bounds.bottom = h; list.add(bounds); } return list; } /** * Calculate the bounds for a view's title * * @param index * @param paint * @return */ private RectF calcBounds(int index, Paint paint) { //Calculate the text bounds RectF bounds = new RectF(); bounds.right = paint.measureText(mTitleProvider.getTitle(index)); bounds.bottom = paint.descent() - paint.ascent(); return bounds; } @Override public void setViewPager(ViewPager view) { final PagerAdapter adapter = view.getAdapter(); if (adapter == null) { throw new IllegalStateException("ViewPager does not have adapter instance."); } if (!(adapter instanceof TitleProvider)) { throw new IllegalStateException("ViewPager adapter must implement TitleProvider to be used with TitlePageIndicator."); } mViewPager = view; mViewPager.setOnPageChangeListener(this); mTitleProvider = (TitleProvider)adapter; invalidate(); } @Override public void setViewPager(ViewPager view, int initialPosition) { setViewPager(view); setCurrentItem(initialPosition); } @Override public void notifyDataSetChanged() { invalidate(); } /** * Set a callback listener for the center item click. * * @param listener Callback instance. */ public void setOnCenterItemClickListener(OnCenterItemClickListener listener) { mCenterItemClickListener = listener; } @Override public void setCurrentItem(int item) { if (mViewPager == null) { throw new IllegalStateException("ViewPager has not been bound."); } mViewPager.setCurrentItem(item); mCurrentPage = item; invalidate(); } @Override public void onPageScrollStateChanged(int state) { mScrollState = state; if (mListener != null) { mListener.onPageScrollStateChanged(state); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { mCurrentPage = position; mCurrentOffset = positionOffsetPixels; invalidate(); if (mListener != null) { mListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } @Override public void onPageSelected(int position) { if (mScrollState == ViewPager.SCROLL_STATE_IDLE) { mCurrentPage = position; invalidate(); } if (mListener != null) { mListener.onPageSelected(position); } } @Override public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) { mListener = listener; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //Measure our width in whatever mode specified final int measuredWidth = MeasureSpec.getSize(widthMeasureSpec); //Determine our height float height = 0; final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); if (heightSpecMode == MeasureSpec.EXACTLY) { //We were told how big to be height = MeasureSpec.getSize(heightMeasureSpec); } else { //Calculate the text bounds RectF bounds = new RectF(); bounds.bottom = mPaintText.descent()-mPaintText.ascent(); height = bounds.bottom - bounds.top + mFooterLineHeight + mFooterPadding + mTopPadding; if (mFooterIndicatorStyle != IndicatorStyle.None) { height += mFooterIndicatorHeight; } } final int measuredHeight = (int)height; setMeasuredDimension(measuredWidth, measuredHeight); } @Override public void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState)state; super.onRestoreInstanceState(savedState.getSuperState()); mCurrentPage = savedState.currentPage; requestLayout(); } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState savedState = new SavedState(superState); savedState.currentPage = mCurrentPage; return savedState; } static class SavedState extends BaseSavedState { int currentPage; public SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); currentPage = in.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(currentPage); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
false
true
protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mViewPager == null) { return; } final int count = mViewPager.getAdapter().getCount(); if (count == 0) { return; } //Calculate views bounds ArrayList<RectF> bounds = calculateAllBounds(mPaintText); //Make sure we're on a page that still exists if (mCurrentPage >= bounds.size()) { setCurrentItem(bounds.size()-1); } final int countMinusOne = count - 1; final float halfWidth = getWidth() / 2f; final int left = getLeft(); final float leftClip = left + mClipPadding; final int width = getWidth(); final int height = getHeight(); final int right = left + width; final float rightClip = right - mClipPadding; int page = mCurrentPage; float offsetPercent; if (mCurrentOffset <= halfWidth) { offsetPercent = 1.0f * mCurrentOffset / width; } else { page += 1; offsetPercent = 1.0f * (width - mCurrentOffset) / width; } final boolean currentSelected = (offsetPercent <= SELECTION_FADE_PERCENTAGE); final boolean currentBold = (offsetPercent <= BOLD_FADE_PERCENTAGE); final float selectedPercent = (SELECTION_FADE_PERCENTAGE - offsetPercent) / SELECTION_FADE_PERCENTAGE; //Verify if the current view must be clipped to the screen RectF curPageBound = bounds.get(mCurrentPage); float curPageWidth = curPageBound.right - curPageBound.left; if (curPageBound.left < leftClip) { //Try to clip to the screen (left side) clipViewOnTheLeft(curPageBound, curPageWidth, left); } if (curPageBound.right > rightClip) { //Try to clip to the screen (right side) clipViewOnTheRight(curPageBound, curPageWidth, right); } //Left views starting from the current position if (mCurrentPage > 0) { for (int i = mCurrentPage - 1; i >= 0; i--) { RectF bound = bounds.get(i); //Is left side is outside the screen if (bound.left < leftClip) { float w = bound.right - bound.left; //Try to clip to the screen (left side) clipViewOnTheLeft(bound, w, left); //Except if there's an intersection with the right view RectF rightBound = bounds.get(i + 1); //Intersection if (bound.right + mTitlePadding > rightBound.left) { bound.left = rightBound.left - w - mTitlePadding; bound.right = bound.left + w; } } } } //Right views starting from the current position if (mCurrentPage < countMinusOne) { for (int i = mCurrentPage + 1 ; i < count; i++) { RectF bound = bounds.get(i); //If right side is outside the screen if (bound.right > rightClip) { float w = bound.right - bound.left; //Try to clip to the screen (right side) clipViewOnTheRight(bound, w, right); //Except if there's an intersection with the left view RectF leftBound = bounds.get(i - 1); //Intersection if (bound.left - mTitlePadding < leftBound.right) { bound.left = leftBound.right + mTitlePadding; bound.right = bound.left + w; } } } } //Now draw views int colorTextAlpha = mColorText >>> 24; for (int i = 0; i < count; i++) { //Get the title RectF bound = bounds.get(i); //Only if one side is visible if ((bound.left > left && bound.left < right) || (bound.right > left && bound.right < right)) { final boolean currentPage = (i == page); //Only set bold if we are within bounds mPaintText.setFakeBoldText(currentPage && currentBold && mBoldText); //Draw text as unselected mPaintText.setColor(mColorText); if(currentPage && currentSelected) { //Fade out/in unselected text as the selected text fades in/out mPaintText.setAlpha(colorTextAlpha - (int)(colorTextAlpha * selectedPercent)); } canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom + mTopPadding, mPaintText); //If we are within the selected bounds draw the selected text if (currentPage && currentSelected) { mPaintText.setColor(mColorSelected); mPaintText.setAlpha((int)((mColorSelected >>> 24) * selectedPercent)); canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom + mTopPadding, mPaintText); } } } //Draw the footer line mPath = new Path(); mPath.moveTo(0, height - mFooterLineHeight / 2f); mPath.lineTo(width, height - mFooterLineHeight / 2f); mPath.close(); canvas.drawPath(mPath, mPaintFooterLine); switch (mFooterIndicatorStyle) { case Triangle: mPath = new Path(); mPath.moveTo(halfWidth, height - mFooterLineHeight - mFooterIndicatorHeight); mPath.lineTo(halfWidth + mFooterIndicatorHeight, height - mFooterLineHeight); mPath.lineTo(halfWidth - mFooterIndicatorHeight, height - mFooterLineHeight); mPath.close(); canvas.drawPath(mPath, mPaintFooterIndicator); break; case Underline: if (!currentSelected) { break; } RectF underlineBounds = bounds.get(page); mPath = new Path(); mPath.moveTo(underlineBounds.left - mFooterIndicatorUnderlinePadding, height - mFooterLineHeight); mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding, height - mFooterLineHeight); mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding, height - mFooterLineHeight - mFooterIndicatorHeight); mPath.lineTo(underlineBounds.left - mFooterIndicatorUnderlinePadding, height - mFooterLineHeight - mFooterIndicatorHeight); mPath.close(); mPaintFooterIndicator.setAlpha((int)(0xFF * selectedPercent)); canvas.drawPath(mPath, mPaintFooterIndicator); mPaintFooterIndicator.setAlpha(0xFF); break; } }
protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mViewPager == null) { return; } final int count = mViewPager.getAdapter().getCount(); if (count == 0) { return; } //Calculate views bounds ArrayList<RectF> bounds = calculateAllBounds(mPaintText); final int boundsSize = bounds.size(); //Make sure we're on a page that still exists if (mCurrentPage >= boundsSize) { setCurrentItem(boundsSize - 1); } final int countMinusOne = count - 1; final float halfWidth = getWidth() / 2f; final int left = getLeft(); final float leftClip = left + mClipPadding; final int width = getWidth(); final int height = getHeight(); final int right = left + width; final float rightClip = right - mClipPadding; int page = mCurrentPage; float offsetPercent; if (mCurrentOffset <= halfWidth) { offsetPercent = 1.0f * mCurrentOffset / width; } else { page += 1; offsetPercent = 1.0f * (width - mCurrentOffset) / width; } final boolean currentSelected = (offsetPercent <= SELECTION_FADE_PERCENTAGE); final boolean currentBold = (offsetPercent <= BOLD_FADE_PERCENTAGE); final float selectedPercent = (SELECTION_FADE_PERCENTAGE - offsetPercent) / SELECTION_FADE_PERCENTAGE; //Verify if the current view must be clipped to the screen RectF curPageBound = bounds.get(mCurrentPage); float curPageWidth = curPageBound.right - curPageBound.left; if (curPageBound.left < leftClip) { //Try to clip to the screen (left side) clipViewOnTheLeft(curPageBound, curPageWidth, left); } if (curPageBound.right > rightClip) { //Try to clip to the screen (right side) clipViewOnTheRight(curPageBound, curPageWidth, right); } //Left views starting from the current position if (mCurrentPage > 0) { for (int i = mCurrentPage - 1; i >= 0; i--) { RectF bound = bounds.get(i); //Is left side is outside the screen if (bound.left < leftClip) { float w = bound.right - bound.left; //Try to clip to the screen (left side) clipViewOnTheLeft(bound, w, left); //Except if there's an intersection with the right view RectF rightBound = bounds.get(i + 1); //Intersection if (bound.right + mTitlePadding > rightBound.left) { bound.left = rightBound.left - w - mTitlePadding; bound.right = bound.left + w; } } } } //Right views starting from the current position if (mCurrentPage < countMinusOne) { for (int i = mCurrentPage + 1 ; i < count; i++) { RectF bound = bounds.get(i); //If right side is outside the screen if (bound.right > rightClip) { float w = bound.right - bound.left; //Try to clip to the screen (right side) clipViewOnTheRight(bound, w, right); //Except if there's an intersection with the left view RectF leftBound = bounds.get(i - 1); //Intersection if (bound.left - mTitlePadding < leftBound.right) { bound.left = leftBound.right + mTitlePadding; bound.right = bound.left + w; } } } } //Now draw views int colorTextAlpha = mColorText >>> 24; for (int i = 0; i < count; i++) { //Get the title RectF bound = bounds.get(i); //Only if one side is visible if ((bound.left > left && bound.left < right) || (bound.right > left && bound.right < right)) { final boolean currentPage = (i == page); //Only set bold if we are within bounds mPaintText.setFakeBoldText(currentPage && currentBold && mBoldText); //Draw text as unselected mPaintText.setColor(mColorText); if(currentPage && currentSelected) { //Fade out/in unselected text as the selected text fades in/out mPaintText.setAlpha(colorTextAlpha - (int)(colorTextAlpha * selectedPercent)); } canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom + mTopPadding, mPaintText); //If we are within the selected bounds draw the selected text if (currentPage && currentSelected) { mPaintText.setColor(mColorSelected); mPaintText.setAlpha((int)((mColorSelected >>> 24) * selectedPercent)); canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom + mTopPadding, mPaintText); } } } //Draw the footer line mPath = new Path(); mPath.moveTo(0, height - mFooterLineHeight / 2f); mPath.lineTo(width, height - mFooterLineHeight / 2f); mPath.close(); canvas.drawPath(mPath, mPaintFooterLine); switch (mFooterIndicatorStyle) { case Triangle: mPath = new Path(); mPath.moveTo(halfWidth, height - mFooterLineHeight - mFooterIndicatorHeight); mPath.lineTo(halfWidth + mFooterIndicatorHeight, height - mFooterLineHeight); mPath.lineTo(halfWidth - mFooterIndicatorHeight, height - mFooterLineHeight); mPath.close(); canvas.drawPath(mPath, mPaintFooterIndicator); break; case Underline: if (!currentSelected || page >= boundsSize) { break; } RectF underlineBounds = bounds.get(page); mPath = new Path(); mPath.moveTo(underlineBounds.left - mFooterIndicatorUnderlinePadding, height - mFooterLineHeight); mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding, height - mFooterLineHeight); mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding, height - mFooterLineHeight - mFooterIndicatorHeight); mPath.lineTo(underlineBounds.left - mFooterIndicatorUnderlinePadding, height - mFooterLineHeight - mFooterIndicatorHeight); mPath.close(); mPaintFooterIndicator.setAlpha((int)(0xFF * selectedPercent)); canvas.drawPath(mPath, mPaintFooterIndicator); mPaintFooterIndicator.setAlpha(0xFF); break; } }
diff --git a/OsceManager/src/main/java/ch/unibas/medizin/osce/client/style/widgets/IconButton.java b/OsceManager/src/main/java/ch/unibas/medizin/osce/client/style/widgets/IconButton.java index f0eb4ff0..aa89756e 100644 --- a/OsceManager/src/main/java/ch/unibas/medizin/osce/client/style/widgets/IconButton.java +++ b/OsceManager/src/main/java/ch/unibas/medizin/osce/client/style/widgets/IconButton.java @@ -1,77 +1,79 @@ package ch.unibas.medizin.osce.client.style.widgets; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.ClickListener; public class IconButton extends Button { private static final String ICON_HTML_OPEN = "<span class=\"ui-icon ui-icon-"; private static final String ICON_HTML_ICONONLY = " ui-icononly"; private static final String ICON_DISABLED = " ui-icon-disabled"; private static final String ICON_HTML_CLOSE = "\"></span>"; private String icon = "bullet"; private String text = ""; public IconButton() { super(); } public IconButton(String html) { super(html); } public IconButton(String html, ClickListener listener) { super(html, listener); } public IconButton(String html, ClickHandler handler) { super(html, handler); } public void setIcon(ImageResource image) { } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); construct(); } @Override public void setHTML(SafeHtml html) { this.text = html.asString(); construct(); } public void setIcon(String iconName) { this.icon = iconName; if (text.length() == 0) text = getText(); construct(); } public void setText(String text) { this.text = text; construct(); } private void construct() { String html = ICON_HTML_OPEN + icon; if (!isEnabled()) { html += ICON_DISABLED; } if (text.length() == 0) { html += ICON_HTML_ICONONLY + ICON_HTML_CLOSE; + super.removeStyleName("gwt-Button-WithIconText"); } else { html += ICON_HTML_CLOSE + text; + super.addStyleName("gwt-Button-WithIconText"); } SafeHtmlBuilder builder = new SafeHtmlBuilder(); builder.appendHtmlConstant(html); super.setHTML(builder.toSafeHtml()); } }
false
true
private void construct() { String html = ICON_HTML_OPEN + icon; if (!isEnabled()) { html += ICON_DISABLED; } if (text.length() == 0) { html += ICON_HTML_ICONONLY + ICON_HTML_CLOSE; } else { html += ICON_HTML_CLOSE + text; } SafeHtmlBuilder builder = new SafeHtmlBuilder(); builder.appendHtmlConstant(html); super.setHTML(builder.toSafeHtml()); }
private void construct() { String html = ICON_HTML_OPEN + icon; if (!isEnabled()) { html += ICON_DISABLED; } if (text.length() == 0) { html += ICON_HTML_ICONONLY + ICON_HTML_CLOSE; super.removeStyleName("gwt-Button-WithIconText"); } else { html += ICON_HTML_CLOSE + text; super.addStyleName("gwt-Button-WithIconText"); } SafeHtmlBuilder builder = new SafeHtmlBuilder(); builder.appendHtmlConstant(html); super.setHTML(builder.toSafeHtml()); }
diff --git a/stripes/src/net/sourceforge/stripes/action/FileBean.java b/stripes/src/net/sourceforge/stripes/action/FileBean.java index 8dc08f6d..8595b00c 100644 --- a/stripes/src/net/sourceforge/stripes/action/FileBean.java +++ b/stripes/src/net/sourceforge/stripes/action/FileBean.java @@ -1,170 +1,172 @@ /* Copyright 2005-2006 Tim Fennell * * 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.sourceforge.stripes.action; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.FileInputStream; /** * <p>Represents a file that was submitted as part of an HTTP POST request. Provides methods for * examining information about the file, and the retreiving the contents of the file. When a file * is uploaded by a user it is stored as a temporary file on the file system, which is wrapped by an * instance of this class. This is necessary because browsers may send file upload segments before * sending any other form parameters needed to identify what to do with the uploaded files!</p> * * <p>The application developer is responsible for removing this temporary file once they have * processed it. This can be accomplished in one of two ways. Firstly a call to save(File) will * effect a save by <em>moving</em> the temporary file to the desired location. In this case there * is no need to call delete(), although doing so will not delete the saved file. The second way is * to simply call delete(). This is more applicable when consuming the file as an InputStream. An * exmaple code fragment for reading a text based file might look like this:</p> * * <pre> * FileBean bean = getUserIcon(); * BufferedReader reader = new BufferedReader( new InputStreamReader(bean.getInputStream()) ); * String line = null * * while ( (line = reader.readLine()) != null) { * // do something with line * } * * bean.delete(); * </pre> * * @author Tim Fennell */ public class FileBean { private String contentType; private String fileName; private File file; private boolean saved; /** * Constructs a FileBean pointing to an on-disk representation of the file uploaded by the user. * * @param file the File object on the server which holds the uploaded contents of the file * @param contentType the content type of the file declared by the browser during uplaod * @param originalName the name of the file as declared by the user&apos;s browser */ public FileBean(File file, String contentType, String originalName) { this.file = file; this.contentType = contentType; this.fileName = originalName; } /** * Returns the name of the file that the user selected and uplaoded (this is not necessarily * the name that the underlying file is now stored on the server using). */ public String getFileName() { return fileName; } /** * Returns the content type of the file that the user selected and uplaoded. */ public String getContentType() { return contentType; } /** * Gets the size of the file that was uploaded. */ public long getSize() { return this.file.length(); } /** * Gets an input stream to read from the file uploaded */ public InputStream getInputStream() throws IOException { return new FileInputStream(this.file); } /** * Saves the uploaded file to the location on disk represented by File. This is currently * implemented as a simple rename of the underlying file that was created during upload. * * @param toFile a File object representing a location * @throws IOException if the save will fail for a reason that we can detect up front, for * example, missing files, permissions etc. or we try to save get a failure. */ public void save(File toFile) throws IOException { // Since File.renameTo doesn't tell you anything about why it failed, we test // for some common reasons for failure ahead of time and give a bit more info if (!this.file.exists()) { throw new IOException ("Some time between uploading and saving we lost the file " + this.file.getAbsolutePath() + " - where did it go?."); } if (!this.file.canWrite()) { throw new IOException ("Some time between uploading and saving we lost the ability to write to the file " + this.file.getAbsolutePath() + " - writability is required to move the file."); } - if (!toFile.canWrite() && !toFile.getParentFile().canWrite()) { - throw new IOException - ("Cannot write to "+ toFile.getAbsolutePath()); + if (toFile.exists() && !toFile.canWrite()) { + throw new IOException("Cannot overwrite existing file at "+ toFile.getAbsolutePath()); + } + else if (!toFile.exists() && !toFile.getAbsoluteFile().getParentFile().canWrite()) { + throw new IOException("Cannot create new file at location: " + toFile.getAbsolutePath()); } this.saved = this.file.renameTo(toFile); if (this.saved == false) { throw new IOException("Tried to save file [" + this.file.getAbsolutePath() + "] to file [" + toFile.getAbsolutePath() + "but got a false from File.renameTo(File)."); } } /** * Deletes the temporary file associated with this file upload if one still exists. If save() * has already been called then there is no temporary file any more, and this is a no-op. * * @throws IOException if the delete will fail for a reason we can detect up front, or if * we try to delete and get a failure */ public void delete() throws IOException { if (!this.saved) { // Since File.delete doesn't tell you anything about why it failed, we test // for some common reasons for failure ahead of time and give a bit more info if (!this.file.exists()) { throw new IOException ("Some time between uploading and saving we lost the file " + this.file.getAbsolutePath() + " - where did it go?."); } if (!this.file.canWrite()) { throw new IOException ("Some time between uploading and saving we lost the ability to write to the file " + this.file.getAbsolutePath() + " - writability is required to delete the file."); } this.file.delete(); } } /** * Returns the name of the file and the content type in a String format. */ public String toString() { return "FileBean{" + "contentType='" + contentType + "'" + ", fileName='" + fileName + "'" + "}"; } }
true
true
public void save(File toFile) throws IOException { // Since File.renameTo doesn't tell you anything about why it failed, we test // for some common reasons for failure ahead of time and give a bit more info if (!this.file.exists()) { throw new IOException ("Some time between uploading and saving we lost the file " + this.file.getAbsolutePath() + " - where did it go?."); } if (!this.file.canWrite()) { throw new IOException ("Some time between uploading and saving we lost the ability to write to the file " + this.file.getAbsolutePath() + " - writability is required to move the file."); } if (!toFile.canWrite() && !toFile.getParentFile().canWrite()) { throw new IOException ("Cannot write to "+ toFile.getAbsolutePath()); } this.saved = this.file.renameTo(toFile); if (this.saved == false) { throw new IOException("Tried to save file [" + this.file.getAbsolutePath() + "] to file [" + toFile.getAbsolutePath() + "but got a false from File.renameTo(File)."); } }
public void save(File toFile) throws IOException { // Since File.renameTo doesn't tell you anything about why it failed, we test // for some common reasons for failure ahead of time and give a bit more info if (!this.file.exists()) { throw new IOException ("Some time between uploading and saving we lost the file " + this.file.getAbsolutePath() + " - where did it go?."); } if (!this.file.canWrite()) { throw new IOException ("Some time between uploading and saving we lost the ability to write to the file " + this.file.getAbsolutePath() + " - writability is required to move the file."); } if (toFile.exists() && !toFile.canWrite()) { throw new IOException("Cannot overwrite existing file at "+ toFile.getAbsolutePath()); } else if (!toFile.exists() && !toFile.getAbsoluteFile().getParentFile().canWrite()) { throw new IOException("Cannot create new file at location: " + toFile.getAbsolutePath()); } this.saved = this.file.renameTo(toFile); if (this.saved == false) { throw new IOException("Tried to save file [" + this.file.getAbsolutePath() + "] to file [" + toFile.getAbsolutePath() + "but got a false from File.renameTo(File)."); } }
diff --git a/insight/insight-elasticsearch/src/test/java/org/elasticsearch/discovery/fabric/NodeJsonTest.java b/insight/insight-elasticsearch/src/test/java/org/elasticsearch/discovery/fabric/NodeJsonTest.java index 199c42d23..733538719 100644 --- a/insight/insight-elasticsearch/src/test/java/org/elasticsearch/discovery/fabric/NodeJsonTest.java +++ b/insight/insight-elasticsearch/src/test/java/org/elasticsearch/discovery/fabric/NodeJsonTest.java @@ -1,71 +1,71 @@ /** * Copyright (C) FuseSource, Inc. * http://fusesource.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.elasticsearch.discovery.fabric; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.codehaus.jackson.map.ObjectMapper; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.junit.Test; import static org.junit.Assert.assertEquals; public class NodeJsonTest { @Test public void testJson() throws Exception { Map<String, String> attr = new HashMap<String, String>(); attr.put("key", "value"); DiscoveryNode n = new DiscoveryNode("thename", "theid", new InetSocketTransportAddress("thehost", 3234), attr); FabricDiscovery.ESNode node = new FabricDiscovery.ESNode("thecluster", n, false); byte[] data = encode(node); System.err.println(new String(data)); FabricDiscovery.ESNode newNode = decode(data); - assertEquals(node.id(), newNode.id()); - assertEquals(node.node().id(), newNode.node().id()); - assertEquals(node.node().name(), newNode.node().name()); - assertEquals(node.node().address(), newNode.node().address()); - assertEquals(node.node().attributes(), newNode.node().attributes()); - assertEquals(node.node().version().toString(), newNode.node().version().toString()); + assertEquals(node.getId(), newNode.getId()); + assertEquals(node.getNode().id(), newNode.getNode().id()); + assertEquals(node.getNode().name(), newNode.getNode().name()); + assertEquals(node.getNode().address(), newNode.getNode().address()); + assertEquals(node.getNode().attributes(), newNode.getNode().attributes()); + assertEquals(node.getNode().version().toString(), newNode.getNode().version().toString()); } private final ObjectMapper mapper = new ObjectMapper(); private byte[] encode(FabricDiscovery.ESNode state) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); mapper.writeValue(baos, state); return baos.toByteArray(); } catch (IOException e) { throw new IllegalStateException("Unable to decode data", e); } } private FabricDiscovery.ESNode decode(byte[] data) { try { return mapper.readValue(data, FabricDiscovery.ESNode.class); } catch (IOException e) { throw new IllegalStateException("Unable to decode data", e); } } }
true
true
public void testJson() throws Exception { Map<String, String> attr = new HashMap<String, String>(); attr.put("key", "value"); DiscoveryNode n = new DiscoveryNode("thename", "theid", new InetSocketTransportAddress("thehost", 3234), attr); FabricDiscovery.ESNode node = new FabricDiscovery.ESNode("thecluster", n, false); byte[] data = encode(node); System.err.println(new String(data)); FabricDiscovery.ESNode newNode = decode(data); assertEquals(node.id(), newNode.id()); assertEquals(node.node().id(), newNode.node().id()); assertEquals(node.node().name(), newNode.node().name()); assertEquals(node.node().address(), newNode.node().address()); assertEquals(node.node().attributes(), newNode.node().attributes()); assertEquals(node.node().version().toString(), newNode.node().version().toString()); }
public void testJson() throws Exception { Map<String, String> attr = new HashMap<String, String>(); attr.put("key", "value"); DiscoveryNode n = new DiscoveryNode("thename", "theid", new InetSocketTransportAddress("thehost", 3234), attr); FabricDiscovery.ESNode node = new FabricDiscovery.ESNode("thecluster", n, false); byte[] data = encode(node); System.err.println(new String(data)); FabricDiscovery.ESNode newNode = decode(data); assertEquals(node.getId(), newNode.getId()); assertEquals(node.getNode().id(), newNode.getNode().id()); assertEquals(node.getNode().name(), newNode.getNode().name()); assertEquals(node.getNode().address(), newNode.getNode().address()); assertEquals(node.getNode().attributes(), newNode.getNode().attributes()); assertEquals(node.getNode().version().toString(), newNode.getNode().version().toString()); }
diff --git a/plugins/valueeditors/src/main/java/org/apache/directory/studio/valueeditors/password/PasswordDialog.java b/plugins/valueeditors/src/main/java/org/apache/directory/studio/valueeditors/password/PasswordDialog.java index 98415f251..205f45db0 100644 --- a/plugins/valueeditors/src/main/java/org/apache/directory/studio/valueeditors/password/PasswordDialog.java +++ b/plugins/valueeditors/src/main/java/org/apache/directory/studio/valueeditors/password/PasswordDialog.java @@ -1,630 +1,631 @@ /* * 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.directory.studio.valueeditors.password; import java.util.Arrays; import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.ConnectionParameter.AuthenticationMethod; import org.apache.directory.studio.connection.core.jobs.CheckBindRunnable; import org.apache.directory.studio.connection.ui.RunnableContextRunner; import org.apache.directory.studio.ldapbrowser.core.model.IEntry; import org.apache.directory.studio.ldapbrowser.core.model.Password; import org.apache.directory.studio.ldapbrowser.core.utils.Utils; import org.apache.directory.studio.valueeditors.ValueEditorsActivator; import org.apache.directory.studio.valueeditors.ValueEditorsConstants; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; 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.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; /** * The PasswordDialog is used from the password value editor to view the current password * and to enter a new password. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class PasswordDialog extends Dialog { /** The supported hash methods */ private static final String[] HASH_METHODS = { Password.HASH_METHOD_SHA, Password.HASH_METHOD_SSHA, Password.HASH_METHOD_MD5, Password.HASH_METHOD_SMD5, Password.HASH_METHOD_CRYPT, Password.HASH_METHOD_NO }; private static final int CURRENT_TAB = 0; private static final int NEW_TAB = 1; private static final String SELECTED_TAB_DIALOGSETTINGS_KEY = PasswordDialog.class.getName() + ".tab"; //$NON-NLS-1$ private static final String SELECTED_HASH_METHOD_DIALOGSETTINGS_KEY = PasswordDialog.class.getName() + ".hashMethod"; //$NON-NLS-1$ private TabFolder tabFolder; private TabItem currentTab; private TabItem newTab; private IEntry entry; private Password currentPassword; private Composite currentPasswordContainer; private Text currentPasswordText; private Text currentPasswordHashMethodText; private Text currentPasswordValueHexText; private Text currentPasswordSaltHexText; private Button showCurrentPasswordDetailsButton; private Text testPasswordText; private Text testBindDnText; private Button showTestPasswordDetailsButton; private Button verifyPasswordButton; private Button bindPasswordButton; private Password newPassword; private Composite newPasswordContainer; private Text newPasswordText; private Combo newPasswordHashMethodCombo; private Text newPasswordPreviewText; private Text newPasswordPreviewValueHexText; private Text newPasswordPreviewSaltHexText; private Button newSaltButton; private Button showNewPasswordDetailsButton; private byte[] returnPassword; private Button okButton; /** * Creates a new instance of PasswordDialog. * * @param parentShell the parent shell * @param currentPassword the current password, null if none * @param entry the entry used to bind */ public PasswordDialog( Shell parentShell, byte[] currentPassword, IEntry entry ) { super( parentShell ); super.setShellStyle( super.getShellStyle() | SWT.RESIZE ); try { this.currentPassword = currentPassword != null ? new Password( currentPassword ) : null; } catch ( IllegalArgumentException e ) { } this.entry = entry; this.returnPassword = null; } /** * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell) */ protected void configureShell( Shell shell ) { super.configureShell( shell ); shell.setText( Messages.getString( "PasswordDialog.PasswordEditor" ) ); //$NON-NLS-1$ shell.setImage( ValueEditorsActivator.getDefault().getImage( ValueEditorsConstants.IMG_PASSWORDEDITOR ) ); } /** * @see org.eclipse.jface.dialogs.Dialog#okPressed() */ protected void okPressed() { // create password if ( newPassword != null ) { returnPassword = newPassword.toBytes(); } else { returnPassword = null; } // save selected hash method to dialog settings, selected tab will be // saved int close() ValueEditorsActivator.getDefault().getDialogSettings().put( SELECTED_HASH_METHOD_DIALOGSETTINGS_KEY, newPasswordHashMethodCombo.getText() ); super.okPressed(); } /** * @see org.eclipse.jface.dialogs.Dialog#close() */ public boolean close() { // save selected tab to dialog settings ValueEditorsActivator.getDefault().getDialogSettings().put( SELECTED_TAB_DIALOGSETTINGS_KEY, tabFolder.getSelectionIndex() ); return super.close(); } /** * @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite) */ protected void createButtonsForButtonBar( Composite parent ) { okButton = createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, false ); createButton( parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false ); // load dialog settings try { int tabIndex = ValueEditorsActivator.getDefault().getDialogSettings().getInt( SELECTED_TAB_DIALOGSETTINGS_KEY ); if ( currentPassword == null || currentPassword.toBytes().length == 0 ) { tabIndex = NEW_TAB; } tabFolder.setSelection( tabIndex ); } catch ( Exception e ) { } try { String hashMethod = ValueEditorsActivator.getDefault().getDialogSettings().get( SELECTED_HASH_METHOD_DIALOGSETTINGS_KEY ); if ( Arrays.asList( HASH_METHODS ).contains( hashMethod ) ) { newPasswordHashMethodCombo.setText( hashMethod ); } } catch ( Exception e ) { } // update on load updateTabFolder(); } /** * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) */ protected Control createDialogArea( Composite parent ) { Composite composite = ( Composite ) super.createDialogArea( parent ); GridData gd = new GridData( GridData.FILL_BOTH ); gd.widthHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH ) * 3 / 2; gd.heightHint = convertVerticalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH ) * 2 / 3; composite.setLayoutData( gd ); tabFolder = new TabFolder( composite, SWT.TOP ); - GridLayout mainLayout = new GridLayout(); - mainLayout.marginWidth = 0; - mainLayout.marginHeight = 0; - tabFolder.setLayout( mainLayout ); +// GridLayout mainLayout = new GridLayout(); +// mainLayout.marginWidth = 0; +// mainLayout.marginHeight = 0; +// tabFolder.setLayout( mainLayout ); tabFolder.setLayoutData( new GridData( GridData.FILL_BOTH ) ); tabFolder.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { updateTabFolder(); } } ); // current password if ( currentPassword != null && currentPassword.toBytes().length > 0 ) { currentPasswordContainer = new Composite( tabFolder, SWT.NONE ); GridLayout currentLayout = new GridLayout( 2, false ); currentLayout.marginHeight = convertVerticalDLUsToPixels( IDialogConstants.VERTICAL_MARGIN ); currentLayout.marginWidth = convertHorizontalDLUsToPixels( IDialogConstants.HORIZONTAL_MARGIN ); currentLayout.verticalSpacing = convertVerticalDLUsToPixels( IDialogConstants.VERTICAL_SPACING ); currentLayout.horizontalSpacing = convertHorizontalDLUsToPixels( IDialogConstants.HORIZONTAL_SPACING ); currentPasswordContainer.setLayout( currentLayout ); + currentPasswordContainer.setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true) ); BaseWidgetUtils.createLabel( currentPasswordContainer, Messages .getString( "PasswordDialog.CurrentPassword" ) + ":", 1 ); //$NON-NLS-1$//$NON-NLS-2$ currentPasswordText = BaseWidgetUtils.createReadonlyText( currentPasswordContainer, "", 1 ); //$NON-NLS-1$ new Label( currentPasswordContainer, SWT.NONE ); Composite currentPasswordDetailContainer = BaseWidgetUtils.createColumnContainer( currentPasswordContainer, 2, 1 ); BaseWidgetUtils.createLabel( currentPasswordDetailContainer, Messages .getString( "PasswordDialog.HashMethod" ), 1 ); //$NON-NLS-1$ currentPasswordHashMethodText = BaseWidgetUtils.createLabeledText( currentPasswordDetailContainer, "", 1 ); //$NON-NLS-1$ BaseWidgetUtils.createLabel( currentPasswordDetailContainer, Messages .getString( "PasswordDialog.PasswordHex" ), 1 ); //$NON-NLS-1$ currentPasswordValueHexText = BaseWidgetUtils.createLabeledText( currentPasswordDetailContainer, "", 1 ); //$NON-NLS-1$ BaseWidgetUtils.createLabel( currentPasswordDetailContainer, Messages.getString( "PasswordDialog.SaltHex" ), 1 ); //$NON-NLS-1$ currentPasswordSaltHexText = BaseWidgetUtils.createLabeledText( currentPasswordDetailContainer, "", 1 ); //$NON-NLS-1$ showCurrentPasswordDetailsButton = BaseWidgetUtils.createCheckbox( currentPasswordDetailContainer, Messages .getString( "PasswordDialog.ShowCurrentPasswordDetails" ), 1 ); //$NON-NLS-1$ showCurrentPasswordDetailsButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { updateCurrentPasswordGroup(); } } ); BaseWidgetUtils.createLabel( currentPasswordContainer, Messages.getString( "PasswordDialog.VerifyPassword" ), 1 ); //$NON-NLS-1$ testPasswordText = BaseWidgetUtils.createText( currentPasswordContainer, "", 1 ); //$NON-NLS-1$ testPasswordText.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { updateCurrentPasswordGroup(); } } ); new Label( currentPasswordContainer, SWT.NONE ); Composite testPasswordDetailContainer = BaseWidgetUtils.createColumnContainer( currentPasswordContainer, 2, 1 ); BaseWidgetUtils.createLabel( testPasswordDetailContainer, Messages.getString( "PasswordDialog.BindDn" ), 1 ); //$NON-NLS-1$ testBindDnText = BaseWidgetUtils.createLabeledText( testPasswordDetailContainer, "", 1 ); //$NON-NLS-1$ showTestPasswordDetailsButton = BaseWidgetUtils.createCheckbox( testPasswordDetailContainer, Messages .getString( "PasswordDialog.ShowTestPasswordDetails" ), 2 ); //$NON-NLS-1$ showTestPasswordDetailsButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { updateCurrentPasswordGroup(); } } ); new Label( currentPasswordContainer, SWT.NONE ); Composite verifyPasswordButtonContainer = BaseWidgetUtils.createColumnContainer( currentPasswordContainer, 2, 1 ); verifyPasswordButton = BaseWidgetUtils.createButton( verifyPasswordButtonContainer, Messages .getString( "PasswordDialog.Verify" ), 1 ); //$NON-NLS-1$ verifyPasswordButton.setEnabled( false ); verifyPasswordButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { verifyCurrentPassword(); } } ); bindPasswordButton = BaseWidgetUtils.createButton( verifyPasswordButtonContainer, Messages .getString( "PasswordDialog.Bind" ), 1 ); //$NON-NLS-1$ bindPasswordButton.setEnabled( false ); bindPasswordButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { bindCurrentPassword(); } } ); currentTab = new TabItem( tabFolder, SWT.NONE ); currentTab.setText( Messages.getString( "PasswordDialog.CurrentPassword" ) ); //$NON-NLS-1$ currentTab.setControl( currentPasswordContainer ); } // new password newPasswordContainer = new Composite( tabFolder, SWT.NONE ); GridLayout newLayout = new GridLayout( 2, false ); newLayout.marginHeight = convertVerticalDLUsToPixels( IDialogConstants.VERTICAL_MARGIN ); newLayout.marginWidth = convertHorizontalDLUsToPixels( IDialogConstants.HORIZONTAL_MARGIN ); newLayout.verticalSpacing = convertVerticalDLUsToPixels( IDialogConstants.VERTICAL_SPACING ); newLayout.horizontalSpacing = convertHorizontalDLUsToPixels( IDialogConstants.HORIZONTAL_SPACING ); newPasswordContainer.setLayout( newLayout ); BaseWidgetUtils.createLabel( newPasswordContainer, Messages.getString( "PasswordDialog.EnterNewPassword" ), 1 ); //$NON-NLS-1$ newPasswordText = BaseWidgetUtils.createText( newPasswordContainer, "", 1 ); //$NON-NLS-1$ newPasswordText.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { updateNewPasswordGroup(); } } ); BaseWidgetUtils.createLabel( newPasswordContainer, Messages.getString( "PasswordDialog.SelectHashMethod" ), 1 ); //$NON-NLS-1$ newPasswordHashMethodCombo = BaseWidgetUtils.createReadonlyCombo( newPasswordContainer, HASH_METHODS, 0, 1 ); newPasswordHashMethodCombo.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { updateNewPasswordGroup(); } } ); BaseWidgetUtils.createLabel( newPasswordContainer, Messages.getString( "PasswordDialog.PasswordPreview" ), 1 ); //$NON-NLS-1$ newPasswordPreviewText = BaseWidgetUtils.createReadonlyText( newPasswordContainer, "", 1 ); //$NON-NLS-1$ newSaltButton = BaseWidgetUtils.createButton( newPasswordContainer, Messages .getString( "PasswordDialog.NewSalt" ), 1 ); //$NON-NLS-1$ newSaltButton.setLayoutData( new GridData() ); newSaltButton.setEnabled( false ); newSaltButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { updateNewPasswordGroup(); } } ); Composite newPasswordPreviewDetailContainer = BaseWidgetUtils .createColumnContainer( newPasswordContainer, 2, 1 ); BaseWidgetUtils.createLabel( newPasswordPreviewDetailContainer, Messages .getString( "PasswordDialog.PasswordHex" ), 1 ); //$NON-NLS-1$ newPasswordPreviewValueHexText = BaseWidgetUtils.createLabeledText( newPasswordPreviewDetailContainer, ":", 1 ); //$NON-NLS-1$ BaseWidgetUtils.createLabel( newPasswordPreviewDetailContainer, Messages.getString( "PasswordDialog.SaltHex" ), 1 ); //$NON-NLS-1$ newPasswordPreviewSaltHexText = BaseWidgetUtils.createLabeledText( newPasswordPreviewDetailContainer, "", 1 ); //$NON-NLS-1$ showNewPasswordDetailsButton = BaseWidgetUtils.createCheckbox( newPasswordPreviewDetailContainer, Messages .getString( "PasswordDialog.ShowNewPasswordDetails" ), 1 ); //$NON-NLS-1$ showNewPasswordDetailsButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { updateNewPasswordGroup(); } } ); newTab = new TabItem( tabFolder, SWT.NONE ); newTab.setText( Messages.getString( "PasswordDialog.NewPassword" ) ); //$NON-NLS-1$ newTab.setControl( newPasswordContainer ); applyDialogFont( composite ); return composite; } /** * Updates the current password tab. */ private void updateCurrentPasswordGroup() { // set current password to the UI widgets if ( currentPassword != null ) { currentPasswordHashMethodText.setText( Utils.getNonNullString( currentPassword.getHashMethod() ) ); currentPasswordValueHexText.setText( Utils .getNonNullString( currentPassword.getHashedPasswordAsHexString() ) ); currentPasswordSaltHexText.setText( Utils.getNonNullString( currentPassword.getSaltAsHexString() ) ); currentPasswordText.setText( currentPassword.toString() ); } // show password details? if ( showCurrentPasswordDetailsButton.getSelection() ) { currentPasswordText.setEchoChar( '\0' ); currentPasswordValueHexText.setEchoChar( '\0' ); currentPasswordSaltHexText.setEchoChar( '\0' ); } else { currentPasswordText.setEchoChar( '\u2022' ); currentPasswordValueHexText.setEchoChar( '\u2022' ); currentPasswordSaltHexText.setEchoChar( currentPasswordSaltHexText.getText().equals( Utils.getNonNullString( null ) ) ? '\0' : '\u2022' ); } // enable/disable test field and buttons testPasswordText.setEnabled( currentPassword != null && currentPassword.getHashedPassword() != null && currentPassword.toBytes().length > 0 ); testBindDnText.setText( entry != null ? entry.getDn().getName() : Utils.getNonNullString( null ) ); if ( showTestPasswordDetailsButton.getSelection() ) { testPasswordText.setEchoChar( '\0' ); } else { testPasswordText.setEchoChar( '\u2022' ); } verifyPasswordButton.setEnabled( testPasswordText.isEnabled() && !"".equals( testPasswordText.getText() ) ); //$NON-NLS-1$ bindPasswordButton.setEnabled( testPasswordText.isEnabled() && !"".equals( testPasswordText.getText() ) //$NON-NLS-1$ && entry != null && entry.getBrowserConnection().getConnection() != null ); // default dialog button if ( verifyPasswordButton.isEnabled() ) { getShell().setDefaultButton( verifyPasswordButton ); } else { getShell().setDefaultButton( okButton ); } } /** * Verifies the current password. */ private void verifyCurrentPassword() { String testPassword = testPasswordText.getText(); if ( currentPassword != null ) { if ( currentPassword.verify( testPassword ) ) { MessageDialog dialog = new MessageDialog( getShell(), Messages.getString( "PasswordDialog.PasswordVerification" ), getShell().getImage(), //$NON-NLS-1$ Messages.getString( "PasswordDialog.PasswordVerifiedSuccessfully" ), MessageDialog.INFORMATION, new String[] //$NON-NLS-1$ { IDialogConstants.OK_LABEL }, 0 ); dialog.open(); } else { MessageDialog dialog = new MessageDialog( getShell(), Messages.getString( "PasswordDialog.PasswordVerification" ), getShell().getImage(), //$NON-NLS-1$ Messages.getString( "PasswordDialog.PasswordVerificationFailed" ), MessageDialog.ERROR, new String[] //$NON-NLS-1$ { IDialogConstants.OK_LABEL }, 0 ); dialog.open(); } } } /** * Binds to the directory using the test password. */ private void bindCurrentPassword() { if ( !"".equals( testPasswordText.getText() ) && entry != null //$NON-NLS-1$ && entry.getBrowserConnection().getConnection() != null ) { Connection connection = ( Connection ) entry.getBrowserConnection().getConnection().clone(); connection.getConnectionParameter().setName( null ); connection.getConnectionParameter().setBindPrincipal( entry.getDn().getName() ); connection.getConnectionParameter().setBindPassword( testPasswordText.getText() ); connection.getConnectionParameter().setAuthMethod( AuthenticationMethod.SIMPLE ); CheckBindRunnable runnable = new CheckBindRunnable( connection ); IStatus status = RunnableContextRunner.execute( runnable, null, true ); if ( status.isOK() ) { MessageDialog.openInformation( Display.getDefault().getActiveShell(), Messages .getString( "PasswordDialog.CheckAuthentication" ), //$NON-NLS-1$ Messages.getString( "PasswordDialog.AuthenticationSuccessful" ) ); //$NON-NLS-1$ } } } /** * Updates the new password tab. */ private void updateNewPasswordGroup() { // set new password to the UI widgets newPassword = new Password( newPasswordHashMethodCombo.getText(), newPasswordText.getText() ); if ( !"".equals( newPasswordText.getText() ) || newPassword.getHashMethod() == null ) //$NON-NLS-1$ { newPasswordPreviewValueHexText .setText( Utils.getNonNullString( newPassword.getHashedPasswordAsHexString() ) ); newPasswordPreviewSaltHexText.setText( Utils.getNonNullString( newPassword.getSaltAsHexString() ) ); newPasswordPreviewText.setText( newPassword.toString() ); newSaltButton.setEnabled( newPassword.getSalt() != null ); okButton.setEnabled( true ); getShell().setDefaultButton( okButton ); } else { newPassword = null; newPasswordPreviewValueHexText.setText( Utils.getNonNullString( null ) ); newPasswordPreviewSaltHexText.setText( Utils.getNonNullString( null ) ); newPasswordPreviewText.setText( Utils.getNonNullString( null ) ); newSaltButton.setEnabled( false ); okButton.setEnabled( false ); } // show password details? if ( showNewPasswordDetailsButton.getSelection() ) { newPasswordText.setEchoChar( '\0' ); newPasswordPreviewText.setEchoChar( '\0' ); newPasswordPreviewValueHexText.setEchoChar( '\0' ); newPasswordPreviewSaltHexText.setEchoChar( '\0' ); } else { newPasswordText.setEchoChar( '\u2022' ); newPasswordPreviewText.setEchoChar( newPasswordPreviewText.getText() .equals( Utils.getNonNullString( null ) ) ? '\0' : '\u2022' ); newPasswordPreviewValueHexText.setEchoChar( newPasswordPreviewValueHexText.getText().equals( Utils.getNonNullString( null ) ) ? '\0' : '\u2022' ); newPasswordPreviewSaltHexText.setEchoChar( newPasswordPreviewSaltHexText.getText().equals( Utils.getNonNullString( null ) ) ? '\0' : '\u2022' ); } } /** * Updates the tab folder and the tabs. */ private void updateTabFolder() { if ( testPasswordText != null && newPasswordText != null ) { if ( tabFolder.getSelectionIndex() == CURRENT_TAB ) { testPasswordText.setFocus(); } else if ( tabFolder.getSelectionIndex() == NEW_TAB ) { newPasswordText.setFocus(); } updateCurrentPasswordGroup(); updateNewPasswordGroup(); } } /** * Gets the new password. * * @return the password, either encypted by the selected * algorithm or as plain text. */ public byte[] getNewPassword() { return returnPassword; } }
false
true
protected Control createDialogArea( Composite parent ) { Composite composite = ( Composite ) super.createDialogArea( parent ); GridData gd = new GridData( GridData.FILL_BOTH ); gd.widthHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH ) * 3 / 2; gd.heightHint = convertVerticalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH ) * 2 / 3; composite.setLayoutData( gd ); tabFolder = new TabFolder( composite, SWT.TOP ); GridLayout mainLayout = new GridLayout(); mainLayout.marginWidth = 0; mainLayout.marginHeight = 0; tabFolder.setLayout( mainLayout ); tabFolder.setLayoutData( new GridData( GridData.FILL_BOTH ) ); tabFolder.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { updateTabFolder(); } } ); // current password if ( currentPassword != null && currentPassword.toBytes().length > 0 ) { currentPasswordContainer = new Composite( tabFolder, SWT.NONE ); GridLayout currentLayout = new GridLayout( 2, false ); currentLayout.marginHeight = convertVerticalDLUsToPixels( IDialogConstants.VERTICAL_MARGIN ); currentLayout.marginWidth = convertHorizontalDLUsToPixels( IDialogConstants.HORIZONTAL_MARGIN ); currentLayout.verticalSpacing = convertVerticalDLUsToPixels( IDialogConstants.VERTICAL_SPACING ); currentLayout.horizontalSpacing = convertHorizontalDLUsToPixels( IDialogConstants.HORIZONTAL_SPACING ); currentPasswordContainer.setLayout( currentLayout ); BaseWidgetUtils.createLabel( currentPasswordContainer, Messages .getString( "PasswordDialog.CurrentPassword" ) + ":", 1 ); //$NON-NLS-1$//$NON-NLS-2$ currentPasswordText = BaseWidgetUtils.createReadonlyText( currentPasswordContainer, "", 1 ); //$NON-NLS-1$ new Label( currentPasswordContainer, SWT.NONE ); Composite currentPasswordDetailContainer = BaseWidgetUtils.createColumnContainer( currentPasswordContainer, 2, 1 ); BaseWidgetUtils.createLabel( currentPasswordDetailContainer, Messages .getString( "PasswordDialog.HashMethod" ), 1 ); //$NON-NLS-1$ currentPasswordHashMethodText = BaseWidgetUtils.createLabeledText( currentPasswordDetailContainer, "", 1 ); //$NON-NLS-1$ BaseWidgetUtils.createLabel( currentPasswordDetailContainer, Messages .getString( "PasswordDialog.PasswordHex" ), 1 ); //$NON-NLS-1$ currentPasswordValueHexText = BaseWidgetUtils.createLabeledText( currentPasswordDetailContainer, "", 1 ); //$NON-NLS-1$ BaseWidgetUtils.createLabel( currentPasswordDetailContainer, Messages.getString( "PasswordDialog.SaltHex" ), 1 ); //$NON-NLS-1$ currentPasswordSaltHexText = BaseWidgetUtils.createLabeledText( currentPasswordDetailContainer, "", 1 ); //$NON-NLS-1$ showCurrentPasswordDetailsButton = BaseWidgetUtils.createCheckbox( currentPasswordDetailContainer, Messages .getString( "PasswordDialog.ShowCurrentPasswordDetails" ), 1 ); //$NON-NLS-1$ showCurrentPasswordDetailsButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { updateCurrentPasswordGroup(); } } ); BaseWidgetUtils.createLabel( currentPasswordContainer, Messages.getString( "PasswordDialog.VerifyPassword" ), 1 ); //$NON-NLS-1$ testPasswordText = BaseWidgetUtils.createText( currentPasswordContainer, "", 1 ); //$NON-NLS-1$ testPasswordText.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { updateCurrentPasswordGroup(); } } ); new Label( currentPasswordContainer, SWT.NONE ); Composite testPasswordDetailContainer = BaseWidgetUtils.createColumnContainer( currentPasswordContainer, 2, 1 ); BaseWidgetUtils.createLabel( testPasswordDetailContainer, Messages.getString( "PasswordDialog.BindDn" ), 1 ); //$NON-NLS-1$ testBindDnText = BaseWidgetUtils.createLabeledText( testPasswordDetailContainer, "", 1 ); //$NON-NLS-1$ showTestPasswordDetailsButton = BaseWidgetUtils.createCheckbox( testPasswordDetailContainer, Messages .getString( "PasswordDialog.ShowTestPasswordDetails" ), 2 ); //$NON-NLS-1$ showTestPasswordDetailsButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { updateCurrentPasswordGroup(); } } ); new Label( currentPasswordContainer, SWT.NONE ); Composite verifyPasswordButtonContainer = BaseWidgetUtils.createColumnContainer( currentPasswordContainer, 2, 1 ); verifyPasswordButton = BaseWidgetUtils.createButton( verifyPasswordButtonContainer, Messages .getString( "PasswordDialog.Verify" ), 1 ); //$NON-NLS-1$ verifyPasswordButton.setEnabled( false ); verifyPasswordButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { verifyCurrentPassword(); } } ); bindPasswordButton = BaseWidgetUtils.createButton( verifyPasswordButtonContainer, Messages .getString( "PasswordDialog.Bind" ), 1 ); //$NON-NLS-1$ bindPasswordButton.setEnabled( false ); bindPasswordButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { bindCurrentPassword(); } } ); currentTab = new TabItem( tabFolder, SWT.NONE ); currentTab.setText( Messages.getString( "PasswordDialog.CurrentPassword" ) ); //$NON-NLS-1$ currentTab.setControl( currentPasswordContainer ); } // new password newPasswordContainer = new Composite( tabFolder, SWT.NONE ); GridLayout newLayout = new GridLayout( 2, false ); newLayout.marginHeight = convertVerticalDLUsToPixels( IDialogConstants.VERTICAL_MARGIN ); newLayout.marginWidth = convertHorizontalDLUsToPixels( IDialogConstants.HORIZONTAL_MARGIN ); newLayout.verticalSpacing = convertVerticalDLUsToPixels( IDialogConstants.VERTICAL_SPACING ); newLayout.horizontalSpacing = convertHorizontalDLUsToPixels( IDialogConstants.HORIZONTAL_SPACING ); newPasswordContainer.setLayout( newLayout ); BaseWidgetUtils.createLabel( newPasswordContainer, Messages.getString( "PasswordDialog.EnterNewPassword" ), 1 ); //$NON-NLS-1$ newPasswordText = BaseWidgetUtils.createText( newPasswordContainer, "", 1 ); //$NON-NLS-1$ newPasswordText.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { updateNewPasswordGroup(); } } ); BaseWidgetUtils.createLabel( newPasswordContainer, Messages.getString( "PasswordDialog.SelectHashMethod" ), 1 ); //$NON-NLS-1$ newPasswordHashMethodCombo = BaseWidgetUtils.createReadonlyCombo( newPasswordContainer, HASH_METHODS, 0, 1 ); newPasswordHashMethodCombo.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { updateNewPasswordGroup(); } } ); BaseWidgetUtils.createLabel( newPasswordContainer, Messages.getString( "PasswordDialog.PasswordPreview" ), 1 ); //$NON-NLS-1$ newPasswordPreviewText = BaseWidgetUtils.createReadonlyText( newPasswordContainer, "", 1 ); //$NON-NLS-1$ newSaltButton = BaseWidgetUtils.createButton( newPasswordContainer, Messages .getString( "PasswordDialog.NewSalt" ), 1 ); //$NON-NLS-1$ newSaltButton.setLayoutData( new GridData() ); newSaltButton.setEnabled( false ); newSaltButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { updateNewPasswordGroup(); } } ); Composite newPasswordPreviewDetailContainer = BaseWidgetUtils .createColumnContainer( newPasswordContainer, 2, 1 ); BaseWidgetUtils.createLabel( newPasswordPreviewDetailContainer, Messages .getString( "PasswordDialog.PasswordHex" ), 1 ); //$NON-NLS-1$ newPasswordPreviewValueHexText = BaseWidgetUtils.createLabeledText( newPasswordPreviewDetailContainer, ":", 1 ); //$NON-NLS-1$ BaseWidgetUtils.createLabel( newPasswordPreviewDetailContainer, Messages.getString( "PasswordDialog.SaltHex" ), 1 ); //$NON-NLS-1$ newPasswordPreviewSaltHexText = BaseWidgetUtils.createLabeledText( newPasswordPreviewDetailContainer, "", 1 ); //$NON-NLS-1$ showNewPasswordDetailsButton = BaseWidgetUtils.createCheckbox( newPasswordPreviewDetailContainer, Messages .getString( "PasswordDialog.ShowNewPasswordDetails" ), 1 ); //$NON-NLS-1$ showNewPasswordDetailsButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { updateNewPasswordGroup(); } } ); newTab = new TabItem( tabFolder, SWT.NONE ); newTab.setText( Messages.getString( "PasswordDialog.NewPassword" ) ); //$NON-NLS-1$ newTab.setControl( newPasswordContainer ); applyDialogFont( composite ); return composite; }
protected Control createDialogArea( Composite parent ) { Composite composite = ( Composite ) super.createDialogArea( parent ); GridData gd = new GridData( GridData.FILL_BOTH ); gd.widthHint = convertHorizontalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH ) * 3 / 2; gd.heightHint = convertVerticalDLUsToPixels( IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH ) * 2 / 3; composite.setLayoutData( gd ); tabFolder = new TabFolder( composite, SWT.TOP ); // GridLayout mainLayout = new GridLayout(); // mainLayout.marginWidth = 0; // mainLayout.marginHeight = 0; // tabFolder.setLayout( mainLayout ); tabFolder.setLayoutData( new GridData( GridData.FILL_BOTH ) ); tabFolder.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { updateTabFolder(); } } ); // current password if ( currentPassword != null && currentPassword.toBytes().length > 0 ) { currentPasswordContainer = new Composite( tabFolder, SWT.NONE ); GridLayout currentLayout = new GridLayout( 2, false ); currentLayout.marginHeight = convertVerticalDLUsToPixels( IDialogConstants.VERTICAL_MARGIN ); currentLayout.marginWidth = convertHorizontalDLUsToPixels( IDialogConstants.HORIZONTAL_MARGIN ); currentLayout.verticalSpacing = convertVerticalDLUsToPixels( IDialogConstants.VERTICAL_SPACING ); currentLayout.horizontalSpacing = convertHorizontalDLUsToPixels( IDialogConstants.HORIZONTAL_SPACING ); currentPasswordContainer.setLayout( currentLayout ); currentPasswordContainer.setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true) ); BaseWidgetUtils.createLabel( currentPasswordContainer, Messages .getString( "PasswordDialog.CurrentPassword" ) + ":", 1 ); //$NON-NLS-1$//$NON-NLS-2$ currentPasswordText = BaseWidgetUtils.createReadonlyText( currentPasswordContainer, "", 1 ); //$NON-NLS-1$ new Label( currentPasswordContainer, SWT.NONE ); Composite currentPasswordDetailContainer = BaseWidgetUtils.createColumnContainer( currentPasswordContainer, 2, 1 ); BaseWidgetUtils.createLabel( currentPasswordDetailContainer, Messages .getString( "PasswordDialog.HashMethod" ), 1 ); //$NON-NLS-1$ currentPasswordHashMethodText = BaseWidgetUtils.createLabeledText( currentPasswordDetailContainer, "", 1 ); //$NON-NLS-1$ BaseWidgetUtils.createLabel( currentPasswordDetailContainer, Messages .getString( "PasswordDialog.PasswordHex" ), 1 ); //$NON-NLS-1$ currentPasswordValueHexText = BaseWidgetUtils.createLabeledText( currentPasswordDetailContainer, "", 1 ); //$NON-NLS-1$ BaseWidgetUtils.createLabel( currentPasswordDetailContainer, Messages.getString( "PasswordDialog.SaltHex" ), 1 ); //$NON-NLS-1$ currentPasswordSaltHexText = BaseWidgetUtils.createLabeledText( currentPasswordDetailContainer, "", 1 ); //$NON-NLS-1$ showCurrentPasswordDetailsButton = BaseWidgetUtils.createCheckbox( currentPasswordDetailContainer, Messages .getString( "PasswordDialog.ShowCurrentPasswordDetails" ), 1 ); //$NON-NLS-1$ showCurrentPasswordDetailsButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { updateCurrentPasswordGroup(); } } ); BaseWidgetUtils.createLabel( currentPasswordContainer, Messages.getString( "PasswordDialog.VerifyPassword" ), 1 ); //$NON-NLS-1$ testPasswordText = BaseWidgetUtils.createText( currentPasswordContainer, "", 1 ); //$NON-NLS-1$ testPasswordText.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { updateCurrentPasswordGroup(); } } ); new Label( currentPasswordContainer, SWT.NONE ); Composite testPasswordDetailContainer = BaseWidgetUtils.createColumnContainer( currentPasswordContainer, 2, 1 ); BaseWidgetUtils.createLabel( testPasswordDetailContainer, Messages.getString( "PasswordDialog.BindDn" ), 1 ); //$NON-NLS-1$ testBindDnText = BaseWidgetUtils.createLabeledText( testPasswordDetailContainer, "", 1 ); //$NON-NLS-1$ showTestPasswordDetailsButton = BaseWidgetUtils.createCheckbox( testPasswordDetailContainer, Messages .getString( "PasswordDialog.ShowTestPasswordDetails" ), 2 ); //$NON-NLS-1$ showTestPasswordDetailsButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { updateCurrentPasswordGroup(); } } ); new Label( currentPasswordContainer, SWT.NONE ); Composite verifyPasswordButtonContainer = BaseWidgetUtils.createColumnContainer( currentPasswordContainer, 2, 1 ); verifyPasswordButton = BaseWidgetUtils.createButton( verifyPasswordButtonContainer, Messages .getString( "PasswordDialog.Verify" ), 1 ); //$NON-NLS-1$ verifyPasswordButton.setEnabled( false ); verifyPasswordButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { verifyCurrentPassword(); } } ); bindPasswordButton = BaseWidgetUtils.createButton( verifyPasswordButtonContainer, Messages .getString( "PasswordDialog.Bind" ), 1 ); //$NON-NLS-1$ bindPasswordButton.setEnabled( false ); bindPasswordButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { bindCurrentPassword(); } } ); currentTab = new TabItem( tabFolder, SWT.NONE ); currentTab.setText( Messages.getString( "PasswordDialog.CurrentPassword" ) ); //$NON-NLS-1$ currentTab.setControl( currentPasswordContainer ); } // new password newPasswordContainer = new Composite( tabFolder, SWT.NONE ); GridLayout newLayout = new GridLayout( 2, false ); newLayout.marginHeight = convertVerticalDLUsToPixels( IDialogConstants.VERTICAL_MARGIN ); newLayout.marginWidth = convertHorizontalDLUsToPixels( IDialogConstants.HORIZONTAL_MARGIN ); newLayout.verticalSpacing = convertVerticalDLUsToPixels( IDialogConstants.VERTICAL_SPACING ); newLayout.horizontalSpacing = convertHorizontalDLUsToPixels( IDialogConstants.HORIZONTAL_SPACING ); newPasswordContainer.setLayout( newLayout ); BaseWidgetUtils.createLabel( newPasswordContainer, Messages.getString( "PasswordDialog.EnterNewPassword" ), 1 ); //$NON-NLS-1$ newPasswordText = BaseWidgetUtils.createText( newPasswordContainer, "", 1 ); //$NON-NLS-1$ newPasswordText.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { updateNewPasswordGroup(); } } ); BaseWidgetUtils.createLabel( newPasswordContainer, Messages.getString( "PasswordDialog.SelectHashMethod" ), 1 ); //$NON-NLS-1$ newPasswordHashMethodCombo = BaseWidgetUtils.createReadonlyCombo( newPasswordContainer, HASH_METHODS, 0, 1 ); newPasswordHashMethodCombo.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { updateNewPasswordGroup(); } } ); BaseWidgetUtils.createLabel( newPasswordContainer, Messages.getString( "PasswordDialog.PasswordPreview" ), 1 ); //$NON-NLS-1$ newPasswordPreviewText = BaseWidgetUtils.createReadonlyText( newPasswordContainer, "", 1 ); //$NON-NLS-1$ newSaltButton = BaseWidgetUtils.createButton( newPasswordContainer, Messages .getString( "PasswordDialog.NewSalt" ), 1 ); //$NON-NLS-1$ newSaltButton.setLayoutData( new GridData() ); newSaltButton.setEnabled( false ); newSaltButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { updateNewPasswordGroup(); } } ); Composite newPasswordPreviewDetailContainer = BaseWidgetUtils .createColumnContainer( newPasswordContainer, 2, 1 ); BaseWidgetUtils.createLabel( newPasswordPreviewDetailContainer, Messages .getString( "PasswordDialog.PasswordHex" ), 1 ); //$NON-NLS-1$ newPasswordPreviewValueHexText = BaseWidgetUtils.createLabeledText( newPasswordPreviewDetailContainer, ":", 1 ); //$NON-NLS-1$ BaseWidgetUtils.createLabel( newPasswordPreviewDetailContainer, Messages.getString( "PasswordDialog.SaltHex" ), 1 ); //$NON-NLS-1$ newPasswordPreviewSaltHexText = BaseWidgetUtils.createLabeledText( newPasswordPreviewDetailContainer, "", 1 ); //$NON-NLS-1$ showNewPasswordDetailsButton = BaseWidgetUtils.createCheckbox( newPasswordPreviewDetailContainer, Messages .getString( "PasswordDialog.ShowNewPasswordDetails" ), 1 ); //$NON-NLS-1$ showNewPasswordDetailsButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { updateNewPasswordGroup(); } } ); newTab = new TabItem( tabFolder, SWT.NONE ); newTab.setText( Messages.getString( "PasswordDialog.NewPassword" ) ); //$NON-NLS-1$ newTab.setControl( newPasswordContainer ); applyDialogFont( composite ); return composite; }
diff --git a/src/plugins/Library/util/concurrent/ObjectProcessor.java b/src/plugins/Library/util/concurrent/ObjectProcessor.java index fc916cd..f0dd4da 100644 --- a/src/plugins/Library/util/concurrent/ObjectProcessor.java +++ b/src/plugins/Library/util/concurrent/ObjectProcessor.java @@ -1,331 +1,328 @@ /* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package plugins.Library.util.concurrent; import plugins.Library.util.func.Closure; import plugins.Library.util.func.SafeClosure; import static plugins.Library.util.func.Tuples.X2; // also imports the class import static plugins.Library.util.func.Tuples.X3; // also imports the class import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; /** ** A class that wraps around an {@link Executor}, for processing any given type ** of object, not just {@link Runnable}. Each object must be accompanied by a ** secondary "deposit" object, which is returned with the object when it has ** been processed. Any exceptions thrown are also returned. ** ** @param <T> Type of object to be processed ** @param <E> Type of object to be used as a deposit ** @param <X> Type of exception thrown by {@link #clo} ** @author infinity0 */ public class ObjectProcessor<T, E, X extends Exception> implements Scheduler { final protected BlockingQueue<T> in; final protected BlockingQueue<X2<T, X>> out; final protected Map<T, E> dep; final protected Closure<T, X> clo; final protected Executor exec; protected volatile boolean open = true; protected int dispatched = 0; protected int completed = 0; protected int started = 0; // TODO NORM make a more intelligent way of adjusting this final public static int maxconc = 0x28; final protected SafeClosure<X2<T, X>> postProcess = new SafeClosure<X2<T, X>>() { /*@Override**/ public void invoke(X2<T, X> res) { try { out.put(res); synchronized(ObjectProcessor.this) { ++completed; } } catch (InterruptedException e) { throw new UnsupportedOperationException(); } } }; // JDK6 replace with ConcurrentSkipListSet final private static ConcurrentMap<ObjectProcessor, Boolean> pending = new ConcurrentHashMap<ObjectProcessor, Boolean>(); // This must only be modified in a static synchronized block private static Thread auto = null; /** ** Constructs a new processor. The processor itself will be thread-safe ** as long as the queues and deposit map are not exposed to other threads, ** and the closure's invoke method is also thread-safe. ** ** If the {@code closure} parameter is {@code null}, it is expected that ** {@link #createJobFor(Object)} will be overridden appropriately. ** ** @param input Queue for input items ** @param output Queue for output/error items ** @param deposit Map for item deposits ** @param closure Closure to call on each item ** @param executor Executor to run each closure call ** @param autostart Whether to start an {@link #auto()} autohandler */ public ObjectProcessor( BlockingQueue<T> input, BlockingQueue<X2<T, X>> output, Map<T, E> deposit, Closure<T, X> closure, Executor executor ) { in = input; out = output; dep = deposit; clo = closure; exec = executor; } /** ** Safely submits the given item and deposit to the given processer. Only ** use this when the input queue's {@link BlockingQueue#put(Object)} method ** does not throw {@link InterruptedException}, such as that of {@link ** java.util.concurrent.PriorityBlockingQueue}. */ public static <T, E, X extends Exception> void submitSafe(ObjectProcessor<T, E, X> proc, T item, E deposit) { try { proc.submit(item, deposit); } catch (InterruptedException e) { throw new IllegalArgumentException("ObjectProcessor: abuse of submitSafe(). Blame the programmer, who did not know what they were doing", e); } } /** ** Submits an item for processing, with the given deposit. ** ** @throws IllegalStateException if the processor has already been {@link ** #close() closed} ** @throws IllegalArgumentException if the item is already being held */ public synchronized void submit(T item, E deposit) throws InterruptedException { if (!open) { throw new IllegalStateException("ObjectProcessor: not open"); } if (dep.containsKey(item)) { throw new IllegalArgumentException("ObjectProcessor: object " + item + " already submitted"); } dep.put(item, deposit); in.put(item); } /** ** Updates the deposit for a given item. ** ** @throws IllegalStateException if the processor has already been {@link ** #close() closed} ** @throws IllegalArgumentException if the item is not currently being held */ public synchronized void update(T item, E deposit) { if (!open) { throw new IllegalStateException("ObjectProcessor: not open"); } if (!dep.containsKey(item)) { throw new IllegalArgumentException("ObjectProcessor: object " + item + " not yet submitted"); } dep.put(item, deposit); } /** ** Retrieved a processed item, along with its deposit and any exception ** that caused processing to abort. */ public synchronized X3<T, E, X> accept() throws InterruptedException { X2<T, X> item = out.take(); return X3(item._0, dep.remove(item._0), item._1); } /** ** Whether there are any unprocessed items (including completed tasks not ** yet retrieved by the submitter). */ public synchronized boolean hasPending() { return !dep.isEmpty(); } /** ** Whether there are any completed items that have not yet been retrieved. */ public synchronized boolean hasCompleted() { return !out.isEmpty(); } /** ** Number of unprocessed tasks. */ public synchronized int size() { return dep.size(); } /** ** Retrieves an item by calling {@link BlockingQueue#take()} on the input ** queue. If this succeeds, a job is {@linkplain #createJobFor(Object) ** created} for it, and sent to {@link #exec} to be executed. ** ** This method is provided for completeness, in case anyone needs it; ** {@link #auto()} should be adequate for most purposes. ** ** @throws InterruptedExeception if interrupted whilst waiting */ public synchronized void dispatchTake() throws InterruptedException { throw new UnsupportedOperationException("not implemented"); /* * TODO NORM first needs a way of obeying maxconc T item = in.take(); exec.execute(createJobFor(item)); ++dispatched; */ } /** ** Retrieves an item by calling {@link BlockingQueue#poll()} on the input ** queue. If this succeeds, a job is {@linkplain #createJobFor(Object) ** created} for it, and sent to {@link #exec} to be executed. ** ** This method is provided for completeness, in case anyone needs it; ** {@link #auto()} should be adequate for most purposes. ** ** @return Whether a task was retrieved and executed */ public synchronized boolean dispatchPoll() { if (dispatched - completed >= maxconc) { return false; } T item = in.poll(); if (item == null) { return false; } exec.execute(createJobFor(item)); ++dispatched; return true; } /** ** Creates a {@link Runnable} to process the item and push it onto the ** output queue, along with any exception that aborted the process. ** ** The default implementation invokes {@link #clo} on the item, and then ** adds the appropriate data onto the output queue. */ protected Runnable createJobFor(final T item) { if (clo == null) { throw new IllegalStateException("ObjectProcessor: no closure given, but createJobFor() was not overidden"); } return new Runnable() { /*@Override**/ public void run() { X ex = null; synchronized(ObjectProcessor.this) { ++started; } try { clo.invoke(item); } // FIXME NORM this could throw RuntimeException catch (Exception e) { ex = (X)e; } postProcess.invoke(X2(item, ex)); } }; } /** ** Start a new thread to run the {@link #pending} processors, if one is not ** already running. */ private static synchronized void ensureAutoHandler() { if (auto != null) { return; } auto = new Thread() { @Override public void run() { final int timeout = 4; int t = timeout; while (!pending.isEmpty() && (t=timeout) == timeout || t-- > 0) { for (Iterator<ObjectProcessor> it = pending.keySet().iterator(); it.hasNext();) { ObjectProcessor proc = it.next(); try { boolean o = proc.open; while (proc.dispatchPoll()); if (!o) { it.remove(); } } catch (RejectedExecutionException e) { // FIXME NORM // neither Executors.DEFAULT_EXECUTOR nor Freenet's in-built executors // throw this, so this is not a high priority System.out.println("REJECTED EXECUTION" + e); } } try { - // sleep 2^10ms for every 2^10 processors - // TODO NORM more intelligent waiting - long sleepTime = ((pending.size()-1)>>10)+1<<10; - Thread.sleep(sleepTime); + Thread.sleep(1000); } catch (InterruptedException e) { // TODO LOW log this somewhere } // System.out.println("pending " + pending.size()); if (t > 0) { continue; } synchronized (ObjectProcessor.class) { // if auto() was called just before we entered this synchronized block, // then its ensureAutoHandler() would have done nothing. so we want to keep // this thread running to take care of the new addition. if (!pending.isEmpty()) { continue; } // otherwise we can safely discard this thread, since ensureAutoHandler() // cannot be called as long as we are in this block. auto = null; return; } } throw new AssertionError("ObjectProcessor: bad exit in autohandler. this is a bug; please report."); } }; auto.start(); } /** ** Add this processor to the collection of {@link #pending} processes, and ** makes sure there is a thread to handle them. ** ** @return Whether the processor was not already being handled. */ public boolean auto() { Boolean r = ObjectProcessor.pending.put(this, Boolean.TRUE); ObjectProcessor.ensureAutoHandler(); return r == null; } /** ** Call {@link #auto()} and return {@code this}. */ public ObjectProcessor autostart() { auto(); return this; } /** ** Stop accepting new submissions or deposit updates. Held items can still ** be processed and retrieved, and if an {@linkplain #auto() auto-handler} ** is running, it will run until all such items have been processed. */ /*@Override**/ public void close() { open = false; } // public class Object /** ** {@inheritDoc} ** ** This implementation just calls {@link #close()}. */ @Override public void finalize() { close(); } protected String name; public void setName(String n) { name = n; } @Override public String toString() { return "ObjProc-" + name + ":{" + size() + "|" + dispatched + "|" + started + "|" + completed + "}"; } }
true
true
private static synchronized void ensureAutoHandler() { if (auto != null) { return; } auto = new Thread() { @Override public void run() { final int timeout = 4; int t = timeout; while (!pending.isEmpty() && (t=timeout) == timeout || t-- > 0) { for (Iterator<ObjectProcessor> it = pending.keySet().iterator(); it.hasNext();) { ObjectProcessor proc = it.next(); try { boolean o = proc.open; while (proc.dispatchPoll()); if (!o) { it.remove(); } } catch (RejectedExecutionException e) { // FIXME NORM // neither Executors.DEFAULT_EXECUTOR nor Freenet's in-built executors // throw this, so this is not a high priority System.out.println("REJECTED EXECUTION" + e); } } try { // sleep 2^10ms for every 2^10 processors // TODO NORM more intelligent waiting long sleepTime = ((pending.size()-1)>>10)+1<<10; Thread.sleep(sleepTime); } catch (InterruptedException e) { // TODO LOW log this somewhere } // System.out.println("pending " + pending.size()); if (t > 0) { continue; } synchronized (ObjectProcessor.class) { // if auto() was called just before we entered this synchronized block, // then its ensureAutoHandler() would have done nothing. so we want to keep // this thread running to take care of the new addition. if (!pending.isEmpty()) { continue; } // otherwise we can safely discard this thread, since ensureAutoHandler() // cannot be called as long as we are in this block. auto = null; return; } } throw new AssertionError("ObjectProcessor: bad exit in autohandler. this is a bug; please report."); } }; auto.start(); }
private static synchronized void ensureAutoHandler() { if (auto != null) { return; } auto = new Thread() { @Override public void run() { final int timeout = 4; int t = timeout; while (!pending.isEmpty() && (t=timeout) == timeout || t-- > 0) { for (Iterator<ObjectProcessor> it = pending.keySet().iterator(); it.hasNext();) { ObjectProcessor proc = it.next(); try { boolean o = proc.open; while (proc.dispatchPoll()); if (!o) { it.remove(); } } catch (RejectedExecutionException e) { // FIXME NORM // neither Executors.DEFAULT_EXECUTOR nor Freenet's in-built executors // throw this, so this is not a high priority System.out.println("REJECTED EXECUTION" + e); } } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO LOW log this somewhere } // System.out.println("pending " + pending.size()); if (t > 0) { continue; } synchronized (ObjectProcessor.class) { // if auto() was called just before we entered this synchronized block, // then its ensureAutoHandler() would have done nothing. so we want to keep // this thread running to take care of the new addition. if (!pending.isEmpty()) { continue; } // otherwise we can safely discard this thread, since ensureAutoHandler() // cannot be called as long as we are in this block. auto = null; return; } } throw new AssertionError("ObjectProcessor: bad exit in autohandler. this is a bug; please report."); } }; auto.start(); }
diff --git a/src/client/SessionClient.java b/src/client/SessionClient.java index 73890a3..4dd5676 100644 --- a/src/client/SessionClient.java +++ b/src/client/SessionClient.java @@ -1,205 +1,205 @@ package client; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; import brute.Bonus; import brute.Brute; import network.Protocol; import network.Reader; import network.Writer; public class SessionClient { protected Socket socket; public SessionClient(Socket socket) throws IOException { this.socket = socket; } private boolean status(byte discriminant) { System.out.print("Client received: " + (byte) discriminant + " "); if (discriminant == Protocol.OK) { System.out.println("[OK]"); return true; } System.out.println("[KO]"); return false; } public int getLogin(String user) throws IOException { Writer w = new WriterClient(this.socket.getOutputStream()); System.out.println("Client send: " + (byte) Protocol.GET_LOGIN + " [GET_LOGIN] " + user); w.writeDiscriminant(Protocol.GET_LOGIN); w.writeString(user); w.send(); Reader r = new ReaderClient(socket.getInputStream()); byte d = r.readDiscriminant(); if (d == Protocol.REPLY_LOGIN) { int id = r.readInt(); System.out.println("Client received: " + Protocol.REPLY_LOGIN + " [REPLY_LOGIN] " + id); return id; } return -1; } public boolean query_test() throws IOException { Writer w = new WriterClient(this.socket.getOutputStream()); System.out.println("Client send: " + (byte) Protocol.QUERY_TEST + " [QUERY_TEST]"); w.writeDiscriminant(Protocol.QUERY_TEST); w.send(); Reader r = new ReaderClient(socket.getInputStream()); return status(r.readDiscriminant()); } public Brute getBruteInfo(int id) throws IOException { Writer w = new WriterClient(this.socket.getOutputStream()); System.out.println("Client send: " + (byte) Protocol.GET_BRUTE_INFO + " [GET_BRUTE_INFO] " + id); w.writeDiscriminant(Protocol.GET_BRUTE_INFO); w.writeInt(id); w.send(); Reader r = new ReaderClient(socket.getInputStream()); byte d = r.readDiscriminant(); System.out.print("Client received: " + d + " "); if (d == Protocol.REPLY_BRUTE_INFO) { System.out.print("[REPLY_BRUTE_INFO] "); String name = r.readString(); int level = r.readInt(); int life = r.readInt(); int strengh = r.readInt(); int speed = r.readInt(); System.out.println(name + " " + level + " " + life + " " + strengh + " " + speed); return new Brute(name, level, life, strengh, speed); } System.out.println("[KO]"); return null; } public ArrayList<Bonus> getBruteBonus(int id) throws IOException { Writer w = new WriterClient(this.socket.getOutputStream()); System.out.println("Client send: " + (byte) Protocol.GET_BRUTE_BONUS + " [GET_BRUTE_BONUS] " + id); w.writeDiscriminant(Protocol.GET_BRUTE_BONUS); w.writeInt(id); w.send(); Reader r = new ReaderClient(socket.getInputStream()); byte d = r.readDiscriminant(); System.out.print("Client received: " + d + " "); - if (d == Protocol.REPLY_BRUTE_INFO) { - System.out.print("[REPLY_BRUTE_INFO] "); + if (d == Protocol.REPLY_BRUTE_BONUS) { + System.out.print("[REPLY_BRUTE_BONUS] "); int size = r.readInt(); System.out.print(size + " "); ArrayList<Bonus> bonus = new ArrayList<Bonus>(); for (int i=0; i<size; i++) { String name = r.readString(); int level = r.readInt(); int life = r.readInt(); int strengh = r.readInt(); int speed = r.readInt(); System.out.print(name + " " + level + " " + life + " " + strengh + " " + speed + " "); bonus.add(new Bonus(name, level, life, strengh, speed)); } System.out.println(); return bonus; } System.out.println("[KO]"); return null; } public int getAdversaire(int me) throws IOException { Writer w = new WriterClient(this.socket.getOutputStream()); System.out.println("Client send: " + (byte) Protocol.GET_ADVERSAIRE + " [GET_ADVERSAIRE] " + me); w.writeDiscriminant(Protocol.GET_ADVERSAIRE); w.writeInt(me); w.send(); Reader r = new ReaderClient(socket.getInputStream()); byte d = r.readDiscriminant(); System.out.print("Client received: " + d + " "); if (d == Protocol.REPLY_ADVERSAIRE) { System.out.print("[REPLY_ADVERSAIRE] "); int other = r.readInt(); System.out.println(other); return other; } System.out.println("[KO]"); return -1; } public boolean getVictory(int one, int two) throws IOException { Writer w = new WriterClient(this.socket.getOutputStream()); System.out.println("Client send: " + (byte) Protocol.GET_VICTORY + " [GET_VICTORY] " + one + " " + two); w.writeDiscriminant(Protocol.GET_VICTORY); w.writeInt(one); w.writeInt(two); w.send(); Reader r = new ReaderClient(socket.getInputStream()); return status(r.readDiscriminant()); } public boolean getDefeat(int one, int two) throws IOException { Writer w = new WriterClient(this.socket.getOutputStream()); System.out.println("Client send: " + (byte) Protocol.GET_DEFEAT + " [GET_DEFEAT] " + one + " " + two); w.writeDiscriminant(Protocol.GET_DEFEAT); w.writeInt(one); w.writeInt(two); w.send(); Reader r = new ReaderClient(socket.getInputStream()); return status(r.readDiscriminant()); } public int getCombat(int one, int two) throws IOException { Writer w = new WriterClient(this.socket.getOutputStream()); System.out.println("Client send: " + (byte) Protocol.GET_COMBAT + " [GET_COMBAT] " + one + " " + two); w.writeDiscriminant(Protocol.GET_COMBAT); w.writeInt(one); w.writeInt(two); w.send(); Reader r = new ReaderClient(socket.getInputStream()); byte d = r.readDiscriminant(); System.out.print("Client received: " + d + " "); if (d == Protocol.REPLY_COMBAT) { System.out.print("[REPLY_COMBAT] "); int winner = r.readInt(); System.out.println(winner); return winner; } System.out.println("[KO]"); return -1; } }
true
true
public ArrayList<Bonus> getBruteBonus(int id) throws IOException { Writer w = new WriterClient(this.socket.getOutputStream()); System.out.println("Client send: " + (byte) Protocol.GET_BRUTE_BONUS + " [GET_BRUTE_BONUS] " + id); w.writeDiscriminant(Protocol.GET_BRUTE_BONUS); w.writeInt(id); w.send(); Reader r = new ReaderClient(socket.getInputStream()); byte d = r.readDiscriminant(); System.out.print("Client received: " + d + " "); if (d == Protocol.REPLY_BRUTE_INFO) { System.out.print("[REPLY_BRUTE_INFO] "); int size = r.readInt(); System.out.print(size + " "); ArrayList<Bonus> bonus = new ArrayList<Bonus>(); for (int i=0; i<size; i++) { String name = r.readString(); int level = r.readInt(); int life = r.readInt(); int strengh = r.readInt(); int speed = r.readInt(); System.out.print(name + " " + level + " " + life + " " + strengh + " " + speed + " "); bonus.add(new Bonus(name, level, life, strengh, speed)); } System.out.println(); return bonus; } System.out.println("[KO]"); return null; }
public ArrayList<Bonus> getBruteBonus(int id) throws IOException { Writer w = new WriterClient(this.socket.getOutputStream()); System.out.println("Client send: " + (byte) Protocol.GET_BRUTE_BONUS + " [GET_BRUTE_BONUS] " + id); w.writeDiscriminant(Protocol.GET_BRUTE_BONUS); w.writeInt(id); w.send(); Reader r = new ReaderClient(socket.getInputStream()); byte d = r.readDiscriminant(); System.out.print("Client received: " + d + " "); if (d == Protocol.REPLY_BRUTE_BONUS) { System.out.print("[REPLY_BRUTE_BONUS] "); int size = r.readInt(); System.out.print(size + " "); ArrayList<Bonus> bonus = new ArrayList<Bonus>(); for (int i=0; i<size; i++) { String name = r.readString(); int level = r.readInt(); int life = r.readInt(); int strengh = r.readInt(); int speed = r.readInt(); System.out.print(name + " " + level + " " + life + " " + strengh + " " + speed + " "); bonus.add(new Bonus(name, level, life, strengh, speed)); } System.out.println(); return bonus; } System.out.println("[KO]"); return null; }
diff --git a/gnu/testlet/java/lang/Integer/parseInt.java b/gnu/testlet/java/lang/Integer/parseInt.java index 6ca291ad..823ed214 100644 --- a/gnu/testlet/java/lang/Integer/parseInt.java +++ b/gnu/testlet/java/lang/Integer/parseInt.java @@ -1,136 +1,137 @@ /* Copyright (C) 2002 Free Software Foundation, Inc. * Written by Mark Wielaard <mark@klomp.org> * * This file is part of Mauve. * * Mauve is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * Mauve is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Mauve; see the file COPYING. If not, write to * the Free Software Foundation, 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ // Tags: JDK1.1 package gnu.testlet.java.lang.Integer; import gnu.testlet.Testlet; import gnu.testlet.TestHarness; public class parseInt implements Testlet { public void test(TestHarness harness) { int i; i = Integer.parseInt("0"); harness.check(i, 0); i = Integer.parseInt("1"); harness.check(i, 1); i = Integer.parseInt("000"); harness.check(i, 0); i = Integer.parseInt("007"); harness.check(i, 7); i = Integer.parseInt("-0"); harness.check(i, 0); i = Integer.parseInt("-1"); harness.check(i, -1); i = Integer.parseInt("-2147483648"); harness.check(i, Integer.MIN_VALUE); i = Integer.parseInt("2147483647"); harness.check(i, Integer.MAX_VALUE); try { i = Integer.parseInt("-2147483649"); harness.fail("-2147483649 is to small for an int"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt("2147483648"); harness.fail("2147483648 is to big for an int"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt("abc"); harness.fail("Illegal input (abc) must throw NumberFormatException"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt("-"); harness.fail("Single '-' must throw NumberFormatException"); } catch (NumberFormatException nfe) { harness.check(true); } + // In JDK1.7, '+' is considered a valid character. try { i = Integer.parseInt("+10"); - harness.fail("Leading '+' must throw NumberFormatException"); + harness.check(true); } catch (NumberFormatException nfe) { - harness.check(true); + harness.fail("Leading '+' does not throw NumberFormatException"); } try { i = Integer.parseInt(null); harness.fail("null input must throw NumberFormatException"); } catch (NullPointerException npe) { harness.fail("null input must throw NumberFormatException, not NullPointerException"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt(""); harness.fail("empty input must throw NumberFormatException"); } catch (IndexOutOfBoundsException ioobe) { harness.fail("empty input must throw NumberFormatException, not IndexOutOfBoundsException"); } catch (NumberFormatException nfe) { harness.check(true); } } }
false
true
public void test(TestHarness harness) { int i; i = Integer.parseInt("0"); harness.check(i, 0); i = Integer.parseInt("1"); harness.check(i, 1); i = Integer.parseInt("000"); harness.check(i, 0); i = Integer.parseInt("007"); harness.check(i, 7); i = Integer.parseInt("-0"); harness.check(i, 0); i = Integer.parseInt("-1"); harness.check(i, -1); i = Integer.parseInt("-2147483648"); harness.check(i, Integer.MIN_VALUE); i = Integer.parseInt("2147483647"); harness.check(i, Integer.MAX_VALUE); try { i = Integer.parseInt("-2147483649"); harness.fail("-2147483649 is to small for an int"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt("2147483648"); harness.fail("2147483648 is to big for an int"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt("abc"); harness.fail("Illegal input (abc) must throw NumberFormatException"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt("-"); harness.fail("Single '-' must throw NumberFormatException"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt("+10"); harness.fail("Leading '+' must throw NumberFormatException"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt(null); harness.fail("null input must throw NumberFormatException"); } catch (NullPointerException npe) { harness.fail("null input must throw NumberFormatException, not NullPointerException"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt(""); harness.fail("empty input must throw NumberFormatException"); } catch (IndexOutOfBoundsException ioobe) { harness.fail("empty input must throw NumberFormatException, not IndexOutOfBoundsException"); } catch (NumberFormatException nfe) { harness.check(true); } }
public void test(TestHarness harness) { int i; i = Integer.parseInt("0"); harness.check(i, 0); i = Integer.parseInt("1"); harness.check(i, 1); i = Integer.parseInt("000"); harness.check(i, 0); i = Integer.parseInt("007"); harness.check(i, 7); i = Integer.parseInt("-0"); harness.check(i, 0); i = Integer.parseInt("-1"); harness.check(i, -1); i = Integer.parseInt("-2147483648"); harness.check(i, Integer.MIN_VALUE); i = Integer.parseInt("2147483647"); harness.check(i, Integer.MAX_VALUE); try { i = Integer.parseInt("-2147483649"); harness.fail("-2147483649 is to small for an int"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt("2147483648"); harness.fail("2147483648 is to big for an int"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt("abc"); harness.fail("Illegal input (abc) must throw NumberFormatException"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt("-"); harness.fail("Single '-' must throw NumberFormatException"); } catch (NumberFormatException nfe) { harness.check(true); } // In JDK1.7, '+' is considered a valid character. try { i = Integer.parseInt("+10"); harness.check(true); } catch (NumberFormatException nfe) { harness.fail("Leading '+' does not throw NumberFormatException"); } try { i = Integer.parseInt(null); harness.fail("null input must throw NumberFormatException"); } catch (NullPointerException npe) { harness.fail("null input must throw NumberFormatException, not NullPointerException"); } catch (NumberFormatException nfe) { harness.check(true); } try { i = Integer.parseInt(""); harness.fail("empty input must throw NumberFormatException"); } catch (IndexOutOfBoundsException ioobe) { harness.fail("empty input must throw NumberFormatException, not IndexOutOfBoundsException"); } catch (NumberFormatException nfe) { harness.check(true); } }
diff --git a/src/main/java/org/jenkinsci/plugins/buildresulttrigger/BuildResultTrigger.java b/src/main/java/org/jenkinsci/plugins/buildresulttrigger/BuildResultTrigger.java index c6946e3..4edf9d0 100644 --- a/src/main/java/org/jenkinsci/plugins/buildresulttrigger/BuildResultTrigger.java +++ b/src/main/java/org/jenkinsci/plugins/buildresulttrigger/BuildResultTrigger.java @@ -1,232 +1,232 @@ package org.jenkinsci.plugins.buildresulttrigger; import antlr.ANTLRException; import hudson.Extension; import hudson.matrix.MatrixConfiguration; import hudson.model.*; import hudson.security.ACL; import hudson.util.SequentialExecutionQueue; import org.acegisecurity.context.SecurityContext; import org.acegisecurity.context.SecurityContextHolder; import org.jenkinsci.lib.xtrigger.AbstractTriggerByFullContext; import org.jenkinsci.lib.xtrigger.XTriggerDescriptor; import org.jenkinsci.lib.xtrigger.XTriggerException; import org.jenkinsci.lib.xtrigger.XTriggerLog; import org.jenkinsci.plugins.buildresulttrigger.model.BuildResultTriggerInfo; import org.jenkinsci.plugins.buildresulttrigger.model.CheckedResult; import org.kohsuke.stapler.DataBoundConstructor; import java.io.File; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author Gregory Boissinot */ public class BuildResultTrigger extends AbstractTriggerByFullContext<BuildResultTriggerContext> { private BuildResultTriggerInfo[] jobsInfo = new BuildResultTriggerInfo[0]; @DataBoundConstructor public BuildResultTrigger(String cronTabSpec, BuildResultTriggerInfo[] jobsInfo) throws ANTLRException { super(cronTabSpec); this.jobsInfo = jobsInfo; } @SuppressWarnings("unused") public BuildResultTriggerInfo[] getJobsInfo() { return jobsInfo; } public File getLogFile() { return new File(job.getRootDir(), "buildResultTrigger-polling.log"); } @Override public Collection<? extends Action> getProjectActions() { BuildResultTriggerAction action = new BuildResultTriggerAction((AbstractProject) job, getLogFile(), getDescriptor().getDisplayName()); return Collections.singleton(action); } @Override protected boolean requiresWorkspaceForPolling() { return false; } @Override protected String getName() { return "BuildResultTrigger"; } @Override protected Action[] getScheduledActions(Node node, XTriggerLog log) { return new Action[0]; } @Override protected String getCause() { return "A change to build result"; } @Override public boolean isContextOnStartupFetched() { return true; } @Override protected BuildResultTriggerContext getContext(Node node, XTriggerLog log) throws XTriggerException { Map<String, Integer> contextResults = new HashMap<String, Integer>(); SecurityContext securityContext = ACL.impersonate(ACL.SYSTEM); try { for (BuildResultTriggerInfo info : jobsInfo) { String jobName = info.getJobName(); AbstractProject job = Hudson.getInstance().getItemByFullName(jobName, AbstractProject.class); if (isValidBuildResultProject(job)) { Run lastBuild = job.getLastBuild(); if (lastBuild != null) { int buildNumber = lastBuild.getNumber(); if (buildNumber != 0) { contextResults.put(jobName, buildNumber); } } } } } finally { SecurityContextHolder.setContext(securityContext); } return new BuildResultTriggerContext(contextResults); } private boolean isValidBuildResultProject(AbstractProject item) { if (item == null) { return false; } if (item instanceof MatrixConfiguration) { return false; } return true; } @Override protected boolean checkIfModified(BuildResultTriggerContext oldContext, BuildResultTriggerContext newContext, XTriggerLog log) throws XTriggerException { SecurityContext securityContext = ACL.impersonate(ACL.SYSTEM); try { for (BuildResultTriggerInfo info : jobsInfo) { boolean atLeastOneModification = checkIfModifiedJob(info, oldContext, newContext, log); if (atLeastOneModification) { log.info(String.format("Job %s is modified. Triggering a new build.", info.getJobName())); return true; } } } finally { SecurityContextHolder.setContext(securityContext); } return false; } private boolean checkIfModifiedJob(BuildResultTriggerInfo configuredTriggerJobInfo, BuildResultTriggerContext oldContext, BuildResultTriggerContext newContext, XTriggerLog log) throws XTriggerException { String jobName = configuredTriggerJobInfo.getJobName(); log.info(String.format("Checking changes for job %s.", jobName)); final Map<String, Integer> oldContextResults = oldContext.getResults(); final Map<String, Integer> newContextResults = newContext.getResults(); if (newContextResults == null || newContextResults.size() == 0) { log.info(String.format("No new builds to check for the job %s", jobName)); return false; } if (newContextResults.size() != oldContextResults.size()) { return isMatchingExpectedResults(configuredTriggerJobInfo, log); } Integer newLastBuildNumber = newContextResults.get(jobName); - if (newLastBuildNumber == null || newLastBuildNumber == 0) { + if (newLastBuildNumber == null || newLastBuildNumber.intValue() == 0) { log.info(String.format("The job %s doesn't have any new builds.", jobName)); return false; } Integer oldLastBuildNumber = oldContextResults.get(jobName); - if (oldLastBuildNumber == null || oldLastBuildNumber == 0) { + if (oldLastBuildNumber == null || oldLastBuildNumber.intValue() == 0) { return isMatchingExpectedResults(configuredTriggerJobInfo, log); } //Process if there is a new build between now and previous polling - if (newLastBuildNumber == 0 || newLastBuildNumber != oldLastBuildNumber) { + if (newLastBuildNumber.intValue() == 0 || newLastBuildNumber.intValue() != oldLastBuildNumber.intValue()) { return isMatchingExpectedResults(configuredTriggerJobInfo, log); } log.info(String.format("There are no new builds for the job %s.", jobName)); return false; } private boolean isMatchingExpectedResults(BuildResultTriggerInfo configuredTriggerJobInfo, XTriggerLog log) { String jobName = configuredTriggerJobInfo.getJobName(); CheckedResult[] expectedResults = configuredTriggerJobInfo.getCheckedResults(); log.info(String.format("There is at least one new build for the job %s. Checking expected job build results.", jobName)); if (expectedResults == null || expectedResults.length == 0) { log.info("No results to check. You have to specify at least one expected build result in the build-result trigger configuration."); return false; } AbstractProject jobObj = Hudson.getInstance().getItemByFullName(jobName, AbstractProject.class); Run jobObjLastBuild = jobObj.getLastBuild(); Result jobObjectLastResult = jobObjLastBuild.getResult(); for (CheckedResult checkedResult : expectedResults) { log.info(String.format("Checking %s", checkedResult.getResult().toString())); if (checkedResult.getResult().ordinal == jobObjectLastResult.ordinal) { log.info(String.format("Last build result for the job %s matches the expected result %s.", jobName, jobObjectLastResult)); return true; } } return false; } @Extension @SuppressWarnings("unused") public static class BuildResultTriggerDescriptor extends XTriggerDescriptor { private transient final SequentialExecutionQueue queue = new SequentialExecutionQueue(Executors.newSingleThreadExecutor()); public ExecutorService getExecutor() { return queue.getExecutors(); } @Override public boolean isApplicable(Item item) { return true; } @Override public String getDisplayName() { return "[BuildResultTrigger] - Monitor build results of other jobs"; } @Override public String getHelpFile() { return "/plugin/buildresult-trigger/help.html"; } } }
false
true
private boolean checkIfModifiedJob(BuildResultTriggerInfo configuredTriggerJobInfo, BuildResultTriggerContext oldContext, BuildResultTriggerContext newContext, XTriggerLog log) throws XTriggerException { String jobName = configuredTriggerJobInfo.getJobName(); log.info(String.format("Checking changes for job %s.", jobName)); final Map<String, Integer> oldContextResults = oldContext.getResults(); final Map<String, Integer> newContextResults = newContext.getResults(); if (newContextResults == null || newContextResults.size() == 0) { log.info(String.format("No new builds to check for the job %s", jobName)); return false; } if (newContextResults.size() != oldContextResults.size()) { return isMatchingExpectedResults(configuredTriggerJobInfo, log); } Integer newLastBuildNumber = newContextResults.get(jobName); if (newLastBuildNumber == null || newLastBuildNumber == 0) { log.info(String.format("The job %s doesn't have any new builds.", jobName)); return false; } Integer oldLastBuildNumber = oldContextResults.get(jobName); if (oldLastBuildNumber == null || oldLastBuildNumber == 0) { return isMatchingExpectedResults(configuredTriggerJobInfo, log); } //Process if there is a new build between now and previous polling if (newLastBuildNumber == 0 || newLastBuildNumber != oldLastBuildNumber) { return isMatchingExpectedResults(configuredTriggerJobInfo, log); } log.info(String.format("There are no new builds for the job %s.", jobName)); return false; }
private boolean checkIfModifiedJob(BuildResultTriggerInfo configuredTriggerJobInfo, BuildResultTriggerContext oldContext, BuildResultTriggerContext newContext, XTriggerLog log) throws XTriggerException { String jobName = configuredTriggerJobInfo.getJobName(); log.info(String.format("Checking changes for job %s.", jobName)); final Map<String, Integer> oldContextResults = oldContext.getResults(); final Map<String, Integer> newContextResults = newContext.getResults(); if (newContextResults == null || newContextResults.size() == 0) { log.info(String.format("No new builds to check for the job %s", jobName)); return false; } if (newContextResults.size() != oldContextResults.size()) { return isMatchingExpectedResults(configuredTriggerJobInfo, log); } Integer newLastBuildNumber = newContextResults.get(jobName); if (newLastBuildNumber == null || newLastBuildNumber.intValue() == 0) { log.info(String.format("The job %s doesn't have any new builds.", jobName)); return false; } Integer oldLastBuildNumber = oldContextResults.get(jobName); if (oldLastBuildNumber == null || oldLastBuildNumber.intValue() == 0) { return isMatchingExpectedResults(configuredTriggerJobInfo, log); } //Process if there is a new build between now and previous polling if (newLastBuildNumber.intValue() == 0 || newLastBuildNumber.intValue() != oldLastBuildNumber.intValue()) { return isMatchingExpectedResults(configuredTriggerJobInfo, log); } log.info(String.format("There are no new builds for the job %s.", jobName)); return false; }
diff --git a/mmstudio/src/org/micromanager/acquisition/MMImageCache.java b/mmstudio/src/org/micromanager/acquisition/MMImageCache.java index 9cfeebe61..77cc9cdfb 100644 --- a/mmstudio/src/org/micromanager/acquisition/MMImageCache.java +++ b/mmstudio/src/org/micromanager/acquisition/MMImageCache.java @@ -1,228 +1,229 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.micromanager.acquisition; import java.lang.ref.SoftReference; import org.micromanager.api.TaggedImageStorage; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import mmcorej.TaggedImage; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMException; import org.micromanager.utils.ReportingUtils; /** * * @author arthur */ public class MMImageCache implements TaggedImageStorage { private TaggedImageStorage imageFileManager_; private Set<String> changingKeys_; private JSONObject firstTags_; private static ImageCollection coll_; MMImageCache(TaggedImageStorage imageFileManager) { imageFileManager_ = imageFileManager; changingKeys_ = new HashSet<String>(); if (coll_ == null) { coll_ = new ImageCollection(); } } public void finished() { imageFileManager_.finished(); } public void setDisplaySettings(JSONObject settings) { imageFileManager_.setDisplaySettings(settings); } public JSONObject getDisplaySettings() { return imageFileManager_.getDisplaySettings(); } public void close() { imageFileManager_.close(); } private class ImageCollection { private ConcurrentLinkedQueue<String> LabelQueue_; private Set<String> LabelSet_; private HashMap<String, SoftReference> taggedImgTable_; public ImageCollection() { LabelQueue_ = new ConcurrentLinkedQueue<String>(); taggedImgTable_ = new HashMap<String, SoftReference>(); LabelSet_ = new HashSet<String>(); } public void add(MMImageCache cache, TaggedImage taggedImage) { String label = MDUtils.getLabel(taggedImage.tags) + "/" + cache.hashCode(); taggedImgTable_.put(label, new SoftReference(taggedImage)); LabelQueue_.add(label); LabelSet_.add(label); } public TaggedImage get(MMImageCache cache, String label) { label += "/" + cache.hashCode(); LabelQueue_.remove(label); LabelQueue_.add(label); SoftReference ref = taggedImgTable_.get(label); if (ref == null) return null; else return (TaggedImage) ref.get(); } public Set<String> getLabels(MMImageCache cache) { String hashCode = Long.toString(cache.hashCode()); Set labelSubSet = new HashSet<String>(); for (String label: LabelSet_) { if (label.endsWith(hashCode)) { labelSubSet.add(label.split("/")[0]); } } return labelSubSet; } } public void saveAs(TaggedImageStorage newImageFileManager) { if (newImageFileManager == null) { return; } for (String label : coll_.getLabels(this)) { int pos[] = MDUtils.getIndices(label); try { newImageFileManager.putImage(getImage(pos[0], pos[1], pos[2], pos[3])); } catch (MMException ex) { ReportingUtils.logError(ex); } } newImageFileManager.setComment(this.getComment()); newImageFileManager.finished(); imageFileManager_ = newImageFileManager; } public String putImage(TaggedImage taggedImg) { try { coll_.add(this, taggedImg); taggedImg.tags.put("Summary",imageFileManager_.getSummaryMetadata()); checkForChangingTags(taggedImg); return imageFileManager_.putImage(taggedImg); } catch (Exception ex) { ReportingUtils.logError(ex); return null; } } public TaggedImage getImage(int channel, int slice, int frame, int position) { String label = MDUtils.generateLabel(channel, slice, frame, position); TaggedImage taggedImg = coll_.get(this, label); if (taggedImg == null) { taggedImg = imageFileManager_.getImage(channel, slice, frame, position); if (taggedImg != null) { checkForChangingTags(taggedImg); coll_.add(this, taggedImg); } } return taggedImg; } private void checkForChangingTags(TaggedImage taggedImg) { if (firstTags_ == null) { firstTags_ = taggedImg.tags; } else { Iterator<String> keys = taggedImg.tags.keys(); while (keys.hasNext()) { String key = keys.next(); try { - if (!firstTags_.has(key) - || !firstTags_.getString(key).contentEquals(taggedImg.tags.getString(key))) { + if (!firstTags_.has(key)) + changingKeys_.add(key); + else if (!firstTags_.getString(key).contentEquals(taggedImg.tags.getString(key))) { changingKeys_.add(key); } } catch (Exception e) { ReportingUtils.logError(e); } } } } private JSONObject getCommentsJSONObject() { JSONObject comments; try { comments = imageFileManager_.getDisplaySettings().getJSONObject("Comments"); } catch (JSONException ex) { comments = new JSONObject(); try { imageFileManager_.getDisplaySettings().put("Comments", comments); } catch (JSONException ex1) { ReportingUtils.logError(ex1); } } return comments; } public void setComment(String text) { JSONObject comments = getCommentsJSONObject(); try { comments.put("Summary", text); } catch (JSONException ex) { ReportingUtils.logError(ex); } } void setImageComment(String comment, JSONObject tags) { JSONObject comments = getCommentsJSONObject(); String label = MDUtils.getLabel(tags); try { comments.put(label,comment); } catch (JSONException ex) { ReportingUtils.logError(ex); } } String getImageComment(JSONObject tags) { if (tags == null) return ""; try { String label = MDUtils.getLabel(tags); return getCommentsJSONObject().getString(label); } catch (Exception ex) { return ""; } } public String getComment() { try { return getCommentsJSONObject().getString("Summary"); } catch (Exception ex) { return ""; } } public JSONObject getSummaryMetadata() { return imageFileManager_.getSummaryMetadata(); } public void setSummaryMetadata(JSONObject tags) { imageFileManager_.setSummaryMetadata(tags); imageFileManager_.setDisplaySettings(MDUtils.getDisplaySettingsFromSummary(tags)); } public Set<String> getChangingKeys() { return changingKeys_; } }
true
true
private void checkForChangingTags(TaggedImage taggedImg) { if (firstTags_ == null) { firstTags_ = taggedImg.tags; } else { Iterator<String> keys = taggedImg.tags.keys(); while (keys.hasNext()) { String key = keys.next(); try { if (!firstTags_.has(key) || !firstTags_.getString(key).contentEquals(taggedImg.tags.getString(key))) { changingKeys_.add(key); } } catch (Exception e) { ReportingUtils.logError(e); } } } }
private void checkForChangingTags(TaggedImage taggedImg) { if (firstTags_ == null) { firstTags_ = taggedImg.tags; } else { Iterator<String> keys = taggedImg.tags.keys(); while (keys.hasNext()) { String key = keys.next(); try { if (!firstTags_.has(key)) changingKeys_.add(key); else if (!firstTags_.getString(key).contentEquals(taggedImg.tags.getString(key))) { changingKeys_.add(key); } } catch (Exception e) { ReportingUtils.logError(e); } } } }
diff --git a/src/com/discretelab/fantasycard/MainActivity.java b/src/com/discretelab/fantasycard/MainActivity.java index 9d3c6e9..ae84012 100644 --- a/src/com/discretelab/fantasycard/MainActivity.java +++ b/src/com/discretelab/fantasycard/MainActivity.java @@ -1,159 +1,159 @@ package com.discretelab.fantasycard; import com.discretelab.cardinfo.CardInfo; import android.app.Activity; import android.graphics.Color; import android.graphics.Rect; import android.os.Bundle; import android.util.DisplayMetrics; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public class MainActivity extends Activity { private MyCardSlotViewGroup mySlotView; private DeckManager mDeckManager; private CardInfo[] mMyHands = new CardInfo[3]; private TextView mtxtTurnCnt; private TextView mtxtManaCnt; private TextView mtxtLifeCnt; private ImageView[] mImgMyCard = new ImageView[3]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); appOnAttachedToWindow(); } public void init() { setDensity(); appOnAttachedToWindow(); mySlotView = (MyCardSlotViewGroup)findViewById(R.id.myslotview); ///TurnCount初期化 mtxtTurnCnt = new TextView(this); mtxtTurnCnt.setTextColor(Color.rgb(246, 196, 5)); mtxtTurnCnt.setText("Turn : 0"); mySlotView.addView(mtxtTurnCnt); RelativeLayout.LayoutParams turnparams = (RelativeLayout.LayoutParams) mtxtTurnCnt.getLayoutParams(); - mtxtTurnCnt.setLayoutParams(UILayoutParams.changeMargin(turnparams, new Rect(10, 45, 10, 35))); + mtxtTurnCnt.setLayoutParams(UILayoutParams.changeMargin(turnparams, new Rect(10, 5, 10, 35))); ///ManaCount初期化 mtxtManaCnt = new TextView(this); mtxtManaCnt.setTextColor(Color.rgb(246, 196, 5)); mtxtManaCnt.setText("Mana : 0"); mySlotView.addView(mtxtManaCnt); RelativeLayout.LayoutParams manaparams = (RelativeLayout.LayoutParams) mtxtManaCnt.getLayoutParams(); - mtxtManaCnt.setLayoutParams(UILayoutParams.changeMargin(manaparams, new Rect(100, 45, 10, 35))); + mtxtManaCnt.setLayoutParams(UILayoutParams.changeMargin(manaparams, new Rect(100, 5, 10, 35))); ///LifeCount初期化 mtxtLifeCnt = new TextView(this); mtxtLifeCnt.setTextColor(Color.rgb(246, 196, 5)); mtxtLifeCnt.setText("Life : 0"); mySlotView.addView(mtxtLifeCnt); RelativeLayout.LayoutParams lifeparams = (RelativeLayout.LayoutParams) mtxtLifeCnt.getLayoutParams(); - mtxtLifeCnt.setLayoutParams(UILayoutParams.changeMargin(lifeparams, new Rect(210, 45, 10, 35))); + mtxtLifeCnt.setLayoutParams(UILayoutParams.changeMargin(lifeparams, new Rect(210, 5, 10, 35))); mDeckManager = new DeckManager(); mDeckManager.init(); drawCard(); } private void drawCard(){ for(int i=0;i<3;i++){ if(mMyHands[i] == null){ mMyHands[i] = mDeckManager.getCardfromDeck(); ImageView cardImgView = getCardImageView(mMyHands[i]); mySlotView.addView(cardImgView); RelativeLayout.LayoutParams lifeparams = (RelativeLayout.LayoutParams) cardImgView.getLayoutParams(); cardImgView.setLayoutParams(UILayoutParams.changeRect(lifeparams, new Rect(12 + (i*90), 430, 70, 90))); mImgMyCard[i] = cardImgView; } } } private ImageView getCardImageView(CardInfo cardinfo) { ImageView cardimg = new ImageView(this); switch(cardinfo.card_id){ case 1: cardimg.setBackgroundDrawable(getResources().getDrawable(R.drawable.element1)); break; case 2: cardimg.setBackgroundDrawable(getResources().getDrawable(R.drawable.element2)); break; case 3: cardimg.setBackgroundDrawable(getResources().getDrawable(R.drawable.element3)); break; case 4: cardimg.setBackgroundDrawable(getResources().getDrawable(R.drawable.card_1_1)); break; case 5: cardimg.setBackgroundDrawable(getResources().getDrawable(R.drawable.card_1_2)); break; case 6: cardimg.setBackgroundDrawable(getResources().getDrawable(R.drawable.card_1_3)); break; case 7: cardimg.setBackgroundDrawable(getResources().getDrawable(R.drawable.card_2_1)); break; case 8: cardimg.setBackgroundDrawable(getResources().getDrawable(R.drawable.card_2_2)); break; case 9: cardimg.setBackgroundDrawable(getResources().getDrawable(R.drawable.card_2_3)); break; case 10: cardimg.setBackgroundDrawable(getResources().getDrawable(R.drawable.card_3_1)); break; } return cardimg; } /** * viewport 設定処理 */ private void setDensity() { DisplayMetrics dm = getResources().getDisplayMetrics(); float wdp = dm.widthPixels / dm.density; if(wdp > 720) wdp = 720; UILayoutParams.DENSITY_DPI = Math.floor(320 * 160 / wdp); if(UILayoutParams.DENSITY_DPI > 160) UILayoutParams.DENSITY_DPI = 160; } /** * 画面表示時に端末のdp設定処理 */ private void appOnAttachedToWindow() { DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int px = getWindowManager().getDefaultDisplay().getWidth(); float dp = px / getResources().getDisplayMetrics().density; if(dp > 720 ){ UILayoutParams.SCALED_DENSITY = (float) ((720f / 320f) * metrics.scaledDensity); }else{ UILayoutParams.SCALED_DENSITY = (float) (dp / 320) * metrics.scaledDensity; } } }
false
true
public void init() { setDensity(); appOnAttachedToWindow(); mySlotView = (MyCardSlotViewGroup)findViewById(R.id.myslotview); ///TurnCount初期化 mtxtTurnCnt = new TextView(this); mtxtTurnCnt.setTextColor(Color.rgb(246, 196, 5)); mtxtTurnCnt.setText("Turn : 0"); mySlotView.addView(mtxtTurnCnt); RelativeLayout.LayoutParams turnparams = (RelativeLayout.LayoutParams) mtxtTurnCnt.getLayoutParams(); mtxtTurnCnt.setLayoutParams(UILayoutParams.changeMargin(turnparams, new Rect(10, 45, 10, 35))); ///ManaCount初期化 mtxtManaCnt = new TextView(this); mtxtManaCnt.setTextColor(Color.rgb(246, 196, 5)); mtxtManaCnt.setText("Mana : 0"); mySlotView.addView(mtxtManaCnt); RelativeLayout.LayoutParams manaparams = (RelativeLayout.LayoutParams) mtxtManaCnt.getLayoutParams(); mtxtManaCnt.setLayoutParams(UILayoutParams.changeMargin(manaparams, new Rect(100, 45, 10, 35))); ///LifeCount初期化 mtxtLifeCnt = new TextView(this); mtxtLifeCnt.setTextColor(Color.rgb(246, 196, 5)); mtxtLifeCnt.setText("Life : 0"); mySlotView.addView(mtxtLifeCnt); RelativeLayout.LayoutParams lifeparams = (RelativeLayout.LayoutParams) mtxtLifeCnt.getLayoutParams(); mtxtLifeCnt.setLayoutParams(UILayoutParams.changeMargin(lifeparams, new Rect(210, 45, 10, 35))); mDeckManager = new DeckManager(); mDeckManager.init(); drawCard(); }
public void init() { setDensity(); appOnAttachedToWindow(); mySlotView = (MyCardSlotViewGroup)findViewById(R.id.myslotview); ///TurnCount初期化 mtxtTurnCnt = new TextView(this); mtxtTurnCnt.setTextColor(Color.rgb(246, 196, 5)); mtxtTurnCnt.setText("Turn : 0"); mySlotView.addView(mtxtTurnCnt); RelativeLayout.LayoutParams turnparams = (RelativeLayout.LayoutParams) mtxtTurnCnt.getLayoutParams(); mtxtTurnCnt.setLayoutParams(UILayoutParams.changeMargin(turnparams, new Rect(10, 5, 10, 35))); ///ManaCount初期化 mtxtManaCnt = new TextView(this); mtxtManaCnt.setTextColor(Color.rgb(246, 196, 5)); mtxtManaCnt.setText("Mana : 0"); mySlotView.addView(mtxtManaCnt); RelativeLayout.LayoutParams manaparams = (RelativeLayout.LayoutParams) mtxtManaCnt.getLayoutParams(); mtxtManaCnt.setLayoutParams(UILayoutParams.changeMargin(manaparams, new Rect(100, 5, 10, 35))); ///LifeCount初期化 mtxtLifeCnt = new TextView(this); mtxtLifeCnt.setTextColor(Color.rgb(246, 196, 5)); mtxtLifeCnt.setText("Life : 0"); mySlotView.addView(mtxtLifeCnt); RelativeLayout.LayoutParams lifeparams = (RelativeLayout.LayoutParams) mtxtLifeCnt.getLayoutParams(); mtxtLifeCnt.setLayoutParams(UILayoutParams.changeMargin(lifeparams, new Rect(210, 5, 10, 35))); mDeckManager = new DeckManager(); mDeckManager.init(); drawCard(); }
diff --git a/seedboxer-web/src/main/java/net/seedboxer/web/controller/rs/TorrentsAPI.java b/seedboxer-web/src/main/java/net/seedboxer/web/controller/rs/TorrentsAPI.java index d145250..f6a6cba 100644 --- a/seedboxer-web/src/main/java/net/seedboxer/web/controller/rs/TorrentsAPI.java +++ b/seedboxer-web/src/main/java/net/seedboxer/web/controller/rs/TorrentsAPI.java @@ -1,65 +1,66 @@ /******************************************************************************* * TorrentsAPI.java * * Copyright (c) 2012 SeedBoxer Team. * * This file is part of SeedBoxer. * * SeedBoxer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SeedBoxer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SeedBoxer. If not, see <http ://www.gnu.org/licenses/>. ******************************************************************************/ package net.seedboxer.web.controller.rs; import net.seedboxer.web.service.DownloadsService; import net.seedboxer.web.type.api.APIResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; /** * WebService that expose method to work with torrent files * @author Jorge Davison (jdavisonc) * */ @Controller @RequestMapping("/webservices/torrents") public class TorrentsAPI extends SeedBoxerAPI { private static final Logger LOGGER = LoggerFactory.getLogger(TorrentsAPI.class); @Autowired private DownloadsService controller; @RequestMapping(value="add", method = RequestMethod.POST) public @ResponseBody APIResponse addTorrent(@RequestPart("file") MultipartFile file) { try { - if (file.getName().endsWith(".torrent")) { - controller.addTorrent(getUser(), file.getName(), file.getInputStream()); + String filename = file.getOriginalFilename(); + if (filename.endsWith(".torrent")) { + controller.addTorrent(getUser(), filename, file.getInputStream()); return APIResponse.createSuccessfulResponse(); } else { return APIResponse.createErrorResponse("Wrong file type, only accept .torrent files"); } } catch (Exception e) { LOGGER.error("Can not read list of downloads", e); return APIResponse.createErrorResponse("Can not put to download"); } } }
true
true
public @ResponseBody APIResponse addTorrent(@RequestPart("file") MultipartFile file) { try { if (file.getName().endsWith(".torrent")) { controller.addTorrent(getUser(), file.getName(), file.getInputStream()); return APIResponse.createSuccessfulResponse(); } else { return APIResponse.createErrorResponse("Wrong file type, only accept .torrent files"); } } catch (Exception e) { LOGGER.error("Can not read list of downloads", e); return APIResponse.createErrorResponse("Can not put to download"); } }
public @ResponseBody APIResponse addTorrent(@RequestPart("file") MultipartFile file) { try { String filename = file.getOriginalFilename(); if (filename.endsWith(".torrent")) { controller.addTorrent(getUser(), filename, file.getInputStream()); return APIResponse.createSuccessfulResponse(); } else { return APIResponse.createErrorResponse("Wrong file type, only accept .torrent files"); } } catch (Exception e) { LOGGER.error("Can not read list of downloads", e); return APIResponse.createErrorResponse("Can not put to download"); } }
diff --git a/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/AddIndividual.java b/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/AddIndividual.java index abaced126..6655420de 100644 --- a/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/AddIndividual.java +++ b/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/AddIndividual.java @@ -1,306 +1,308 @@ /* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenFlexo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.foundation.viewpoint; import java.lang.reflect.Type; import java.util.Vector; import java.util.logging.Logger; import org.openflexo.antar.binding.DataBinding; import org.openflexo.foundation.ontology.IFlexoOntologyClass; import org.openflexo.foundation.ontology.IFlexoOntologyIndividual; import org.openflexo.foundation.ontology.IndividualOfClass; import org.openflexo.foundation.technologyadapter.FlexoMetaModel; import org.openflexo.foundation.technologyadapter.FlexoModel; import org.openflexo.foundation.validation.FixProposal; import org.openflexo.foundation.validation.ValidationError; import org.openflexo.foundation.validation.ValidationIssue; import org.openflexo.foundation.validation.ValidationRule; import org.openflexo.foundation.viewpoint.ViewPointObject.FMLRepresentationContext.FMLRepresentationOutput; import org.openflexo.logging.FlexoLogger; import org.openflexo.toolbox.StringUtils; public abstract class AddIndividual<M extends FlexoModel<M, MM>, MM extends FlexoMetaModel<MM>, T extends IFlexoOntologyIndividual> extends AddConcept<M, MM, T> { protected static final Logger logger = FlexoLogger.getLogger(AddIndividual.class.getPackage().getName()); private Vector<DataPropertyAssertion> dataAssertions; private Vector<ObjectPropertyAssertion> objectAssertions; private String ontologyClassURI = null; private DataBinding<String> individualName; public AddIndividual(VirtualModel.VirtualModelBuilder builder) { super(builder); dataAssertions = new Vector<DataPropertyAssertion>(); objectAssertions = new Vector<ObjectPropertyAssertion>(); } @Override public String getFMLRepresentation(FMLRepresentationContext context) { FMLRepresentationOutput out = new FMLRepresentationOutput(context); if (getAssignation().isSet()) { out.append(getAssignation().toString() + " = (", context); } out.append(getClass().getSimpleName() + (getOntologyClass() != null ? " conformTo " + getOntologyClass().getName() : "") + " from " + getModelSlot().getName() + " {" + StringUtils.LINE_SEPARATOR, context); out.append(getAssertionsFMLRepresentation(context), context); out.append("}", context); if (getAssignation().isSet()) { out.append(")", context); } return out.toString(); } protected String getAssertionsFMLRepresentation(FMLRepresentationContext context) { if (getDataAssertions().size() > 0) { StringBuffer sb = new StringBuffer(); for (DataPropertyAssertion a : getDataAssertions()) { - sb.append(" " + a.getOntologyProperty().getName() + " = " + a.getValue().toString() + ";" + StringUtils.LINE_SEPARATOR); + if (a.getOntologyProperty() != null) { + sb.append(" " + a.getOntologyProperty().getName() + " = " + a.getValue().toString() + ";" + StringUtils.LINE_SEPARATOR); + } } return sb.toString(); } if (getObjectAssertions().size() > 0) { StringBuffer sb = new StringBuffer(); for (ObjectPropertyAssertion a : getObjectAssertions()) { sb.append(" " + a.getOntologyProperty().getName() + " = " + a.getObject().toString() + ";" + StringUtils.LINE_SEPARATOR); } return sb.toString(); } return null; } @Override public EditionActionType getEditionActionType() { return EditionActionType.AddIndividual; } public abstract Class<T> getOntologyIndividualClass(); @Override public IndividualPatternRole getPatternRole() { PatternRole superPatternRole = super.getPatternRole(); if (superPatternRole instanceof IndividualPatternRole) { return (IndividualPatternRole) superPatternRole; } else if (superPatternRole != null) { // logger.warning("Unexpected pattern role of type " + superPatternRole.getClass().getSimpleName()); return null; } return null; } public IFlexoOntologyClass getType() { return getOntologyClass(); } public void setType(IFlexoOntologyClass type) { setOntologyClass(type); } @Override public IFlexoOntologyClass getOntologyClass() { // System.out.println("AddIndividual: ontologyClassURI=" + ontologyClassURI); if (StringUtils.isNotEmpty(ontologyClassURI)) { return getVirtualModel().getOntologyClass(ontologyClassURI); } else { if (getPatternRole() != null) { // System.out.println("Je reponds avec le pattern role " + getPatternRole()); return getPatternRole().getOntologicType(); } } // System.out.println("Je reponds null"); return null; } @Override public void setOntologyClass(IFlexoOntologyClass ontologyClass) { System.out.println("!!!!!!!! Je sette la classe avec " + ontologyClass); if (ontologyClass != null) { if (getPatternRole() instanceof IndividualPatternRole) { if (getPatternRole().getOntologicType().isSuperConceptOf(ontologyClass)) { ontologyClassURI = ontologyClass.getURI(); } else { getPatternRole().setOntologicType(ontologyClass); } } else { ontologyClassURI = ontologyClass.getURI(); } } else { ontologyClassURI = null; } System.out.println("ontologyClassURI=" + ontologyClassURI); } public String _getOntologyClassURI() { if (getOntologyClass() != null) { if (getPatternRole() instanceof IndividualPatternRole && getPatternRole().getOntologicType() == getOntologyClass()) { // No need to store an overriding type, just use default provided by pattern role return null; } return getOntologyClass().getURI(); } return ontologyClassURI; } public void _setOntologyClassURI(String ontologyClassURI) { this.ontologyClassURI = ontologyClassURI; } public Vector<DataPropertyAssertion> getDataAssertions() { return dataAssertions; } public void setDataAssertions(Vector<DataPropertyAssertion> assertions) { this.dataAssertions = assertions; } public void addToDataAssertions(DataPropertyAssertion assertion) { assertion.setAction(this); dataAssertions.add(assertion); } public void removeFromDataAssertions(DataPropertyAssertion assertion) { assertion.setAction(null); dataAssertions.remove(assertion); } public DataPropertyAssertion createDataPropertyAssertion() { DataPropertyAssertion newDataPropertyAssertion = new DataPropertyAssertion(null); addToDataAssertions(newDataPropertyAssertion); return newDataPropertyAssertion; } public DataPropertyAssertion deleteDataPropertyAssertion(DataPropertyAssertion assertion) { removeFromDataAssertions(assertion); assertion.delete(); return assertion; } public Vector<ObjectPropertyAssertion> getObjectAssertions() { return objectAssertions; } public void setObjectAssertions(Vector<ObjectPropertyAssertion> assertions) { this.objectAssertions = assertions; } public void addToObjectAssertions(ObjectPropertyAssertion assertion) { assertion.setAction(this); objectAssertions.add(assertion); } public void removeFromObjectAssertions(ObjectPropertyAssertion assertion) { assertion.setAction(null); objectAssertions.remove(assertion); } public ObjectPropertyAssertion createObjectPropertyAssertion() { ObjectPropertyAssertion newObjectPropertyAssertion = new ObjectPropertyAssertion(null); addToObjectAssertions(newObjectPropertyAssertion); return newObjectPropertyAssertion; } public ObjectPropertyAssertion deleteObjectPropertyAssertion(ObjectPropertyAssertion assertion) { removeFromObjectAssertions(assertion); assertion.delete(); return assertion; } public DataBinding<String> getIndividualName() { if (individualName == null) { individualName = new DataBinding<String>(this, String.class, DataBinding.BindingDefinitionType.GET); individualName.setBindingName("individualName"); } return individualName; } public void setIndividualName(DataBinding<String> individualName) { if (individualName != null) { individualName.setOwner(this); individualName.setDeclaredType(String.class); individualName.setBindingDefinitionType(DataBinding.BindingDefinitionType.GET); individualName.setBindingName("individualName"); } this.individualName = individualName; } @Override public Type getAssignableType() { if (getOntologyClass() == null) { return IFlexoOntologyIndividual.class; } return IndividualOfClass.getIndividualOfClass(getOntologyClass()); } public static class AddIndividualActionMustDefineAnOntologyClass extends ValidationRule<AddIndividualActionMustDefineAnOntologyClass, AddIndividual> { public AddIndividualActionMustDefineAnOntologyClass() { super(AddIndividual.class, "add_individual_action_must_define_an_ontology_class"); } @Override public ValidationIssue<AddIndividualActionMustDefineAnOntologyClass, AddIndividual> applyValidation(AddIndividual action) { if (action.getOntologyClass() == null) { Vector<FixProposal<AddIndividualActionMustDefineAnOntologyClass, AddIndividual>> v = new Vector<FixProposal<AddIndividualActionMustDefineAnOntologyClass, AddIndividual>>(); for (IndividualPatternRole pr : action.getEditionPattern().getIndividualPatternRoles()) { v.add(new SetsPatternRole(pr)); } return new ValidationError<AddIndividualActionMustDefineAnOntologyClass, AddIndividual>(this, action, "add_individual_action_does_not_define_any_ontology_class", v); } return null; } protected static class SetsPatternRole extends FixProposal<AddIndividualActionMustDefineAnOntologyClass, AddIndividual> { private IndividualPatternRole patternRole; public SetsPatternRole(IndividualPatternRole patternRole) { super("assign_action_to_pattern_role_($patternRole.patternRoleName)"); this.patternRole = patternRole; } public IndividualPatternRole<?> getPatternRole() { return patternRole; } @Override protected void fixAction() { AddIndividual<?, ?, ?> action = getObject(); action.setAssignation(new DataBinding<Object>(patternRole.getPatternRoleName())); } } } public static class URIBindingIsRequiredAndMustBeValid extends BindingIsRequiredAndMustBeValid<AddIndividual> { public URIBindingIsRequiredAndMustBeValid() { super("'uri'_binding_is_required_and_must_be_valid", AddIndividual.class); } @Override public DataBinding<String> getBinding(AddIndividual object) { return object.getIndividualName(); } } }
true
true
protected String getAssertionsFMLRepresentation(FMLRepresentationContext context) { if (getDataAssertions().size() > 0) { StringBuffer sb = new StringBuffer(); for (DataPropertyAssertion a : getDataAssertions()) { sb.append(" " + a.getOntologyProperty().getName() + " = " + a.getValue().toString() + ";" + StringUtils.LINE_SEPARATOR); } return sb.toString(); } if (getObjectAssertions().size() > 0) { StringBuffer sb = new StringBuffer(); for (ObjectPropertyAssertion a : getObjectAssertions()) { sb.append(" " + a.getOntologyProperty().getName() + " = " + a.getObject().toString() + ";" + StringUtils.LINE_SEPARATOR); } return sb.toString(); } return null; }
protected String getAssertionsFMLRepresentation(FMLRepresentationContext context) { if (getDataAssertions().size() > 0) { StringBuffer sb = new StringBuffer(); for (DataPropertyAssertion a : getDataAssertions()) { if (a.getOntologyProperty() != null) { sb.append(" " + a.getOntologyProperty().getName() + " = " + a.getValue().toString() + ";" + StringUtils.LINE_SEPARATOR); } } return sb.toString(); } if (getObjectAssertions().size() > 0) { StringBuffer sb = new StringBuffer(); for (ObjectPropertyAssertion a : getObjectAssertions()) { sb.append(" " + a.getOntologyProperty().getName() + " = " + a.getObject().toString() + ";" + StringUtils.LINE_SEPARATOR); } return sb.toString(); } return null; }
diff --git a/org.caleydo.view.entourage/src/org/caleydo/view/entourage/contextmenu/AddPathwayActionFactory.java b/org.caleydo.view.entourage/src/org/caleydo/view/entourage/contextmenu/AddPathwayActionFactory.java index a26a2e07e..7e6baf9ae 100644 --- a/org.caleydo.view.entourage/src/org/caleydo/view/entourage/contextmenu/AddPathwayActionFactory.java +++ b/org.caleydo.view.entourage/src/org/caleydo/view/entourage/contextmenu/AddPathwayActionFactory.java @@ -1,70 +1,70 @@ package org.caleydo.view.entourage.contextmenu; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.caleydo.core.event.EventPublisher; import org.caleydo.core.util.base.IAction; import org.caleydo.core.util.collection.Pair; import org.caleydo.core.util.logging.Logger; import org.caleydo.datadomain.pathway.PathwayActions.IPathwayActionFactory; import org.caleydo.datadomain.pathway.graph.PathwayGraph; import org.caleydo.view.entourage.EEmbeddingID; import org.caleydo.view.entourage.GLEntourage; import org.caleydo.view.entourage.RcpGLEntourageView; import org.caleydo.view.entourage.event.AddPathwayEvent; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; /** * Action factory to add a pathway to {@link GLEntourage}. * * @author Christian Partl * */ public class AddPathwayActionFactory implements IPathwayActionFactory { public AddPathwayActionFactory() { } @Override public Collection<Pair<String, ? extends IAction>> create(PathwayGraph pathway, Object sender) { final AddPathwayEvent event = new AddPathwayEvent(pathway, EEmbeddingID.PATHWAY_LEVEL1); event.setSender(sender); List<Pair<String, ? extends IAction>> actions = new ArrayList<>(); - actions.add(Pair.make("Show " + pathway.getTitle() + "in Entourage", new IAction() { + actions.add(Pair.make("Show " + pathway.getTitle() + " in Entourage", new IAction() { @Override public void perform() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getActivePage(); try { RcpGLEntourageView entourage = (RcpGLEntourageView) activePage .showView(GLEntourage.VIEW_TYPE); String eventSpace = entourage.getView().getPathEventSpace(); event.setEventSpace(eventSpace); EventPublisher.trigger(event); } catch (PartInitException e) { Logger.log(new Status(IStatus.ERROR, "Show Pathway in Entourage Action", "Could not show view" + GLEntourage.VIEW_TYPE)); } } }); } })); return actions; } }
true
true
public Collection<Pair<String, ? extends IAction>> create(PathwayGraph pathway, Object sender) { final AddPathwayEvent event = new AddPathwayEvent(pathway, EEmbeddingID.PATHWAY_LEVEL1); event.setSender(sender); List<Pair<String, ? extends IAction>> actions = new ArrayList<>(); actions.add(Pair.make("Show " + pathway.getTitle() + "in Entourage", new IAction() { @Override public void perform() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getActivePage(); try { RcpGLEntourageView entourage = (RcpGLEntourageView) activePage .showView(GLEntourage.VIEW_TYPE); String eventSpace = entourage.getView().getPathEventSpace(); event.setEventSpace(eventSpace); EventPublisher.trigger(event); } catch (PartInitException e) { Logger.log(new Status(IStatus.ERROR, "Show Pathway in Entourage Action", "Could not show view" + GLEntourage.VIEW_TYPE)); } } }); } })); return actions; }
public Collection<Pair<String, ? extends IAction>> create(PathwayGraph pathway, Object sender) { final AddPathwayEvent event = new AddPathwayEvent(pathway, EEmbeddingID.PATHWAY_LEVEL1); event.setSender(sender); List<Pair<String, ? extends IAction>> actions = new ArrayList<>(); actions.add(Pair.make("Show " + pathway.getTitle() + " in Entourage", new IAction() { @Override public void perform() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getActivePage(); try { RcpGLEntourageView entourage = (RcpGLEntourageView) activePage .showView(GLEntourage.VIEW_TYPE); String eventSpace = entourage.getView().getPathEventSpace(); event.setEventSpace(eventSpace); EventPublisher.trigger(event); } catch (PartInitException e) { Logger.log(new Status(IStatus.ERROR, "Show Pathway in Entourage Action", "Could not show view" + GLEntourage.VIEW_TYPE)); } } }); } })); return actions; }
diff --git a/web/src/main/java/org/openmrs/web/taglib/PortletTag.java b/web/src/main/java/org/openmrs/web/taglib/PortletTag.java index 2ec7373c..40f4c59c 100644 --- a/web/src/main/java/org/openmrs/web/taglib/PortletTag.java +++ b/web/src/main/java/org/openmrs/web/taglib/PortletTag.java @@ -1,226 +1,226 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.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://license.openmrs.org * * 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. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.web.taglib; import java.io.IOException; import java.util.Map; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.PageContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.taglibs.standard.tag.common.core.ImportSupport; import org.openmrs.module.Module; import org.openmrs.module.ModuleFactory; import org.openmrs.util.OpenmrsUtil; public class PortletTag extends ImportSupport { public static final long serialVersionUID = 21L; private final Log log = LogFactory.getLog(getClass()); private String size = ""; private String id = ""; private String parameters = ""; private Map<String, Object> parameterMap = null; private Integer patientId = null; private Integer personId = null; private Integer encounterId = null; private Integer userId = null; private String patientIds = ""; private String moduleId = ""; public PageContext getPageContext() { return this.pageContext; } public int doStartTag() throws JspException { if (url == null) { log.warn("URL came through as NULL to PortletTag - this is a big problem"); url = ""; } if (id == null) id = ""; try { if (url.equals("")) pageContext.getOut().print("Every portlet must be defined with a URI"); else { // all portlets are contained in the /WEB-INF/view/portlets/ folder and end with .portlet - if (!url.endsWith("portlet")) + if (!url.endsWith(".portlet")) url += ".portlet"; // module specific portlets are in /WEB-INF/view/module/*/portlets/ if (moduleId != null && moduleId.length() > 0) { Module mod = ModuleFactory.getModuleById(moduleId); if (mod == null) log.warn("no module found with id: " + moduleId); else url = "/module/" + moduleId + "/portlets/" + url; } else url = "/portlets/" + url; // opening portlet tag if (moduleId != null && moduleId.length() > 0) pageContext.getOut().print("<div class='portlet' id='" + moduleId + "." + id + "'>"); else pageContext.getOut().print("<div class='portlet' id='" + id + "'>"); // add attrs to request so that the controller (and portlet) can see/use them pageContext.getRequest().setAttribute("org.openmrs.portlet.id", id); pageContext.getRequest().setAttribute("org.openmrs.portlet.size", size); pageContext.getRequest().setAttribute("org.openmrs.portlet.parameters", OpenmrsUtil.parseParameterList(parameters)); pageContext.getRequest().setAttribute("org.openmrs.portlet.patientId", patientId); pageContext.getRequest().setAttribute("org.openmrs.portlet.personId", personId); pageContext.getRequest().setAttribute("org.openmrs.portlet.encounterId", encounterId); pageContext.getRequest().setAttribute("org.openmrs.portlet.userId", userId); pageContext.getRequest().setAttribute("org.openmrs.portlet.patientIds", patientIds); pageContext.getRequest().setAttribute("org.openmrs.portlet.parameterMap", parameterMap); } } catch (IOException e) { log.error("Error while starting portlet tag", e); } return super.doStartTag(); } public int doEndTag() throws JspException { int i = super.doEndTag(); try { // closing portlet tag pageContext.getOut().print("</div>"); } catch (IOException e) { log.error("Error while closing portlet tag", e); } resetValues(); return i; } private void resetValues() { id = ""; parameters = ""; patientIds = ""; moduleId = ""; personId = null; patientId = null; encounterId = null; userId = null; parameterMap = null; } public void setUrl(String url) throws JspTagException { this.url = url; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getParameters() { return parameters; } public void setParameters(String parameters) { this.parameters = parameters; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public Integer getEncounterId() { return encounterId; } public void setEncounterId(Integer encounterId) { this.encounterId = encounterId; } public Integer getPatientId() { return patientId; } public void setPatientId(Integer patientId) { this.patientId = patientId; } public Integer getPersonId() { return personId; } public void setPersonId(Integer personId) { this.personId = personId; } public String getPatientIds() { return patientIds; } public void setPatientIds(String patientIds) { this.patientIds = patientIds; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Map<String, Object> getParameterMap() { return parameterMap; } public void setParameterMap(Map<String, Object> parameterMap) { this.parameterMap = parameterMap; } public String getModuleId() { return moduleId; } public void setModuleId(String moduleId) { this.moduleId = moduleId; } }
true
true
public int doStartTag() throws JspException { if (url == null) { log.warn("URL came through as NULL to PortletTag - this is a big problem"); url = ""; } if (id == null) id = ""; try { if (url.equals("")) pageContext.getOut().print("Every portlet must be defined with a URI"); else { // all portlets are contained in the /WEB-INF/view/portlets/ folder and end with .portlet if (!url.endsWith("portlet")) url += ".portlet"; // module specific portlets are in /WEB-INF/view/module/*/portlets/ if (moduleId != null && moduleId.length() > 0) { Module mod = ModuleFactory.getModuleById(moduleId); if (mod == null) log.warn("no module found with id: " + moduleId); else url = "/module/" + moduleId + "/portlets/" + url; } else url = "/portlets/" + url; // opening portlet tag if (moduleId != null && moduleId.length() > 0) pageContext.getOut().print("<div class='portlet' id='" + moduleId + "." + id + "'>"); else pageContext.getOut().print("<div class='portlet' id='" + id + "'>"); // add attrs to request so that the controller (and portlet) can see/use them pageContext.getRequest().setAttribute("org.openmrs.portlet.id", id); pageContext.getRequest().setAttribute("org.openmrs.portlet.size", size); pageContext.getRequest().setAttribute("org.openmrs.portlet.parameters", OpenmrsUtil.parseParameterList(parameters)); pageContext.getRequest().setAttribute("org.openmrs.portlet.patientId", patientId); pageContext.getRequest().setAttribute("org.openmrs.portlet.personId", personId); pageContext.getRequest().setAttribute("org.openmrs.portlet.encounterId", encounterId); pageContext.getRequest().setAttribute("org.openmrs.portlet.userId", userId); pageContext.getRequest().setAttribute("org.openmrs.portlet.patientIds", patientIds); pageContext.getRequest().setAttribute("org.openmrs.portlet.parameterMap", parameterMap); } } catch (IOException e) { log.error("Error while starting portlet tag", e); } return super.doStartTag(); }
public int doStartTag() throws JspException { if (url == null) { log.warn("URL came through as NULL to PortletTag - this is a big problem"); url = ""; } if (id == null) id = ""; try { if (url.equals("")) pageContext.getOut().print("Every portlet must be defined with a URI"); else { // all portlets are contained in the /WEB-INF/view/portlets/ folder and end with .portlet if (!url.endsWith(".portlet")) url += ".portlet"; // module specific portlets are in /WEB-INF/view/module/*/portlets/ if (moduleId != null && moduleId.length() > 0) { Module mod = ModuleFactory.getModuleById(moduleId); if (mod == null) log.warn("no module found with id: " + moduleId); else url = "/module/" + moduleId + "/portlets/" + url; } else url = "/portlets/" + url; // opening portlet tag if (moduleId != null && moduleId.length() > 0) pageContext.getOut().print("<div class='portlet' id='" + moduleId + "." + id + "'>"); else pageContext.getOut().print("<div class='portlet' id='" + id + "'>"); // add attrs to request so that the controller (and portlet) can see/use them pageContext.getRequest().setAttribute("org.openmrs.portlet.id", id); pageContext.getRequest().setAttribute("org.openmrs.portlet.size", size); pageContext.getRequest().setAttribute("org.openmrs.portlet.parameters", OpenmrsUtil.parseParameterList(parameters)); pageContext.getRequest().setAttribute("org.openmrs.portlet.patientId", patientId); pageContext.getRequest().setAttribute("org.openmrs.portlet.personId", personId); pageContext.getRequest().setAttribute("org.openmrs.portlet.encounterId", encounterId); pageContext.getRequest().setAttribute("org.openmrs.portlet.userId", userId); pageContext.getRequest().setAttribute("org.openmrs.portlet.patientIds", patientIds); pageContext.getRequest().setAttribute("org.openmrs.portlet.parameterMap", parameterMap); } } catch (IOException e) { log.error("Error while starting portlet tag", e); } return super.doStartTag(); }
diff --git a/oracle/src/main/java/org/archive/accesscontrol/model/HibernateRuleDao.java b/oracle/src/main/java/org/archive/accesscontrol/model/HibernateRuleDao.java index 22a9b6b..e2f92d1 100644 --- a/oracle/src/main/java/org/archive/accesscontrol/model/HibernateRuleDao.java +++ b/oracle/src/main/java/org/archive/accesscontrol/model/HibernateRuleDao.java @@ -1,162 +1,162 @@ package org.archive.accesscontrol.model; import java.text.ParseException; import java.util.Collection; import java.util.Date; import java.util.List; import org.archive.accesscontrol.RuleDao; import org.archive.accesscontrol.RuleOracleUnavailableException; import org.archive.surt.NewSurtTokenizer; import org.archive.util.ArchiveUtils; import org.hibernate.Session; import org.hibernate.Transaction; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; /** * The rule data access object provides convenience methods for using Hibernate * to access stored rules. The database connection is expected to be configured * using the SpringFramework ORM layer. * * @author aosborne */ @SuppressWarnings("unchecked") public class HibernateRuleDao extends HibernateDaoSupport implements RuleDao { public Rule getRule(Long id) { return (Rule) getHibernateTemplate().get(Rule.class, id); } public List<Rule> getAllRules() { return getHibernateTemplate().find("from Rule"); } public List<Rule> getRulesWithSurtPrefix(String prefix) { // escape wildcard characters % and _ using ! as the escape character. prefix = prefix.replace("!", "!!").replace("%", "!%") .replace("_", "!_"); return getHibernateTemplate().find( "from Rule rule where rule.surt like ? escape '!'", prefix + "%"); } public List<Rule> getRulesWithExactSurt(String surt) { return getHibernateTemplate().find( "from Rule rule where rule.surt = ?", surt); } public List<Rule> getRulesModifiedAfter(String timestamp, String who, String customRestrict) throws ParseException { - Date date = ArchiveUtils.getDate(timestamp); + Date date = (timestamp != null ? ArchiveUtils.getDate(timestamp) : null); String ruleWhereQuery = "from Rule rule where "; if (customRestrict != null) { ruleWhereQuery += customRestrict; } if (who == null && date != null) { return getHibernateTemplate().find(ruleWhereQuery + " rule.lastModified >= ?", date); } else if (who != null && date == null) { return getHibernateTemplate().find(ruleWhereQuery + " rule.who = ? or rule.who = \'\'", who); } Object[] params = {date, who}; return getHibernateTemplate().find(ruleWhereQuery + " rule.lastModified >= ? and (rule.who = ? or rule.who = \'\')", params); } /** * Returns the "rule tree" for a given SURT. This is a sorted set of all * rules equal or lower in specificity than the given SURT plus all rules on * the path from this SURT to the root SURT "(". * * The intention is to call this function with a domain or public suffix, * then queries within that domain can be made very fast by searching the * resulting list. * * @param surt * @return */ public RuleSet getRuleTree(String surt) { RuleSet rules = new RuleSet(); // add the root SURT rules.addAll(getRulesWithExactSurt("(")); boolean first = true; for (String search: new NewSurtTokenizer(surt).getSearchList()) { if (first) { first = false; rules.addAll(getRulesWithSurtPrefix(search)); } else { rules.addAll(getRulesWithExactSurt(search)); } } return rules; } public void saveRule(Rule rule) { rule.setLastModified(new Date()); getHibernateTemplate().saveOrUpdate(rule); } public boolean saveRuleIfNotDup(Rule rule) { List<Rule> allRules = getAllRules(); for (Rule existingRule : allRules) { if (existingRule.compareTo(rule) == 0) { // If we're not the same, rule then we're a dup! if ((rule.getId() == null) || !rule.getId().equals(existingRule.getId())) { return false; } } } saveRule(rule); return true; } /** * Save a rule and a change log entry in one go. (Uses a transaction). * @param rule * @param change */ public void saveRule(Rule rule, RuleChange change) { rule.setLastModified(new Date()); Session session1 = getHibernateTemplate().getSessionFactory().openSession(); Transaction tx = session1.beginTransaction(); session1.saveOrUpdate(rule); session1.save(change); tx.commit(); session1.close(); } public void saveChange(RuleChange change) { getHibernateTemplate().saveOrUpdate(change); } public void deleteRule(Long id) { Object record = getHibernateTemplate().load(Rule.class, id); getHibernateTemplate().delete(record); } public void deleteAllRules() { getHibernateTemplate().bulkUpdate("delete from Rule"); } public void prepare(Collection<String> surts) { // no-op } public boolean hasNewRulesSince(String timestamp, String who) throws RuleOracleUnavailableException { try { return !getRulesModifiedAfter(timestamp, who, null).isEmpty(); } catch (ParseException e) { throw new RuleOracleUnavailableException(e); } } }
true
true
public List<Rule> getRulesModifiedAfter(String timestamp, String who, String customRestrict) throws ParseException { Date date = ArchiveUtils.getDate(timestamp); String ruleWhereQuery = "from Rule rule where "; if (customRestrict != null) { ruleWhereQuery += customRestrict; } if (who == null && date != null) { return getHibernateTemplate().find(ruleWhereQuery + " rule.lastModified >= ?", date); } else if (who != null && date == null) { return getHibernateTemplate().find(ruleWhereQuery + " rule.who = ? or rule.who = \'\'", who); } Object[] params = {date, who}; return getHibernateTemplate().find(ruleWhereQuery + " rule.lastModified >= ? and (rule.who = ? or rule.who = \'\')", params); }
public List<Rule> getRulesModifiedAfter(String timestamp, String who, String customRestrict) throws ParseException { Date date = (timestamp != null ? ArchiveUtils.getDate(timestamp) : null); String ruleWhereQuery = "from Rule rule where "; if (customRestrict != null) { ruleWhereQuery += customRestrict; } if (who == null && date != null) { return getHibernateTemplate().find(ruleWhereQuery + " rule.lastModified >= ?", date); } else if (who != null && date == null) { return getHibernateTemplate().find(ruleWhereQuery + " rule.who = ? or rule.who = \'\'", who); } Object[] params = {date, who}; return getHibernateTemplate().find(ruleWhereQuery + " rule.lastModified >= ? and (rule.who = ? or rule.who = \'\')", params); }
diff --git a/plugins-dev/planning/pt/lsts/neptus/plugins/planning/PlanEditor.java b/plugins-dev/planning/pt/lsts/neptus/plugins/planning/PlanEditor.java index 82d6644f3..7e5372795 100644 --- a/plugins-dev/planning/pt/lsts/neptus/plugins/planning/PlanEditor.java +++ b/plugins-dev/planning/pt/lsts/neptus/plugins/planning/PlanEditor.java @@ -1,1683 +1,1683 @@ /* * Copyright (c) 2004-2014 Universidade do Porto - Faculdade de Engenharia * Laboratório de Sistemas e Tecnologia Subaquática (LSTS) * All rights reserved. * Rua Dr. Roberto Frias s/n, sala I203, 4200-465 Porto, Portugal * * This file is part of Neptus, Command and Control Framework. * * Commercial Licence Usage * Licencees holding valid commercial Neptus licences may use this file * in accordance with the commercial licence agreement provided with the * Software or, alternatively, in accordance with the terms contained in a * written agreement between you and Universidade do Porto. For licensing * terms, conditions, and further information contact lsts@fe.up.pt. * * European Union Public Licence - EUPL v.1.1 Usage * Alternatively, this file may be used under the terms of the EUPL, * Version 1.1 only (the "Licence"), appearing in the file LICENCE.md * included in the packaging of this file. You may not use this work * except in compliance with the Licence. Unless required by applicable * law or agreed to in writing, software distributed under the Licence is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the Licence for the specific * language governing permissions and limitations at * https://www.lsts.pt/neptus/licence. * * For more information please see <http://lsts.fe.up.pt/neptus>. * * Author: José Pinto * 200?/??/?? */ package pt.lsts.neptus.plugins.planning; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Cursor; import java.awt.Dialog.ModalityType; import java.awt.Font; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Image; import java.awt.Point; import java.awt.Toolkit; import java.awt.Window; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.text.Collator; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; import javax.swing.undo.UndoManager; import org.dom4j.Document; import org.dom4j.DocumentHelper; import pt.lsts.imc.IMCMessage; import pt.lsts.neptus.NeptusLog; import pt.lsts.neptus.console.ConsoleLayout; import pt.lsts.neptus.console.plugins.MissionChangeListener; import pt.lsts.neptus.gui.PropertiesEditor; import pt.lsts.neptus.gui.VehicleChooser; import pt.lsts.neptus.gui.VehicleSelectionDialog; import pt.lsts.neptus.gui.ZValueSelector; import pt.lsts.neptus.i18n.I18n; import pt.lsts.neptus.mp.Maneuver; import pt.lsts.neptus.mp.ManeuverFactory; import pt.lsts.neptus.mp.ManeuverLocation; import pt.lsts.neptus.mp.maneuvers.Goto; import pt.lsts.neptus.mp.maneuvers.LocatedManeuver; import pt.lsts.neptus.mp.preview.PlanSimulationOverlay; import pt.lsts.neptus.params.ManeuverPayloadConfig; import pt.lsts.neptus.planeditor.PlanTransitionsSimpleEditor; import pt.lsts.neptus.plugins.NeptusProperty; import pt.lsts.neptus.plugins.NeptusProperty.LEVEL; import pt.lsts.neptus.plugins.PluginDescription; import pt.lsts.neptus.plugins.PluginDescription.CATEGORY; import pt.lsts.neptus.plugins.PluginUtils; import pt.lsts.neptus.plugins.planning.edit.ManeuverAdded; import pt.lsts.neptus.plugins.planning.edit.ManeuverChanged; import pt.lsts.neptus.plugins.planning.edit.ManeuverPropertiesPanel; import pt.lsts.neptus.plugins.planning.edit.ManeuverRemoved; import pt.lsts.neptus.plugins.planning.edit.PlanRotated; import pt.lsts.neptus.plugins.planning.edit.PlanTranslated; import pt.lsts.neptus.plugins.update.IPeriodicUpdates; import pt.lsts.neptus.plugins.update.PeriodicUpdatesService; import pt.lsts.neptus.renderer2d.InteractionAdapter; import pt.lsts.neptus.renderer2d.LayerPriority; import pt.lsts.neptus.renderer2d.Renderer2DPainter; import pt.lsts.neptus.renderer2d.StateRenderer2D; import pt.lsts.neptus.renderer2d.StateRendererInteraction; import pt.lsts.neptus.types.coord.CoordinateUtil; import pt.lsts.neptus.types.coord.LocationType; import pt.lsts.neptus.types.map.MapGroup; import pt.lsts.neptus.types.map.MapType; import pt.lsts.neptus.types.map.PlanElement; import pt.lsts.neptus.types.map.PlanUtil; import pt.lsts.neptus.types.mission.MissionType; import pt.lsts.neptus.types.mission.TransitionType; import pt.lsts.neptus.types.mission.plan.PlanType; import pt.lsts.neptus.types.vehicle.VehicleType; import pt.lsts.neptus.types.vehicle.VehiclesHolder; import pt.lsts.neptus.util.GuiUtils; import pt.lsts.neptus.util.ImageUtils; import pt.lsts.neptus.util.conf.ConfigFetch; import com.l2fprod.common.propertysheet.DefaultProperty; import com.l2fprod.common.propertysheet.PropertySheet; import com.l2fprod.common.propertysheet.PropertySheetDialog; import com.l2fprod.common.propertysheet.PropertySheetPanel; /** * * @author ZP * @author pdias */ @PluginDescription(name = "Plan Edition", icon = "pt/lsts/neptus/plugins/planning/images/plan_editor.png", author = "José Pinto, Paulo Dias", version = "1.5", category = CATEGORY.INTERFACE) @LayerPriority(priority = 100) public class PlanEditor extends InteractionAdapter implements Renderer2DPainter, IPeriodicUpdates, MissionChangeListener { private static final long serialVersionUID = 1L; private final String defaultCondition = "ManeuverIsDone"; private MissionType mission = null; private PlanType plan = null; private PlanElement planElem; private ManeuverFactory mf = null; private final MapGroup mapGroup = null; private Maneuver selectedManeuver = null; // private Vector<Maneuver> selection = new Vector<Maneuver>(); private Point2D lastDragPoint = null; private final Vector<String> takenNames = new Vector<String>(); private StateRenderer2D renderer; private StateRendererInteraction delegate = null; private JPanel controls; protected JPanel sidePanel = null; protected JLabel statsLabel = null; protected static final String maneuverPreamble = "[Neptus:Maneuver]\n"; protected PlanSimulationOverlay overlay = null; public enum ToolbarLocation { Right, Left }; private ManeuverPropertiesPanel propertiesPanel = null; private LocationType maneuverLocationBeforeMoving = null; private boolean maneuverWasMoved = false; private boolean planChanged = false; private boolean planTranslated = false; // private boolean planRotated = false; private double planRotatedRads = 0; private String planStatistics = ""; @NeptusProperty(name = "Toolbar Location", userLevel = LEVEL.REGULAR) public ToolbarLocation toolbarLocation = ToolbarLocation.Right; /** * @param console */ public PlanEditor(ConsoleLayout console) { super(console); } @Override public long millisBetweenUpdates() { return 1000; } protected ManeuverPropertiesPanel getPropertiesPanel() { if (propertiesPanel == null) propertiesPanel = new ManeuverPropertiesPanel(); return propertiesPanel; } @Override public boolean update() { Maneuver curManeuver = getPropertiesPanel().getManeuver(); if (curManeuver != null && renderer.isFocusOwner()) { getPropertiesPanel().setManeuver(curManeuver); getPropertiesPanel().setPlan(plan); getPropertiesPanel().setManager(manager); if (delegate != null) getPropertiesPanel().getEditBtn().setSelected(true); } try { if (plan != null) { planStatistics = PlanUtil.getPlanStatisticsAsText(plan, null, true, true); statsLabel.setText(planStatistics); } } catch (Exception e) { e.printStackTrace(); } return true; } private final UndoManager manager = new UndoManager() { private static final long serialVersionUID = 1L; @Override public synchronized boolean addEdit(javax.swing.undo.UndoableEdit anEdit) { boolean ret = super.addEdit(anEdit); updateUndoRedo(); return ret; }; @Override public synchronized void undo() throws javax.swing.undo.CannotUndoException { super.undo(); updateUndoRedo(); }; @Override public synchronized void redo() throws javax.swing.undo.CannotRedoException { super.redo(); updateUndoRedo(); }; }; @Override public Image getIconImage() { return ImageUtils.getImage(PluginUtils.getPluginIcon(getClass())); } @Override public void setActive(boolean mode, StateRenderer2D source) { super.setActive(mode, source); getPropertiesPanel().setManeuver(null); this.renderer = source; if (mode) { PeriodicUpdatesService.register(this); Container c = source; while (c.getParent() != null && !(c.getLayout() instanceof BorderLayout)) c = c.getParent(); if (c.getLayout() instanceof BorderLayout) { switch (toolbarLocation) { case Left: c.add(getSidePanel(), BorderLayout.WEST); break; default: c.add(getSidePanel(), BorderLayout.EAST); break; } c.invalidate(); c.validate(); if (c instanceof JComponent) ((JComponent) c).setBorder(new LineBorder(Color.orange.darker(), 3)); } if (plan == null && getConsole().getPlan() != null) setPlan(getConsole().getPlan().clonePlan()); else if (plan == null) { VehicleType choice = null; if (getConsole().getMainSystem() != null) choice = VehicleChooser.showVehicleDialog( VehiclesHolder.getVehicleById(getConsole().getMainSystem()), getConsole()); else choice = VehicleChooser.showVehicleDialog(getConsole()); if (choice == null) { if (getAssociatedSwitch() != null) getAssociatedSwitch().doClick(); return; } PlanType plan = new PlanType(getConsole().getMission()); plan.setVehicle(choice.getId()); setPlan(plan); } else { setPlan(plan); } } else { PeriodicUpdatesService.unregister(this); if (delegate != null) { delegate.setActive(false, source); getPropertiesPanel().getEditBtn().setSelected(false); delegate = null; } Container c = source; while (c.getParent() != null && !(c.getLayout() instanceof BorderLayout)) c = c.getParent(); if (c.getLayout() instanceof BorderLayout) { c.remove(getSidePanel()); c.invalidate(); c.validate(); if (c instanceof JComponent) ((JComponent) c).setBorder(new EmptyBorder(0, 0, 0, 0)); } if (plan != null && !manager.canUndo() && getConsole().getMission().getIndividualPlansList().containsKey(plan.getId())) plan = null; planElem = null; renderer.setToolTipText(""); overlay = null; } } @SuppressWarnings("serial") protected JPanel getSidePanel() { if (sidePanel == null) { sidePanel = new JPanel(new BorderLayout(2, 2)); statsLabel = new JLabel() { @Override public void setText(String text) { String[] txts = text.split("\n"); text = "<html>"; for (String str : txts) { if (!str.contains(I18n.text("Plan Statistics")) && !str.contains(I18n.text("ID") + ":") && !str.contains(I18n.text("Vehicle") + ":") && !str.equals("")) { text += str + "<br>"; } } super.setText(text); } }; controls = new JPanel(new GridLayout(0, 3)); controls.add(new JButton(getNewAction())); controls.add(new JButton(getSaveAction())); controls.add(new JButton(getCloseAction())); controls.add(new JButton(getSettingsAction()) { { setEnabled(false); } }); controls.add(new JButton(getUndoAction())); controls.add(new JButton(getRedoAction())); updateUndoRedo(); controls.setBorder(new TitledBorder(I18n.text("Plan"))); // controls.add(statsLabel); sidePanel.add(controls, BorderLayout.SOUTH); JPanel holder = new JPanel(new BorderLayout()); holder.add(getPropertiesPanel()); holder.add(statsLabel, BorderLayout.SOUTH); sidePanel.add(holder, BorderLayout.CENTER); getPropertiesPanel().getEditBtn().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Maneuver man = getPropertiesPanel().getManeuver(); if (man instanceof StateRendererInteraction) { if (getPropertiesPanel().getEditBtn().isSelected()) { delegate = (StateRendererInteraction) man; delegate.setActive(true, renderer); } else { delegate.setActive(false, renderer); delegate = null; planElem.recalculateManeuverPositions(renderer); } } } }); getPropertiesPanel().getDeleteBtn().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (getPropertiesPanel().getManeuver() != null) { removeManeuver(getPropertiesPanel().getManeuver().getId()); } } }); getPropertiesPanel().setOpaque(false); controls.setOpaque(false); } return sidePanel; } protected AbstractAction getSettingsAction() { return new AbstractAction(I18n.text("Statistics"), ImageUtils.getScaledIcon( "pt/lsts/neptus/plugins/planning/images/edit_settings.png", 16, 16)) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { JDialog dialog = new JDialog(getConsole(), I18n.text("Edited plan statistics")); JEditorPane editor = new JEditorPane("text/html", PlanUtil.getPlanStatisticsAsText(plan, I18n.textf("%planName statistics", plan.getId()), false, false)); editor.setEditable(false); dialog.getContentPane().add(new JScrollPane(editor)); dialog.setSize(400, 400); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); GuiUtils.centerOnScreen(dialog); dialog.setVisible(true); } }; } public void editDifferentPlan(PlanType newPlan) { if (plan != null && manager.canUndo()) { int option = JOptionPane.showConfirmDialog(getConsole(), I18n.textf("Continuing will discard all changes made to %planName. Continue?", plan.getId()), I18n.text("Edit plan"), JOptionPane.YES_NO_OPTION); if (option == JOptionPane.NO_OPTION) return; } manager.discardAllEdits(); updateUndoRedo(); setPlan(newPlan.clonePlan()); if (getAssociatedSwitch() != null && !getAssociatedSwitch().isSelected()) getAssociatedSwitch().doClick(); } public void newPlan() { getPropertiesPanel().setManeuver(null); if (plan != null) { int option = JOptionPane.showConfirmDialog(getConsole(), I18n.textf("Continuing will discard all changes made to %planName. Continue?", plan.getId()), I18n.text("Create new plan"), JOptionPane.YES_NO_OPTION); if (option == JOptionPane.NO_OPTION) return; } manager.discardAllEdits(); updateUndoRedo(); VehicleType choice = null; if (getConsole().getMainSystem() != null) choice = VehicleChooser.showVehicleDialog(VehiclesHolder.getVehicleById(getConsole().getMainSystem()), getConsole()); else choice = VehicleChooser.showVehicleDialog(getConsole()); if (choice == null) return; PlanType plan = new PlanType(getConsole().getMission()); plan.setVehicle(choice.getId()); setPlan(plan); if (getAssociatedSwitch() != null && !getAssociatedSwitch().isSelected()) getAssociatedSwitch().doClick(); } protected AbstractAction getNewAction() { return new AbstractAction(I18n.textc("New", "Plan"), ImageUtils.getScaledIcon( "pt/lsts/neptus/plugins/planning/images/edit_new.png", 16, 16)) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { newPlan(); } }; } protected AbstractAction undoAction, redoAction; protected void updateUndoRedo() { getUndoAction().putValue(AbstractAction.SHORT_DESCRIPTION, manager.getUndoPresentationName()); getRedoAction().putValue(AbstractAction.SHORT_DESCRIPTION, manager.getRedoPresentationName()); getUndoAction().setEnabled(manager.canUndo()); getRedoAction().setEnabled(manager.canRedo()); planChanged = manager.canUndo(); if (planElem != null) planElem.recalculateManeuverPositions(renderer); try { if (getPropertiesPanel().getManeuver() != null) { if (plan.getGraph().getManeuver(getPropertiesPanel().getManeuver().getId()) == null) getPropertiesPanel().setManeuver(null); } } catch (Exception e) { e.printStackTrace(); } } protected AbstractAction getUndoAction() { if (undoAction == null) undoAction = new AbstractAction(I18n.text("Undo"), ImageUtils.getScaledIcon( "pt/lsts/neptus/plugins/planning/images/undo.png", 16, 16)) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { manager.undo(); planElem.recalculateManeuverPositions(renderer); } }; return undoAction; } protected AbstractAction getRedoAction() { if (redoAction == null) redoAction = new AbstractAction(I18n.text("Redo"), ImageUtils.getScaledIcon( "pt/lsts/neptus/plugins/planning/images/redo.png", 16, 16)) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { manager.redo(); planElem.recalculateManeuverPositions(renderer); } }; return redoAction; } protected AbstractAction getSaveAction() { return new AbstractAction(I18n.text("Save"), ImageUtils.getScaledIcon( "pt/lsts/neptus/plugins/planning/images/edit_save.png", 16, 16)) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { getPropertiesPanel().setManeuver(null); String lastPlanId = plan.getId(); String planId = lastPlanId; while (true) { planId = JOptionPane.showInputDialog(getConsole(), I18n.text("Enter the plan ID"), lastPlanId); if (planId == null) return; if (getConsole().getMission().getIndividualPlansList().get(planId) != null) { int option = JOptionPane.showConfirmDialog(getConsole(), I18n.text("Do you wish to replace the existing plan with same name?")); if (option == JOptionPane.CANCEL_OPTION) return; else if (option == JOptionPane.YES_OPTION) { break; } lastPlanId = planId; } else break; } plan.setId(planId); plan.setMissionType(getConsole().getMission()); getConsole().getMission().addPlan(plan); // getConsole().getMission().save(true); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { getConsole().getMission().save(true); return null; } }; worker.execute(); if (getConsole().getPlan() == null || getConsole().getPlan().getId().equalsIgnoreCase(plan.getId())) { getConsole().setPlan(plan); } setPlan(null); manager.discardAllEdits(); updateUndoRedo(); if (getAssociatedSwitch() != null) getAssociatedSwitch().doClick(); getConsole().updateMissionListeners(); } }; } protected AbstractAction getCloseAction() { return new AbstractAction(I18n.text("Close"), ImageUtils.getScaledIcon( "pt/lsts/neptus/plugins/planning/images/edit_close.png", 16, 16)) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { if (plan != null && planChanged) { int option = JOptionPane.showConfirmDialog(getConsole(), I18n.textf("Continuing will discard all changes made to %planName. Continue?", plan.getId()), I18n.text("Close discarding changes"), JOptionPane.YES_NO_OPTION); if (option == JOptionPane.NO_OPTION) return; } setPlan(null); manager.discardAllEdits(); updateUndoRedo(); if (getAssociatedSwitch() != null) getAssociatedSwitch().doClick(); } }; } @Override public void paint(Graphics2D g, StateRenderer2D renderer) { this.renderer = renderer; if (planElem != null) { planElem.setRenderer(renderer); planElem.paint((Graphics2D) g.create(), renderer); } if (overlay != null && isActive()) overlay.paint(g, renderer); g.setFont(new Font("Helvetica", Font.BOLD, 14)); if (delegate != null) { String txt = I18n.textf("Editing %manName - Double click to end", ((Maneuver) delegate).getId()); g.setColor(Color.black); g.drawString(txt, 55, 15); g.setColor(Color.white); g.drawString(txt, 54, 14); } } /** * Verifies if a given vehicle supports this kind of editor * * @param vehicleID The vehicle's ID * @return <b>true</b> if the vehicle is supported or <b>false</b> otherwise */ public static boolean isVehicleSupported(String vehicleID) { VehicleType vehicle = VehiclesHolder.getVehicleById(vehicleID); if (vehicle == null) return false; LinkedHashMap<String, String> maneuvers = vehicle.getFeasibleManeuvers(); for (String maneuver : maneuvers.keySet()) { Maneuver man = ManeuverFactory.createManeuver(maneuver, maneuvers.get(maneuver)); if (man != null) { return true; } } return false; } public void setPlan(PlanType plan) { this.plan = plan; if (plan == null) { planElem = null; return; } getPropertiesPanel().setManager(null); parsePlan(); planElem = new PlanElement(mapGroup, new MapType()); planElem.setBeingEdited(true); planElem.setRenderer(renderer); planElem.setTransp2d(1.0); planElem.setPlan(plan); controls.setBorder(new TitledBorder(I18n.textf("Editing %planName", plan.getId()))); } private void parsePlan() { VehicleType vt = plan.getVehicleType(); if (vt == null) { NeptusLog.pub().warn("No vehicle type for vehicle " + plan.getVehicle() + " for plan " + plan.getId()); String mvid = getMainVehicleId(); vt = VehiclesHolder.getVehicleById(mvid); if (vt == null) NeptusLog.pub().warn("No vehicle type for main vehicle " + getMainVehicleId() + " for plan " + plan.getId()); else plan.setVehicle(getMainVehicleId()); } if (vt != null) { this.mf = vt.getManeuverFactory(); } else { NeptusLog.pub().warn("No vehicle type creating empty maneuver factory for plan " + plan.getId()); this.mf = new ManeuverFactory(null); } for (Maneuver man : plan.getGraph().getAllManeuvers()) { takenNames.add(man.getId()); } } protected Collection<AbstractAction> getActionsForManeuver(final Maneuver man, final Point mousePoint) { Vector<AbstractAction> actions = new Vector<AbstractAction>(); AbstractAction props = new AbstractAction(I18n.textf("%manName properties", man.getId())) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { boolean wasInitialManeuver = man.isInitialManeuver(); String oldXml = man.asXML(); PropertiesEditor.editProperties(man, PlanEditor.this.getConsole(), true); manager.addEdit(new ManeuverChanged(man, plan, oldXml)); if (man.isInitialManeuver()) plan.getGraph().setInitialManeuver(man.getId()); else { if (wasInitialManeuver) { man.setInitialManeuver(true); GuiUtils.infoMessage(ConfigFetch.getSuperParentFrame(), I18n.text("Set Properties"), I18n.text("To change the initial maneuver, please set another maneuver as the initial")); } } planElem.recalculateManeuverPositions(renderer); renderer.repaint(); refreshPropertiesManeuver(); } }; props.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getImage("images/menus/edit.png"))); actions.add(props); if (man instanceof StateRendererInteraction) { AbstractAction editMan = new AbstractAction(I18n.textf("Edit %maneuverName in the map", man.getId())) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { delegate = (StateRendererInteraction) man; delegate.setActive(true, renderer); } }; actions.add(editMan); } AbstractAction remove = new AbstractAction(I18n.textf("Remove %maneuverName", man.getId())) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { removeManeuver(man.getId()); } }; remove.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getImage("images/menus/editdelete.png"))); actions.add(remove); AbstractAction copy = new AbstractAction(I18n.textf("Copy %maneuverName to clipboard", man.getId())) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { ClipboardOwner owner = new ClipboardOwner() { @Override public void lostOwnership(java.awt.datatransfer.Clipboard clipboard, java.awt.datatransfer.Transferable contents) { } }; Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(new StringSelection(maneuverPreamble + man.getManeuverXml()), owner); } }; copy.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getImage("images/menus/editcopy.png"))); actions.add(copy); List<String> names = Arrays.asList(mf.getAvailableManeuversIDs()); Collections.sort(names, new Comparator<String>() { @Override public int compare(String o1, String o2) { Collator collator = Collator.getInstance(Locale.US); return collator.compare(o1, o2); } }); ImageIcon icon = ImageUtils.getIcon("images/led_none.png"); for (String manName : names) { final String manType = manName; AbstractAction act = new AbstractAction(I18n.textf("Add %maneuverName1 before %maneuverName2", manName, man.getId()), icon) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent evt) { Vector<TransitionType> trans = plan.getGraph().getIncomingTransitions(man); if (trans.isEmpty()) addManeuverAtBeginning(manType, mousePoint); else addManeuverAfter(manType, trans.firstElement().getSourceManeuver()); planElem.recalculateManeuverPositions(renderer); renderer.repaint(); } }; actions.add(act); } return actions; } private String xml = null; @Override public void mouseClicked(MouseEvent event, StateRenderer2D source) { final StateRenderer2D renderer = source; final Point2D mousePoint = event.getPoint(); if (delegate != null) { if (event.getClickCount() == 2) { delegate.setActive(false, source); getPropertiesPanel().setManeuver(getPropertiesPanel().getManeuver()); getPropertiesPanel().getEditBtn().setSelected(false); planElem.recalculateManeuverPositions(source); delegate = null; if (xml != null) { ManeuverChanged edit = new ManeuverChanged(getPropertiesPanel().getManeuver(), plan, xml); xml = null; manager.addEdit(edit); } return; } else { delegate.mouseClicked(event, source); return; } } if (event.getClickCount() == 2) { planElem.iterateManeuverBack(event.getPoint()); final Maneuver man = planElem.iterateManeuverBack(event.getPoint()); if (man != null) { if (man instanceof StateRendererInteraction) { delegate = (StateRendererInteraction) man; ((StateRendererInteraction) man).setActive(true, source); getPropertiesPanel().getEditBtn().setSelected(true); xml = getPropertiesPanel().getManeuver().getManeuverXml(); } return; } } if (event.isControlDown() && event.getButton() == MouseEvent.BUTTON1) { Maneuver m = plan.getGraph().getLastManeuver(); addManeuverAtEnd(event.getPoint(), m.getType()); return; } if (event.getButton() == MouseEvent.BUTTON3) { JPopupMenu popup = new JPopupMenu(); AbstractAction copy = new AbstractAction(I18n.text("Copy location")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { CoordinateUtil.copyToClipboard(renderer.getRealWorldLocation(mousePoint)); } }; copy.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getImage("images/menus/editcopy.png"))); popup.add(copy); final Maneuver[] mans = planElem.getAllInterceptedManeuvers(event.getPoint()); popup.addSeparator(); if (mans.length == 1) { for (AbstractAction act : getActionsForManeuver(mans[0], (Point) mousePoint)) popup.add(act); } else if (mans.length > 1) { for (Maneuver m : mans) { JMenu subMenu = new JMenu(m.getId()); if (m instanceof LocatedManeuver) { subMenu.setText(m.getId() + " (" + (GuiUtils.getNeptusDecimalFormat(1).format(((LocatedManeuver) m) .getManeuverLocation().getAllZ())) + " m)"); } subMenu.setIcon(new ImageIcon(ImageUtils.getImage("images/menus/plan.png"))); for (AbstractAction act : getActionsForManeuver(m, (Point) mousePoint)) subMenu.add(act); popup.add(subMenu); } } else { if (plan.hasInitialManeuver()) { - JMenu planSettings = new JMenu(I18n.text("Change existing Maneuvers")); + JMenu planSettings = new JMenu(I18n.text("Change existing maneuvers")); AbstractAction pDepth = new AbstractAction(I18n.text("Plan depth / altitude...")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { ManeuverLocation loc = new ManeuverLocation(); for (Maneuver m : plan.getGraph().getAllManeuvers()) { if (m instanceof LocatedManeuver) { loc = ((LocatedManeuver) m).getManeuverLocation().clone(); break; } } boolean newZ = ZValueSelector.showHeightDepthDialog(getConsole().getMainPanel(), loc, I18n.text("Plan depth / altitude")); if (newZ) { planElem.setPlanZ(loc.getZ(), loc.getZUnits()); refreshPropertiesManeuver(); } } }; pDepth.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); planSettings.add(pDepth); AbstractAction pVel = new AbstractAction(I18n.text("Plan speed...")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { String[] optionsI18n = { I18n.text("m/s"), I18n.text("RPM"), "%" }; String[] optionsNotI18n = { "m/s", "RPM", "%" }; DefaultProperty dp = planElem.getLastSetProperties().get("Speed units"); String curValueNotI18n = "m/s"; if (dp != null) curValueNotI18n = dp.getValue().toString(); Object resp = JOptionPane.showInputDialog(getConsole(), I18n.text("Please choose the speed units"), I18n.text("Set plan speed"), JOptionPane.QUESTION_MESSAGE, null, optionsI18n, I18n.text(curValueNotI18n)); if (resp == null) return; String velUnitI18n = resp.toString(); String velUnitNotI18n = "m/s"; for (int i = 0; i < optionsI18n.length; i++) { if (velUnitI18n.equals(optionsI18n[i])) { velUnitNotI18n = optionsNotI18n[i]; break; } } double velocity = 0; boolean validVel = false; while (!validVel) { double curSpeed = 1.3; dp = planElem.getLastSetProperties().get("Speed"); if (dp != null) curSpeed = (Double) dp.getValue(); String res = JOptionPane.showInputDialog(getConsole(), I18n.textf("Enter new speed (%speedUnit)", velUnitI18n), curSpeed); if (res == null) return; try { velocity = Double.parseDouble(res); validVel = true; } catch (Exception ex) { ex.printStackTrace(); GuiUtils.errorMessage(getConsole(), I18n.text("Set plan speed"), I18n.text("Speed must be a numeric value")); } } DefaultProperty propVel = new DefaultProperty(); propVel.setName("Speed"); propVel.setValue(velocity); propVel.setType(Double.class); propVel.setDisplayName(I18n.text("Speed")); planElem.setPlanProperty(propVel); DefaultProperty propVelUnits = new DefaultProperty(); propVelUnits.setName("Speed units"); propVelUnits.setValue(velUnitNotI18n); // velUnitI18n propVelUnits.setType(String.class); propVelUnits.setDisplayName(I18n.text("Speed units")); planElem.setPlanProperty(propVelUnits); refreshPropertiesManeuver(); } }; pVel.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); planSettings.add(pVel); AbstractAction pPayload = new AbstractAction(I18n.text("Payload settings...")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { // PropertiesEditor editor = new PropertiesEditor(); Goto pivot = new Goto(); PropertySheetPanel psp = new PropertySheetPanel(); psp.setEditorFactory(PropertiesEditor.getPropertyEditorRegistry()); psp.setRendererFactory(PropertiesEditor.getPropertyRendererRegistry()); psp.setMode(PropertySheet.VIEW_AS_CATEGORIES); psp.setToolBarVisible(false); psp.setSortingCategories(true); psp.setDescriptionVisible(true); ManeuverPayloadConfig payloadConfig = new ManeuverPayloadConfig(plan.getVehicle(), pivot, psp); DefaultProperty[] properties = payloadConfig.getProperties(); // FIXME localize these properties! // Vector<DefaultProperty> result = new Vector<DefaultProperty>(); // PropertiesEditor.localizeProperties(Arrays.asList(properties), result); // DefaultProperty[] propertiesLocalized = properties;//result.toArray(new // DefaultProperty[0]); psp.setProperties(properties); final PropertySheetDialog propertySheetDialog = PropertiesEditor.createWindow(getConsole(), true, psp, "Payload Settings to apply to entire plan"); if (propertySheetDialog.ask()) { // DefaultProperty[] propsUnlocalized = PropertiesEditor.unlocalizeProps(original, // psp.getProperties()); payloadConfig.setProperties(properties); Vector<IMCMessage> startActions = new Vector<>(); startActions.addAll(Arrays.asList(pivot.getStartActions().getAllMessages())); for (Maneuver m : plan.getGraph().getAllManeuvers()) { m.getStartActions().parseMessages(startActions); NeptusLog.pub().info("<###> " + m.getId()); } refreshPropertiesManeuver(); } } }; pPayload.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); planSettings.add(pPayload); AbstractAction pVehicle = new AbstractAction(I18n.text("Set plan vehicles...")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { Window parentW = SwingUtilities.getWindowAncestor(getConsole()); String[] vehicles = VehicleSelectionDialog.showSelectionDialog(parentW, plan.getVehicles() .toArray(new VehicleType[0])); Vector<VehicleType> vts = new Vector<VehicleType>(); for (String v : vehicles) { vts.add(VehiclesHolder.getVehicleById(v)); } plan.setVehicles(vts); } }; pVehicle.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); planSettings.add(pVehicle); planSettings.setIcon(new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); popup.add(planSettings); // popup.addSeparator(); } AbstractAction pTransitions = new AbstractAction(I18n.text("Plan Transitions")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { Window parent = SwingUtilities.getWindowAncestor(getConsole()); if (parent == null) parent = SwingUtilities.getWindowAncestor(ConfigFetch.getSuperParentAsFrame()); JDialog transitions = new JDialog(parent, I18n.textf("Edit '%planName' plan transitions", plan.getId())); transitions.setModalityType(ModalityType.DOCUMENT_MODAL); transitions.getContentPane().add(new PlanTransitionsSimpleEditor(plan)); transitions.setSize(800, 500); GuiUtils.centerParent(transitions, getConsole()); transitions.setVisible(true); parsePlan(); renderer.repaint(); refreshPropertiesManeuver(); } }; pTransitions.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); popup.add(pTransitions); // popup.addSeparator(); JMenu pStatistics = PlanUtil.getPlanStatisticsAsJMenu(plan, I18n.text("Edited Plan Statistics")); pStatistics.setIcon(new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); popup.add(pStatistics); popup.addSeparator(); List<String> names = Arrays.asList(mf.getAvailableManeuversIDs()); Collections.sort(names); ImageIcon icon = ImageUtils.getIcon("images/led_none.png"); for (final String manName : names) { String manNameStr = I18n.text(manName); AbstractAction act = new AbstractAction(I18n.textf("Add %maneuverName", manNameStr), icon) { private static final long serialVersionUID = 1L; private final Point2D mousePos = mousePoint; @Override public void actionPerformed(ActionEvent evt) { String maneuverName = manName; addManeuverAtEnd((Point) mousePos, maneuverName); planElem.recalculateManeuverPositions(renderer); renderer.repaint(); } }; popup.add(act); } popup.add(getPasteAction((Point) mousePoint)); // AbstractAction act = new AbstractAction(I18n.text("Simulate plan"), null) { // private static final long serialVersionUID = 1L; // // @Override // public void actionPerformed(ActionEvent evt) { // // String vehicle = getConsole().getMainSystem(); // LocationType startLoc = plan.getMissionType().getStartLocation(); // SystemPositionAndAttitude start = new SystemPositionAndAttitude(startLoc, 0, 0, 0); // EstimatedState lastState = null; // FuelLevel lastFuel = null; // double motionRemaingHours = 4; // // try { // lastState = ImcMsgManager.getManager().getState(vehicle).lastEstimatedState(); // lastFuel = ImcMsgManager.getManager().getState(vehicle).lastFuelLevel(); // // if (lastState != null) // start = new SystemPositionAndAttitude(lastState); // // if (lastFuel != null) { // LinkedHashMap<String, String> opmodes = lastFuel.getOpmodes(); // motionRemaingHours = Double.parseDouble(opmodes.get("Full")); // } // } // catch (Exception e) { // NeptusLog.pub().error("Error getting info from main vehicle", e); // } // // overlay = new PlanSimulationOverlay(plan, 0, motionRemaingHours, start); // PlanSimulation3D.showSimulation(getConsole(), overlay, plan); // // } // }; // popup.add(act); } popup.show(source, (int) mousePoint.getX(), (int) mousePoint.getY()); } } private void refreshPropertiesManeuver() { if (getPropertiesPanel().getManeuver() != null) { getPropertiesPanel().setManeuver(getPropertiesPanel().getManeuver()); } } protected AbstractAction getPasteAction(final Point mousePoint) { Transferable contents = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); boolean enabled = false; boolean hasTransferableText = (contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor); if (hasTransferableText) { try { String text = (String) contents.getTransferData(DataFlavor.stringFlavor); if (text.startsWith(maneuverPreamble)) enabled = true; } catch (Exception e) { NeptusLog.pub().error(e); } } AbstractAction paste = new AbstractAction(I18n.text("Paste maneuver from clipboard")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { Transferable contents = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); try { String text = (String) contents.getTransferData(DataFlavor.stringFlavor); String xml = text.substring(maneuverPreamble.length()); Document doc = DocumentHelper.parseText(xml); String maneuverType = doc.getRootElement().getName(); Maneuver m = mf.getManeuver(maneuverType); if (m != null) { m.loadFromXML(xml); m.setId(getNewManeuverName(maneuverType)); if (m instanceof LocatedManeuver) { LocationType originalPos = ((LocatedManeuver) m).getManeuverLocation(); double originalDepth = originalPos.getAllZ(); LocationType pos = renderer.getRealWorldLocation(mousePoint); pos.setAbsoluteDepth(originalDepth); ((LocatedManeuver) m).getManeuverLocation().setLocation(pos); } plan.getGraph().addManeuver(m); plan.getGraph().addTransition(plan.getGraph().getLastManeuver().getId(), m.getId(), defaultCondition); repaint(); } } catch (Exception ex) { GuiUtils.errorMessage(getConsole(), ex); } } }; paste.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getImage("images/menus/editpaste.png"))); paste.setEnabled(enabled); return paste; } @Override public void mouseDragged(MouseEvent e, StateRenderer2D renderer) { if (delegate != null) { delegate.mouseDragged(e, renderer); getPropertiesPanel().setManeuver((Maneuver) delegate); return; } if (lastDragPoint == null && selectedManeuver != null) { selectedManeuver = planElem.iterateManeuverBack(e.getPoint()); getPropertiesPanel().setManeuver(selectedManeuver); getPropertiesPanel().getEditBtn().setEnabled(selectedManeuver instanceof StateRendererInteraction); getPropertiesPanel().getEditBtn().setSelected(false); getPropertiesPanel().setManager(manager); getPropertiesPanel().setPlan(plan); } if (selectedManeuver != null && selectedManeuver instanceof LocatedManeuver) { if (lastDragPoint != null) { maneuverWasMoved = true; double diffX = e.getPoint().getX() - lastDragPoint.getX(); double diffY = e.getPoint().getY() - lastDragPoint.getY(); if (e.isControlDown()) { LocationType oldPt = renderer.getRealWorldLocation(lastDragPoint); LocationType newPt = renderer.getRealWorldLocation(e.getPoint()); double[] offsets = newPt.getOffsetFrom(oldPt); planElem.translatePlan(offsets[0], offsets[1], 0); lastDragPoint = e.getPoint(); planTranslated = true; } else { if (e.isShiftDown()) { double ammount = Math.toRadians(lastDragPoint.getY() - e.getPoint().getY()); planElem.rotatePlan((LocatedManeuver) selectedManeuver, ammount); lastDragPoint = e.getPoint(); planRotatedRads += ammount; } else { Point2D newManPos = planElem.translateManeuverPosition(selectedManeuver.getId(), diffX, diffY); ManeuverLocation loc = ((LocatedManeuver) selectedManeuver).getManeuverLocation(); loc.setLocation(renderer.getRealWorldLocation(newManPos)); ((LocatedManeuver) selectedManeuver).setManeuverLocation(loc); lastDragPoint = newManPos; } } renderer.repaint(); } else { lastDragPoint = e.getPoint(); renderer.setCursor(Cursor.getDefaultCursor()); } } else { super.mouseDragged(e, renderer); } } @Override public void mouseMoved(MouseEvent e, StateRenderer2D renderer) { if (plan == null || selectedManeuver != null) { super.mouseMoved(e, renderer); return; } String[] mans = planElem.getManeuversUnder(e.getPoint()); if (mans.length > 0) { renderer.setCursor(Cursor.getDefaultCursor()); String text = plan.getGraph().getManeuver(mans[0]).getTooltipText(); for (int i = 1; i < mans.length && i < 3; i++) { String tooltip = plan.getGraph().getManeuver(mans[i]).getTooltipText(); if (tooltip.startsWith("<html>")) tooltip = tooltip.substring(6); text = text + "<br><br>" + tooltip; } if (mans.length >= 4) text = text + "<br><b>(...)</b>"; renderer.setToolTipText(text); } super.mouseMoved(e, renderer); } @Override public void mousePressed(MouseEvent event, StateRenderer2D renderer) { planTranslated = false; planRotatedRads = 0; if (delegate != null) { delegate.mousePressed(event, renderer); getPropertiesPanel().setManeuver((Maneuver) delegate); return; } if (event.getButton() == MouseEvent.BUTTON1) { selectedManeuver = planElem.iterateManeuverUnder(event.getPoint()); if (selectedManeuver != null && selectedManeuver instanceof LocatedManeuver) { maneuverLocationBeforeMoving = ((LocatedManeuver) selectedManeuver).getManeuverLocation(); } if (selectedManeuver != getPropertiesPanel().getManeuver()) { if (getPropertiesPanel().getManeuver() != null && getPropertiesPanel().isChanged()) { ManeuverChanged edit = new ManeuverChanged(getPropertiesPanel().getManeuver(), plan, getPropertiesPanel().getBeforeXml()); manager.addEdit(edit); } getPropertiesPanel().setPlan(plan); // This call has to be before setManeuver (pdias 20130822) getPropertiesPanel().setManeuver(selectedManeuver); getPropertiesPanel().setManager(manager); getPropertiesPanel().getEditBtn().setEnabled(selectedManeuver instanceof StateRendererInteraction); getPropertiesPanel().getEditBtn().setSelected(false); } } else { super.mousePressed(event, renderer); } } @Override public void mouseReleased(MouseEvent e, StateRenderer2D renderer) { if (delegate != null) { delegate.mouseReleased(e, renderer); getPropertiesPanel().setManeuver((Maneuver) delegate); return; } if (selectedManeuver != null) { if (planTranslated) { LocatedManeuver locProvider = (LocatedManeuver) selectedManeuver; LocationType curLocation = locProvider.getManeuverLocation(); double[] offsets = curLocation.getOffsetFrom(maneuverLocationBeforeMoving); PlanTranslated edit = new PlanTranslated(plan, offsets[1], offsets[0]); manager.addEdit(edit); } else if (maneuverWasMoved) { LocatedManeuver locProvider = (LocatedManeuver) selectedManeuver; LocationType curLocation = locProvider.getManeuverLocation(); locProvider.getManeuverLocation().setLocation(maneuverLocationBeforeMoving); String xml = selectedManeuver.getManeuverXml(); locProvider.getManeuverLocation().setLocation(curLocation); ManeuverChanged edit = new ManeuverChanged(selectedManeuver, plan, xml); manager.addEdit(edit); } else if (planRotatedRads != 0) { PlanRotated edit = new PlanRotated(plan, (LocatedManeuver) selectedManeuver, planRotatedRads); manager.addEdit(edit); } maneuverWasMoved = false; maneuverLocationBeforeMoving = null; planElem.recalculateManeuverPositions(renderer); getPropertiesPanel().setManeuver(selectedManeuver); getPropertiesPanel().getEditBtn().setEnabled(selectedManeuver instanceof StateRendererInteraction); getPropertiesPanel().getEditBtn().setSelected(false); getPropertiesPanel().setPlan(plan); getPropertiesPanel().setManager(manager); } lastDragPoint = null; selectedManeuver = null; mouseMoved(e, renderer); super.mouseReleased(e, renderer); } @Override public void keyPressed(KeyEvent event, StateRenderer2D source) { if (delegate != null) delegate.keyPressed(event, source); else super.keyPressed(event, source); } @Override public void keyReleased(KeyEvent event, StateRenderer2D source) { if (delegate != null) delegate.keyReleased(event, source); else super.keyReleased(event, source); } @Override public void keyTyped(KeyEvent event, StateRenderer2D source) { if (delegate != null) delegate.keyTyped(event, source); else super.keyTyped(event, source); } private void removeManeuver(String manID) { Maneuver man = plan.getGraph().getManeuver(manID); Maneuver next = plan.getGraph().getFollowingManeuver(manID); Vector<TransitionType> addedTransitions = new Vector<TransitionType>(); Vector<TransitionType> removedTransitions = new Vector<TransitionType>(); if (next != null) removedTransitions.add(plan.getGraph().removeTransition(manID, next.getId())); for (Maneuver previous : plan.getGraph().getPreviousManeuvers(manID)) { removedTransitions.add(plan.getGraph().removeTransition(previous.getId(), manID)); if (next != null && previous != null) addedTransitions.add(plan.getGraph().addTransition(previous.getId(), next.getId(), defaultCondition)); } plan.getGraph().removeManeuver(man); planElem.recalculateManeuverPositions(renderer); renderer.repaint(); if (man.isInitialManeuver() && next != null) { plan.getGraph().setInitialManeuver(next.getId()); } ManeuverRemoved edit = new ManeuverRemoved(man, plan, addedTransitions, removedTransitions, man.isInitialManeuver()); manager.addEdit(edit); } private Maneuver addManeuverAfter(String manType, String manID) { Maneuver nextMan = plan.getGraph().getFollowingManeuver(manID); Maneuver previousMan = plan.getGraph().getManeuver(manID); Maneuver newMan = mf.getManeuver(manType); if (newMan == null) { GuiUtils.errorMessage(this, I18n.text("Error adding maneuver"), I18n.textf("The maneuver %maneuverType can't be added", manType)); return null; } newMan.setId(getNewManeuverName(manType)); if (newMan instanceof LocatedManeuver) ((LocatedManeuver) newMan).getManeuverLocation().setLocation(renderer.getCenter()); if (newMan instanceof LocatedManeuver && previousMan instanceof LocatedManeuver && nextMan instanceof LocatedManeuver) { ManeuverLocation loc1 = ((LocatedManeuver) previousMan).getManeuverLocation().clone(); ManeuverLocation loc2 = ((LocatedManeuver) nextMan).getManeuverLocation().clone(); double offsets[] = loc2.getOffsetFrom(loc1); loc1.translatePosition(offsets[0] / 2, offsets[1] / 2, 0); loc1.setDepth(loc1.getDepth()); ((LocatedManeuver) newMan).setManeuverLocation(loc1); } else { if (newMan instanceof LocatedManeuver && previousMan instanceof LocatedManeuver) { LocationType loc1 = new LocationType(((LocatedManeuver) previousMan).getManeuverLocation()); loc1.translatePosition(0, 30, 0); ((LocatedManeuver) newMan).getManeuverLocation().setLocation(loc1); } if (newMan instanceof LocatedManeuver && nextMan instanceof LocatedManeuver) { LocationType loc1 = new LocationType(((LocatedManeuver) nextMan).getManeuverLocation()); loc1.translatePosition(0, -30, 0); ((LocatedManeuver) newMan).getManeuverLocation().setLocation(loc1); } } if (plan.getGraph().getExitingTransitions(previousMan).size() != 0) { for (TransitionType exitingTrans : plan.getGraph().getExitingTransitions(previousMan)) { plan.getGraph().removeTransition(exitingTrans.getSourceManeuver(), exitingTrans.getTargetManeuver()); } } plan.getGraph().addManeuver(newMan); plan.getGraph().addTransition(previousMan.getId(), newMan.getId(), defaultCondition); if (nextMan != null) { plan.getGraph().removeTransition(previousMan.getId(), nextMan.getId()); plan.getGraph().addTransition(newMan.getId(), nextMan.getId(), defaultCondition); } return newMan; } private Maneuver addManeuverAtBeginning(String manType, Point loc) { Maneuver man = addManeuverAtEnd(loc, manType); for (TransitionType t : plan.getGraph().getIncomingTransitions(man)) { plan.getGraph().removeTransition(t.getSourceManeuver(), t.getTargetManeuver()); } String initial = plan.getGraph().getInitialManeuverId(); plan.getGraph().addTransition(man.getId(), initial, defaultCondition); plan.getGraph().setInitialManeuver(man.getId()); return man; } private Maneuver addManeuverAtEnd(Point loc, String manType) { Maneuver man = mf.getManeuver(manType); Vector<TransitionType> addedTransitions = new Vector<TransitionType>(); Vector<TransitionType> removedTransitions = new Vector<TransitionType>(); LocationType worldLoc = renderer.getRealWorldLocation(loc); if (man == null) { GuiUtils.errorMessage(this, I18n.text("Error adding maneuver"), I18n.textf("The maneuver %maneuverType can't be added", manType)); return null; } man.setId(getNewManeuverName(manType)); Maneuver lastMan = plan.getGraph().getLastManeuver(); if (lastMan != null && lastMan != man) { if (plan.getGraph().getExitingTransitions(lastMan).size() != 0) { for (TransitionType exitingTrans : plan.getGraph().getExitingTransitions(lastMan)) { removedTransitions.add(plan.getGraph().removeTransition(exitingTrans.getSourceManeuver(), exitingTrans.getTargetManeuver())); } } if (man.getType().equals(lastMan.getType())) { String id = man.getId(); man = (Maneuver) lastMan.clone(); //man.getStartActions().getPayloadConfigs().clear(); //man.getStartActions().getActionMsgs().clear(); //man.getEndActions().getPayloadConfigs().clear(); //man.getEndActions().getActionMsgs().clear(); man.setId(id); } if (man instanceof LocatedManeuver) { ManeuverLocation lt = new ManeuverLocation(); if (lastMan instanceof LocatedManeuver) lt = ((LocatedManeuver) lastMan).getManeuverLocation().clone(); lt.setLocation(worldLoc); ((LocatedManeuver) man).setManeuverLocation(lt); } man.cloneActions(lastMan); addedTransitions.add(plan.getGraph().addTransition(lastMan.getId(), man.getId(), defaultCondition)); } if (man instanceof LocatedManeuver) { ManeuverLocation l = new ManeuverLocation(); l.setLocation(renderer.getRealWorldLocation(loc)); l.setZ(((LocatedManeuver) man).getManeuverLocation().getZ()); l.setZUnits(((LocatedManeuver) man).getManeuverLocation().getZUnits()); ((LocatedManeuver) man).setManeuverLocation(l); } plan.getGraph().addManeuver(man); parsePlan(); manager.addEdit(new ManeuverAdded(man, plan, addedTransitions, removedTransitions)); getPropertiesPanel().setManeuver(man); if (lastMan == null) { selectedManeuver = null; getPropertiesPanel().setManeuver(null); } return man; } private String getNewManeuverName(String manType) { int i = 1; while (plan.getGraph().getManeuver(manType + i) != null) i++; return manType + i; } public void reset() { planElem.recalculateManeuverPositions(renderer); repaint(); } public PlanElement getPlanElem() { return planElem; } public StateRenderer2D getRenderer() { return renderer; } public MissionType getMission() { return mission; } @Override public void missionReplaced(MissionType mission) { this.mission = mission; } @Override public void missionUpdated(MissionType mission) { this.mission = mission; } @Override public void initSubPanel() { this.mission = getConsole().getMission(); } }
true
true
public void mouseClicked(MouseEvent event, StateRenderer2D source) { final StateRenderer2D renderer = source; final Point2D mousePoint = event.getPoint(); if (delegate != null) { if (event.getClickCount() == 2) { delegate.setActive(false, source); getPropertiesPanel().setManeuver(getPropertiesPanel().getManeuver()); getPropertiesPanel().getEditBtn().setSelected(false); planElem.recalculateManeuverPositions(source); delegate = null; if (xml != null) { ManeuverChanged edit = new ManeuverChanged(getPropertiesPanel().getManeuver(), plan, xml); xml = null; manager.addEdit(edit); } return; } else { delegate.mouseClicked(event, source); return; } } if (event.getClickCount() == 2) { planElem.iterateManeuverBack(event.getPoint()); final Maneuver man = planElem.iterateManeuverBack(event.getPoint()); if (man != null) { if (man instanceof StateRendererInteraction) { delegate = (StateRendererInteraction) man; ((StateRendererInteraction) man).setActive(true, source); getPropertiesPanel().getEditBtn().setSelected(true); xml = getPropertiesPanel().getManeuver().getManeuverXml(); } return; } } if (event.isControlDown() && event.getButton() == MouseEvent.BUTTON1) { Maneuver m = plan.getGraph().getLastManeuver(); addManeuverAtEnd(event.getPoint(), m.getType()); return; } if (event.getButton() == MouseEvent.BUTTON3) { JPopupMenu popup = new JPopupMenu(); AbstractAction copy = new AbstractAction(I18n.text("Copy location")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { CoordinateUtil.copyToClipboard(renderer.getRealWorldLocation(mousePoint)); } }; copy.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getImage("images/menus/editcopy.png"))); popup.add(copy); final Maneuver[] mans = planElem.getAllInterceptedManeuvers(event.getPoint()); popup.addSeparator(); if (mans.length == 1) { for (AbstractAction act : getActionsForManeuver(mans[0], (Point) mousePoint)) popup.add(act); } else if (mans.length > 1) { for (Maneuver m : mans) { JMenu subMenu = new JMenu(m.getId()); if (m instanceof LocatedManeuver) { subMenu.setText(m.getId() + " (" + (GuiUtils.getNeptusDecimalFormat(1).format(((LocatedManeuver) m) .getManeuverLocation().getAllZ())) + " m)"); } subMenu.setIcon(new ImageIcon(ImageUtils.getImage("images/menus/plan.png"))); for (AbstractAction act : getActionsForManeuver(m, (Point) mousePoint)) subMenu.add(act); popup.add(subMenu); } } else { if (plan.hasInitialManeuver()) { JMenu planSettings = new JMenu(I18n.text("Change existing Maneuvers")); AbstractAction pDepth = new AbstractAction(I18n.text("Plan depth / altitude...")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { ManeuverLocation loc = new ManeuverLocation(); for (Maneuver m : plan.getGraph().getAllManeuvers()) { if (m instanceof LocatedManeuver) { loc = ((LocatedManeuver) m).getManeuverLocation().clone(); break; } } boolean newZ = ZValueSelector.showHeightDepthDialog(getConsole().getMainPanel(), loc, I18n.text("Plan depth / altitude")); if (newZ) { planElem.setPlanZ(loc.getZ(), loc.getZUnits()); refreshPropertiesManeuver(); } } }; pDepth.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); planSettings.add(pDepth); AbstractAction pVel = new AbstractAction(I18n.text("Plan speed...")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { String[] optionsI18n = { I18n.text("m/s"), I18n.text("RPM"), "%" }; String[] optionsNotI18n = { "m/s", "RPM", "%" }; DefaultProperty dp = planElem.getLastSetProperties().get("Speed units"); String curValueNotI18n = "m/s"; if (dp != null) curValueNotI18n = dp.getValue().toString(); Object resp = JOptionPane.showInputDialog(getConsole(), I18n.text("Please choose the speed units"), I18n.text("Set plan speed"), JOptionPane.QUESTION_MESSAGE, null, optionsI18n, I18n.text(curValueNotI18n)); if (resp == null) return; String velUnitI18n = resp.toString(); String velUnitNotI18n = "m/s"; for (int i = 0; i < optionsI18n.length; i++) { if (velUnitI18n.equals(optionsI18n[i])) { velUnitNotI18n = optionsNotI18n[i]; break; } } double velocity = 0; boolean validVel = false; while (!validVel) { double curSpeed = 1.3; dp = planElem.getLastSetProperties().get("Speed"); if (dp != null) curSpeed = (Double) dp.getValue(); String res = JOptionPane.showInputDialog(getConsole(), I18n.textf("Enter new speed (%speedUnit)", velUnitI18n), curSpeed); if (res == null) return; try { velocity = Double.parseDouble(res); validVel = true; } catch (Exception ex) { ex.printStackTrace(); GuiUtils.errorMessage(getConsole(), I18n.text("Set plan speed"), I18n.text("Speed must be a numeric value")); } } DefaultProperty propVel = new DefaultProperty(); propVel.setName("Speed"); propVel.setValue(velocity); propVel.setType(Double.class); propVel.setDisplayName(I18n.text("Speed")); planElem.setPlanProperty(propVel); DefaultProperty propVelUnits = new DefaultProperty(); propVelUnits.setName("Speed units"); propVelUnits.setValue(velUnitNotI18n); // velUnitI18n propVelUnits.setType(String.class); propVelUnits.setDisplayName(I18n.text("Speed units")); planElem.setPlanProperty(propVelUnits); refreshPropertiesManeuver(); } }; pVel.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); planSettings.add(pVel); AbstractAction pPayload = new AbstractAction(I18n.text("Payload settings...")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { // PropertiesEditor editor = new PropertiesEditor(); Goto pivot = new Goto(); PropertySheetPanel psp = new PropertySheetPanel(); psp.setEditorFactory(PropertiesEditor.getPropertyEditorRegistry()); psp.setRendererFactory(PropertiesEditor.getPropertyRendererRegistry()); psp.setMode(PropertySheet.VIEW_AS_CATEGORIES); psp.setToolBarVisible(false); psp.setSortingCategories(true); psp.setDescriptionVisible(true); ManeuverPayloadConfig payloadConfig = new ManeuverPayloadConfig(plan.getVehicle(), pivot, psp); DefaultProperty[] properties = payloadConfig.getProperties(); // FIXME localize these properties! // Vector<DefaultProperty> result = new Vector<DefaultProperty>(); // PropertiesEditor.localizeProperties(Arrays.asList(properties), result); // DefaultProperty[] propertiesLocalized = properties;//result.toArray(new // DefaultProperty[0]); psp.setProperties(properties); final PropertySheetDialog propertySheetDialog = PropertiesEditor.createWindow(getConsole(), true, psp, "Payload Settings to apply to entire plan"); if (propertySheetDialog.ask()) { // DefaultProperty[] propsUnlocalized = PropertiesEditor.unlocalizeProps(original, // psp.getProperties()); payloadConfig.setProperties(properties); Vector<IMCMessage> startActions = new Vector<>(); startActions.addAll(Arrays.asList(pivot.getStartActions().getAllMessages())); for (Maneuver m : plan.getGraph().getAllManeuvers()) { m.getStartActions().parseMessages(startActions); NeptusLog.pub().info("<###> " + m.getId()); } refreshPropertiesManeuver(); } } }; pPayload.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); planSettings.add(pPayload); AbstractAction pVehicle = new AbstractAction(I18n.text("Set plan vehicles...")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { Window parentW = SwingUtilities.getWindowAncestor(getConsole()); String[] vehicles = VehicleSelectionDialog.showSelectionDialog(parentW, plan.getVehicles() .toArray(new VehicleType[0])); Vector<VehicleType> vts = new Vector<VehicleType>(); for (String v : vehicles) { vts.add(VehiclesHolder.getVehicleById(v)); } plan.setVehicles(vts); } }; pVehicle.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); planSettings.add(pVehicle); planSettings.setIcon(new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); popup.add(planSettings); // popup.addSeparator(); } AbstractAction pTransitions = new AbstractAction(I18n.text("Plan Transitions")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { Window parent = SwingUtilities.getWindowAncestor(getConsole()); if (parent == null) parent = SwingUtilities.getWindowAncestor(ConfigFetch.getSuperParentAsFrame()); JDialog transitions = new JDialog(parent, I18n.textf("Edit '%planName' plan transitions", plan.getId())); transitions.setModalityType(ModalityType.DOCUMENT_MODAL); transitions.getContentPane().add(new PlanTransitionsSimpleEditor(plan)); transitions.setSize(800, 500); GuiUtils.centerParent(transitions, getConsole()); transitions.setVisible(true); parsePlan(); renderer.repaint(); refreshPropertiesManeuver(); } }; pTransitions.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); popup.add(pTransitions); // popup.addSeparator(); JMenu pStatistics = PlanUtil.getPlanStatisticsAsJMenu(plan, I18n.text("Edited Plan Statistics")); pStatistics.setIcon(new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); popup.add(pStatistics); popup.addSeparator(); List<String> names = Arrays.asList(mf.getAvailableManeuversIDs()); Collections.sort(names); ImageIcon icon = ImageUtils.getIcon("images/led_none.png"); for (final String manName : names) { String manNameStr = I18n.text(manName); AbstractAction act = new AbstractAction(I18n.textf("Add %maneuverName", manNameStr), icon) { private static final long serialVersionUID = 1L; private final Point2D mousePos = mousePoint; @Override public void actionPerformed(ActionEvent evt) { String maneuverName = manName; addManeuverAtEnd((Point) mousePos, maneuverName); planElem.recalculateManeuverPositions(renderer); renderer.repaint(); } }; popup.add(act); } popup.add(getPasteAction((Point) mousePoint)); // AbstractAction act = new AbstractAction(I18n.text("Simulate plan"), null) { // private static final long serialVersionUID = 1L; // // @Override // public void actionPerformed(ActionEvent evt) { // // String vehicle = getConsole().getMainSystem(); // LocationType startLoc = plan.getMissionType().getStartLocation(); // SystemPositionAndAttitude start = new SystemPositionAndAttitude(startLoc, 0, 0, 0); // EstimatedState lastState = null; // FuelLevel lastFuel = null; // double motionRemaingHours = 4; // // try { // lastState = ImcMsgManager.getManager().getState(vehicle).lastEstimatedState(); // lastFuel = ImcMsgManager.getManager().getState(vehicle).lastFuelLevel(); // // if (lastState != null) // start = new SystemPositionAndAttitude(lastState); // // if (lastFuel != null) { // LinkedHashMap<String, String> opmodes = lastFuel.getOpmodes(); // motionRemaingHours = Double.parseDouble(opmodes.get("Full")); // } // } // catch (Exception e) { // NeptusLog.pub().error("Error getting info from main vehicle", e); // } // // overlay = new PlanSimulationOverlay(plan, 0, motionRemaingHours, start); // PlanSimulation3D.showSimulation(getConsole(), overlay, plan); // // } // }; // popup.add(act); } popup.show(source, (int) mousePoint.getX(), (int) mousePoint.getY()); } }
public void mouseClicked(MouseEvent event, StateRenderer2D source) { final StateRenderer2D renderer = source; final Point2D mousePoint = event.getPoint(); if (delegate != null) { if (event.getClickCount() == 2) { delegate.setActive(false, source); getPropertiesPanel().setManeuver(getPropertiesPanel().getManeuver()); getPropertiesPanel().getEditBtn().setSelected(false); planElem.recalculateManeuverPositions(source); delegate = null; if (xml != null) { ManeuverChanged edit = new ManeuverChanged(getPropertiesPanel().getManeuver(), plan, xml); xml = null; manager.addEdit(edit); } return; } else { delegate.mouseClicked(event, source); return; } } if (event.getClickCount() == 2) { planElem.iterateManeuverBack(event.getPoint()); final Maneuver man = planElem.iterateManeuverBack(event.getPoint()); if (man != null) { if (man instanceof StateRendererInteraction) { delegate = (StateRendererInteraction) man; ((StateRendererInteraction) man).setActive(true, source); getPropertiesPanel().getEditBtn().setSelected(true); xml = getPropertiesPanel().getManeuver().getManeuverXml(); } return; } } if (event.isControlDown() && event.getButton() == MouseEvent.BUTTON1) { Maneuver m = plan.getGraph().getLastManeuver(); addManeuverAtEnd(event.getPoint(), m.getType()); return; } if (event.getButton() == MouseEvent.BUTTON3) { JPopupMenu popup = new JPopupMenu(); AbstractAction copy = new AbstractAction(I18n.text("Copy location")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { CoordinateUtil.copyToClipboard(renderer.getRealWorldLocation(mousePoint)); } }; copy.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getImage("images/menus/editcopy.png"))); popup.add(copy); final Maneuver[] mans = planElem.getAllInterceptedManeuvers(event.getPoint()); popup.addSeparator(); if (mans.length == 1) { for (AbstractAction act : getActionsForManeuver(mans[0], (Point) mousePoint)) popup.add(act); } else if (mans.length > 1) { for (Maneuver m : mans) { JMenu subMenu = new JMenu(m.getId()); if (m instanceof LocatedManeuver) { subMenu.setText(m.getId() + " (" + (GuiUtils.getNeptusDecimalFormat(1).format(((LocatedManeuver) m) .getManeuverLocation().getAllZ())) + " m)"); } subMenu.setIcon(new ImageIcon(ImageUtils.getImage("images/menus/plan.png"))); for (AbstractAction act : getActionsForManeuver(m, (Point) mousePoint)) subMenu.add(act); popup.add(subMenu); } } else { if (plan.hasInitialManeuver()) { JMenu planSettings = new JMenu(I18n.text("Change existing maneuvers")); AbstractAction pDepth = new AbstractAction(I18n.text("Plan depth / altitude...")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { ManeuverLocation loc = new ManeuverLocation(); for (Maneuver m : plan.getGraph().getAllManeuvers()) { if (m instanceof LocatedManeuver) { loc = ((LocatedManeuver) m).getManeuverLocation().clone(); break; } } boolean newZ = ZValueSelector.showHeightDepthDialog(getConsole().getMainPanel(), loc, I18n.text("Plan depth / altitude")); if (newZ) { planElem.setPlanZ(loc.getZ(), loc.getZUnits()); refreshPropertiesManeuver(); } } }; pDepth.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); planSettings.add(pDepth); AbstractAction pVel = new AbstractAction(I18n.text("Plan speed...")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { String[] optionsI18n = { I18n.text("m/s"), I18n.text("RPM"), "%" }; String[] optionsNotI18n = { "m/s", "RPM", "%" }; DefaultProperty dp = planElem.getLastSetProperties().get("Speed units"); String curValueNotI18n = "m/s"; if (dp != null) curValueNotI18n = dp.getValue().toString(); Object resp = JOptionPane.showInputDialog(getConsole(), I18n.text("Please choose the speed units"), I18n.text("Set plan speed"), JOptionPane.QUESTION_MESSAGE, null, optionsI18n, I18n.text(curValueNotI18n)); if (resp == null) return; String velUnitI18n = resp.toString(); String velUnitNotI18n = "m/s"; for (int i = 0; i < optionsI18n.length; i++) { if (velUnitI18n.equals(optionsI18n[i])) { velUnitNotI18n = optionsNotI18n[i]; break; } } double velocity = 0; boolean validVel = false; while (!validVel) { double curSpeed = 1.3; dp = planElem.getLastSetProperties().get("Speed"); if (dp != null) curSpeed = (Double) dp.getValue(); String res = JOptionPane.showInputDialog(getConsole(), I18n.textf("Enter new speed (%speedUnit)", velUnitI18n), curSpeed); if (res == null) return; try { velocity = Double.parseDouble(res); validVel = true; } catch (Exception ex) { ex.printStackTrace(); GuiUtils.errorMessage(getConsole(), I18n.text("Set plan speed"), I18n.text("Speed must be a numeric value")); } } DefaultProperty propVel = new DefaultProperty(); propVel.setName("Speed"); propVel.setValue(velocity); propVel.setType(Double.class); propVel.setDisplayName(I18n.text("Speed")); planElem.setPlanProperty(propVel); DefaultProperty propVelUnits = new DefaultProperty(); propVelUnits.setName("Speed units"); propVelUnits.setValue(velUnitNotI18n); // velUnitI18n propVelUnits.setType(String.class); propVelUnits.setDisplayName(I18n.text("Speed units")); planElem.setPlanProperty(propVelUnits); refreshPropertiesManeuver(); } }; pVel.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); planSettings.add(pVel); AbstractAction pPayload = new AbstractAction(I18n.text("Payload settings...")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { // PropertiesEditor editor = new PropertiesEditor(); Goto pivot = new Goto(); PropertySheetPanel psp = new PropertySheetPanel(); psp.setEditorFactory(PropertiesEditor.getPropertyEditorRegistry()); psp.setRendererFactory(PropertiesEditor.getPropertyRendererRegistry()); psp.setMode(PropertySheet.VIEW_AS_CATEGORIES); psp.setToolBarVisible(false); psp.setSortingCategories(true); psp.setDescriptionVisible(true); ManeuverPayloadConfig payloadConfig = new ManeuverPayloadConfig(plan.getVehicle(), pivot, psp); DefaultProperty[] properties = payloadConfig.getProperties(); // FIXME localize these properties! // Vector<DefaultProperty> result = new Vector<DefaultProperty>(); // PropertiesEditor.localizeProperties(Arrays.asList(properties), result); // DefaultProperty[] propertiesLocalized = properties;//result.toArray(new // DefaultProperty[0]); psp.setProperties(properties); final PropertySheetDialog propertySheetDialog = PropertiesEditor.createWindow(getConsole(), true, psp, "Payload Settings to apply to entire plan"); if (propertySheetDialog.ask()) { // DefaultProperty[] propsUnlocalized = PropertiesEditor.unlocalizeProps(original, // psp.getProperties()); payloadConfig.setProperties(properties); Vector<IMCMessage> startActions = new Vector<>(); startActions.addAll(Arrays.asList(pivot.getStartActions().getAllMessages())); for (Maneuver m : plan.getGraph().getAllManeuvers()) { m.getStartActions().parseMessages(startActions); NeptusLog.pub().info("<###> " + m.getId()); } refreshPropertiesManeuver(); } } }; pPayload.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); planSettings.add(pPayload); AbstractAction pVehicle = new AbstractAction(I18n.text("Set plan vehicles...")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { Window parentW = SwingUtilities.getWindowAncestor(getConsole()); String[] vehicles = VehicleSelectionDialog.showSelectionDialog(parentW, plan.getVehicles() .toArray(new VehicleType[0])); Vector<VehicleType> vts = new Vector<VehicleType>(); for (String v : vehicles) { vts.add(VehiclesHolder.getVehicleById(v)); } plan.setVehicles(vts); } }; pVehicle.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); planSettings.add(pVehicle); planSettings.setIcon(new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); popup.add(planSettings); // popup.addSeparator(); } AbstractAction pTransitions = new AbstractAction(I18n.text("Plan Transitions")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { Window parent = SwingUtilities.getWindowAncestor(getConsole()); if (parent == null) parent = SwingUtilities.getWindowAncestor(ConfigFetch.getSuperParentAsFrame()); JDialog transitions = new JDialog(parent, I18n.textf("Edit '%planName' plan transitions", plan.getId())); transitions.setModalityType(ModalityType.DOCUMENT_MODAL); transitions.getContentPane().add(new PlanTransitionsSimpleEditor(plan)); transitions.setSize(800, 500); GuiUtils.centerParent(transitions, getConsole()); transitions.setVisible(true); parsePlan(); renderer.repaint(); refreshPropertiesManeuver(); } }; pTransitions.putValue(AbstractAction.SMALL_ICON, new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); popup.add(pTransitions); // popup.addSeparator(); JMenu pStatistics = PlanUtil.getPlanStatisticsAsJMenu(plan, I18n.text("Edited Plan Statistics")); pStatistics.setIcon(new ImageIcon(ImageUtils.getScaledImage("images/buttons/wizard.png", 16, 16))); popup.add(pStatistics); popup.addSeparator(); List<String> names = Arrays.asList(mf.getAvailableManeuversIDs()); Collections.sort(names); ImageIcon icon = ImageUtils.getIcon("images/led_none.png"); for (final String manName : names) { String manNameStr = I18n.text(manName); AbstractAction act = new AbstractAction(I18n.textf("Add %maneuverName", manNameStr), icon) { private static final long serialVersionUID = 1L; private final Point2D mousePos = mousePoint; @Override public void actionPerformed(ActionEvent evt) { String maneuverName = manName; addManeuverAtEnd((Point) mousePos, maneuverName); planElem.recalculateManeuverPositions(renderer); renderer.repaint(); } }; popup.add(act); } popup.add(getPasteAction((Point) mousePoint)); // AbstractAction act = new AbstractAction(I18n.text("Simulate plan"), null) { // private static final long serialVersionUID = 1L; // // @Override // public void actionPerformed(ActionEvent evt) { // // String vehicle = getConsole().getMainSystem(); // LocationType startLoc = plan.getMissionType().getStartLocation(); // SystemPositionAndAttitude start = new SystemPositionAndAttitude(startLoc, 0, 0, 0); // EstimatedState lastState = null; // FuelLevel lastFuel = null; // double motionRemaingHours = 4; // // try { // lastState = ImcMsgManager.getManager().getState(vehicle).lastEstimatedState(); // lastFuel = ImcMsgManager.getManager().getState(vehicle).lastFuelLevel(); // // if (lastState != null) // start = new SystemPositionAndAttitude(lastState); // // if (lastFuel != null) { // LinkedHashMap<String, String> opmodes = lastFuel.getOpmodes(); // motionRemaingHours = Double.parseDouble(opmodes.get("Full")); // } // } // catch (Exception e) { // NeptusLog.pub().error("Error getting info from main vehicle", e); // } // // overlay = new PlanSimulationOverlay(plan, 0, motionRemaingHours, start); // PlanSimulation3D.showSimulation(getConsole(), overlay, plan); // // } // }; // popup.add(act); } popup.show(source, (int) mousePoint.getX(), (int) mousePoint.getY()); } }
diff --git a/src/com/lolbro/nian/MainActivity.java b/src/com/lolbro/nian/MainActivity.java index 9ab3bec..d940ad1 100644 --- a/src/com/lolbro/nian/MainActivity.java +++ b/src/com/lolbro/nian/MainActivity.java @@ -1,387 +1,387 @@ package com.lolbro.nian; import org.andengine.engine.camera.SmoothCamera; import org.andengine.engine.camera.hud.HUD; import org.andengine.engine.handler.IUpdateHandler; import org.andengine.engine.handler.timer.ITimerCallback; import org.andengine.engine.handler.timer.TimerHandler; import org.andengine.engine.options.EngineOptions; import org.andengine.engine.options.ScreenOrientation; import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy; import org.andengine.entity.scene.Scene; import org.andengine.entity.scene.menu.MenuScene; import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener; import org.andengine.entity.scene.menu.item.IMenuItem; import org.andengine.entity.sprite.Sprite; import org.andengine.entity.text.Text; import org.andengine.entity.text.TextOptions; import org.andengine.entity.util.FPSCounter; import org.andengine.extension.physics.box2d.FixedStepPhysicsWorld; import org.andengine.extension.physics.box2d.PhysicsConnector; import org.andengine.extension.physics.box2d.PhysicsWorld; import org.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import org.andengine.opengl.font.Font; import org.andengine.opengl.font.FontFactory; import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.andengine.opengl.texture.region.ITextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.ui.activity.SimpleBaseGameActivity; import org.andengine.util.HorizontalAlign; import android.graphics.Typeface; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Manifold; import com.lolbro.nian.customs.AutoVerticalParallaxBackground; import com.lolbro.nian.customs.SwipeScene; import com.lolbro.nian.customs.SwipeScene.SwipeListener; import com.lolbro.nian.customs.VerticalParallaxBackground.VerticalParallaxEntity; import com.lolbro.nian.models.MObject; public class MainActivity extends SimpleBaseGameActivity implements SwipeListener, IUpdateHandler, ContactListener, IOnMenuItemClickListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 720; private static final int STEPS_PER_SECOND = 60; private static final int MAX_STEPS_PER_UPDATE = 1; private static final int MENU_RETRY = 1; private static final int PLAYER_SIZE = 64; private static final float LANE_STEP_SIZE = 140; private static final float PLAYER_ROLL_SPEED = 15f; private static final String PLAYER_USERDATA = "body_player"; public static final int JUMP_UP = SwipeListener.DIRECTION_UP; public static final int JUMP_DOWN = SwipeListener.DIRECTION_DOWN; public static final int JUMP_LEFT = SwipeListener.DIRECTION_LEFT; public static final int JUMP_RIGHT = SwipeListener.DIRECTION_RIGHT; public static final Vector2 PLAYER_HOME_POSITION = new Vector2(CAMERA_WIDTH/2, -CAMERA_HEIGHT/2 + PLAYER_SIZE*2); // public static final float LANE_LEFT = PLAYER_HOME_POSITION.x - LANE_STEP_SIZE; // public static final float LANE_MID = PLAYER_HOME_POSITION.x; // public static final float LANE_RIGHT = PLAYER_HOME_POSITION.x + LANE_STEP_SIZE; public static final Vector2 PLAYER_SPRITE_SPAWN = new Vector2(PLAYER_HOME_POSITION.x - PLAYER_SIZE/2, PLAYER_HOME_POSITION.y -PLAYER_SIZE/2); // =========================================================== // Fields // =========================================================== private SmoothCamera mCamera; private SwipeScene mScene; private PhysicsWorld mPhysicsWorld; private BitmapTextureAtlas mCharactersTexture; private ITextureRegion mPlayerRegion; private ITextureRegion mObstacleRegion; private BitmapTextureAtlas mMenuTexture; private ITextureRegion mMenuRetryRegion; private MObject mPlayer; private MObject mEnemy; private BitmapTextureAtlas mAutoParallaxBackgroundTexture; private ITextureRegion mParallaxLayerBack; private boolean moveLeft = false; private boolean moveRight = false; private boolean moveUp = false; private boolean moveDown = false; private float rollToPosition = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public EngineOptions onCreateEngineOptions() { this.mCamera = new SmoothCamera(0, -CAMERA_HEIGHT, CAMERA_WIDTH, CAMERA_HEIGHT, 10 * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, 10 * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, 10); //new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT) return new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new FillResolutionPolicy(), this.mCamera); } @Override protected void onCreateResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mAutoParallaxBackgroundTexture = new BitmapTextureAtlas(this.getTextureManager(), 512, 64); this.mParallaxLayerBack = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "floor_2.png", 0, 0); this.mAutoParallaxBackgroundTexture.load(); this.mCharactersTexture = new BitmapTextureAtlas(this.getTextureManager(), 64, 32, TextureOptions.BILINEAR); this.mPlayerRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mCharactersTexture, this, "player.png", 0, 0); this.mObstacleRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mCharactersTexture, this, "obstacle.png", 32, 0); this.mCharactersTexture.load(); this.mMenuTexture = new BitmapTextureAtlas(this.getTextureManager(), 256, 64, TextureOptions.BILINEAR); this.mMenuRetryRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "menu_retry.png", 0, 0); this.mMenuTexture.load(); } @Override protected Scene onCreateScene() { createScene(); this.mPhysicsWorld = new FixedStepPhysicsWorld(STEPS_PER_SECOND, MAX_STEPS_PER_UPDATE, new Vector2(0, 0), false, 10, 10); this.mPhysicsWorld.setContactListener(this); this.mScene.registerUpdateHandler(this.mPhysicsWorld); initBackground(); initPlayer(); spawnMob(); // showFPS(); return this.mScene; } @Override public synchronized void onResumeGame() { super.onResumeGame(); mScene.registerForGestureDetection(this, this); } @Override public void reset() { } @Override public void onSwipe(int direction) { jump(direction); } @Override public boolean onMenuItemClicked(MenuScene pMenuScene, IMenuItem pMenuItem, float pMenuItemLocalX, float pMenuItemLocalY) { // TODO Auto return true; } // =========================================================== // On update // =========================================================== @Override public void onUpdate(float pSecondsElapsed) { Body playerBody = mPlayer.getBody(); float x = mPlayer.getBodyPositionX(true); float y = mPlayer.getBodyPositionY(true); float rollMovement = PLAYER_ROLL_SPEED * pSecondsElapsed; if (moveUp == true) { - if (y > rollToPosition) { + if (y - rollMovement > rollToPosition) { playerBody.setTransform(x, y - rollMovement, 0); } else { moveUp = false; playerBody.setTransform(x, rollToPosition, 0); } } else if (moveDown == true) { - if (y < rollToPosition) { + if (y + rollMovement < rollToPosition) { playerBody.setTransform(x, y + rollMovement, 0); } else { moveDown = false; playerBody.setTransform(x, rollToPosition, 0); } } else if (moveLeft == true) { - if (x > rollToPosition) { + if (x - rollMovement > rollToPosition) { playerBody.setTransform(x - rollMovement, y, 0); } else { moveLeft = false; playerBody.setTransform(rollToPosition, y, 0); } } else if (moveRight == true) { - if (x < rollToPosition) { + if (x + rollMovement < rollToPosition) { playerBody.setTransform(x + rollMovement, y, 0); } else { moveRight = false; playerBody.setTransform(rollToPosition, y, 0); } } } // =========================================================== // On Contact // =========================================================== @Override public void beginContact(Contact contact) { Object userDataA = contact.getFixtureA().getBody().getUserData(); Object userDataB = contact.getFixtureB().getBody().getUserData(); if(userDataA.equals(PLAYER_USERDATA) || userDataB.equals(PLAYER_USERDATA)){ } } @Override public void endContact(Contact contact) { } @Override public void preSolve(Contact contact, Manifold oldManifold) { } @Override public void postSolve(Contact contact, ContactImpulse impulse) { } // =========================================================== // Methods // =========================================================== private void initBackground() { final VertexBufferObjectManager vertexBufferObjectManager = this.getVertexBufferObjectManager(); final AutoVerticalParallaxBackground autoParallaxBackground = new AutoVerticalParallaxBackground(0, 0, 0, 30); autoParallaxBackground.attachVerticalParallaxEntity(new VerticalParallaxEntity(-5.0f, new Sprite(0, 720, this.mParallaxLayerBack, vertexBufferObjectManager))); this.mScene.setBackground(autoParallaxBackground); } private void spawnMob() { this.mEnemy = new MObject( CAMERA_WIDTH/2-PLAYER_SIZE/2, -CAMERA_HEIGHT - PLAYER_SIZE, PLAYER_SIZE, PLAYER_SIZE, this.mObstacleRegion, this.getVertexBufferObjectManager(), mPhysicsWorld); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(mEnemy.getSprite(), mEnemy.getBody(), true, false)); this.mScene.attachChild(mEnemy.getSprite()); } private void initPlayer() { this.mPlayer = new MObject( PLAYER_SPRITE_SPAWN.x, PLAYER_SPRITE_SPAWN.y, PLAYER_SIZE, PLAYER_SIZE, this.mPlayerRegion, this.getVertexBufferObjectManager(), mPhysicsWorld); this.mPlayer.getBody().setUserData(PLAYER_USERDATA); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(mPlayer.getSprite(), mPlayer.getBody(), true, false)); this.mScene.attachChild(mPlayer.getSprite()); } private void createScene() { this.mScene = new SwipeScene(); // final SpriteMenuItem retryMenuItem = new SpriteMenuItem(MENU_RETRY, this.mMenuRetryRegion, this.getVertexBufferObjectManager()); // retryMenuItem.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); // this.mScene.addMenuItem(retryMenuItem); // // this.mScene.buildAnimations(); this.mScene.registerUpdateHandler(this); // this.mScene.setOnMenuItemClickListener(this); } /* Methods for debugging */ private void showFPS() { final FPSCounter fpsCounter = new FPSCounter(); this.mEngine.registerUpdateHandler(fpsCounter); HUD hud=new HUD(); Font font = FontFactory.create(this.getFontManager(), this.getTextureManager(), 256, 256, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32); font.load(); final Text text = new Text(10, 10, font, "FPS: ", 20, new TextOptions(HorizontalAlign.CENTER), this.getVertexBufferObjectManager()); hud.attachChild(text); mCamera.setHUD(hud); mScene.registerUpdateHandler(new TimerHandler(1 / 20.0f, true, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { text.setText("FPS: " + fpsCounter.getFPS()); } })); } /* Methods for moving */ private void jump(int direction){ if(isMoving()){ return; } Vector2 playerPosition = mPlayer.getBodyPosition(false); switch(direction){ case JUMP_UP: if ((int)playerPosition.y >= PLAYER_HOME_POSITION.y) { rollToPosition = (int)playerPosition.y - LANE_STEP_SIZE; rollToPosition /= PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT; moveUp = true; } break; case JUMP_DOWN: if ((int)playerPosition.y <= PLAYER_HOME_POSITION.y) { rollToPosition = (int)playerPosition.y + LANE_STEP_SIZE; rollToPosition /= PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT; moveDown = true; } break; case JUMP_LEFT: if ((int)playerPosition.x >= PLAYER_HOME_POSITION.x) { rollToPosition = (int)playerPosition.x - LANE_STEP_SIZE; rollToPosition /= PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT; moveLeft = true; } break; case JUMP_RIGHT: if ((int)playerPosition.x <= PLAYER_HOME_POSITION.x) { rollToPosition = (int)playerPosition.x + LANE_STEP_SIZE; rollToPosition /= PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT; moveRight = true; } break; } } private boolean isMoving() { return (moveLeft == true || moveRight == true || moveUp == true || moveDown == true); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
false
true
public void onUpdate(float pSecondsElapsed) { Body playerBody = mPlayer.getBody(); float x = mPlayer.getBodyPositionX(true); float y = mPlayer.getBodyPositionY(true); float rollMovement = PLAYER_ROLL_SPEED * pSecondsElapsed; if (moveUp == true) { if (y > rollToPosition) { playerBody.setTransform(x, y - rollMovement, 0); } else { moveUp = false; playerBody.setTransform(x, rollToPosition, 0); } } else if (moveDown == true) { if (y < rollToPosition) { playerBody.setTransform(x, y + rollMovement, 0); } else { moveDown = false; playerBody.setTransform(x, rollToPosition, 0); } } else if (moveLeft == true) { if (x > rollToPosition) { playerBody.setTransform(x - rollMovement, y, 0); } else { moveLeft = false; playerBody.setTransform(rollToPosition, y, 0); } } else if (moveRight == true) { if (x < rollToPosition) { playerBody.setTransform(x + rollMovement, y, 0); } else { moveRight = false; playerBody.setTransform(rollToPosition, y, 0); } } }
public void onUpdate(float pSecondsElapsed) { Body playerBody = mPlayer.getBody(); float x = mPlayer.getBodyPositionX(true); float y = mPlayer.getBodyPositionY(true); float rollMovement = PLAYER_ROLL_SPEED * pSecondsElapsed; if (moveUp == true) { if (y - rollMovement > rollToPosition) { playerBody.setTransform(x, y - rollMovement, 0); } else { moveUp = false; playerBody.setTransform(x, rollToPosition, 0); } } else if (moveDown == true) { if (y + rollMovement < rollToPosition) { playerBody.setTransform(x, y + rollMovement, 0); } else { moveDown = false; playerBody.setTransform(x, rollToPosition, 0); } } else if (moveLeft == true) { if (x - rollMovement > rollToPosition) { playerBody.setTransform(x - rollMovement, y, 0); } else { moveLeft = false; playerBody.setTransform(rollToPosition, y, 0); } } else if (moveRight == true) { if (x + rollMovement < rollToPosition) { playerBody.setTransform(x + rollMovement, y, 0); } else { moveRight = false; playerBody.setTransform(rollToPosition, y, 0); } } }
diff --git a/src/org/jruby/util/CommandlineParser.java b/src/org/jruby/util/CommandlineParser.java index e15e182ab..44761adfc 100644 --- a/src/org/jruby/util/CommandlineParser.java +++ b/src/org/jruby/util/CommandlineParser.java @@ -1,321 +1,321 @@ /***** BEGIN LICENSE BLOCK ***** * Version: CPL 1.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Common Public * License Version 1.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.eclipse.org/legal/cpl-v10.html * * 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. * * Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se> * Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de> * Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de> * Copyright (C) 2005 Jason Voegele <jason@jvoegele.com> * Copyright (C) 2005 Tim Azzopardi <tim@tigerfive.com> * Copyright (C) 2006 Charles O Nutter <headius@headius.com> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the CPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the CPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.jruby.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.jruby.Main; import org.jruby.exceptions.MainExitException; public class CommandlineParser { private final String[] arguments; private Main main; private ArrayList loadPaths = new ArrayList(); private StringBuffer inlineScript = new StringBuffer(); private String scriptFileName = null; private ArrayList requiredLibraries = new ArrayList(); private boolean benchmarking = false; private boolean assumeLoop = false; private boolean assumePrinting = false; private boolean processLineEnds = false; private boolean split = false; private boolean verbose = false; private boolean debug = false; private boolean showVersion = false; private String[] scriptArguments = null; private boolean shouldRunInterpreter = true; private boolean objectSpaceEnabled = true; private boolean compilerEnabled = false; private String encoding = "ISO8859_1"; public int argumentIndex = 0; public int characterIndex = 0; public CommandlineParser(Main main, String[] arguments) { this.arguments = arguments; this.main = main; processArguments(); } private void processArguments() { while (argumentIndex < arguments.length && isInterpreterArgument(arguments[argumentIndex])) { processArgument(); argumentIndex++; } if (! hasInlineScript()) { if (argumentIndex < arguments.length) { setScriptFileName(arguments[argumentIndex]); //consume the file name argumentIndex++; } } // Remaining arguments are for the script itself scriptArguments = new String[arguments.length - argumentIndex]; System.arraycopy(arguments, argumentIndex, getScriptArguments(), 0, getScriptArguments().length); } private static boolean isInterpreterArgument(String argument) { return argument.charAt(0) == '-'; } private void processArgument() { String argument = arguments[argumentIndex]; FOR : for (characterIndex = 1; characterIndex < argument.length(); characterIndex++) { switch (argument.charAt(characterIndex)) { case 'h' : main.printUsage(); shouldRunInterpreter = false; break; case 'I' : String s = grabValue(" -I must be followed by a directory name to add to lib path"); - String[] ls = s.split(":"); + String[] ls = s.split(java.io.File.pathSeparator); for(int i=0;i<ls.length;i++) { loadPaths.add(ls[i]); } break FOR; case 'r' : requiredLibraries.add(grabValue("-r must be followed by a package to require")); break FOR; case 'e' : inlineScript.append(grabValue(" -e must be followed by an expression to evaluate")); inlineScript.append('\n'); break FOR; case 'b' : benchmarking = true; break; case 'p' : assumePrinting = true; assumeLoop = true; break; case 'O' : objectSpaceEnabled = false; break; case 'C' : compilerEnabled = true; break; case 'n' : assumeLoop = true; break; case 'a' : split = true; break; case 'd' : debug = true; verbose = true; break; case 'l' : processLineEnds = true; break; case 'v' : verbose = true; setShowVersion(true); break; case 'w' : verbose = true; break; case 'K': // FIXME: No argument seems to work for -K in MRI plus this should not // siphon off additional args 'jruby -K ~/scripts/foo'. Also better error // processing. String eArg = grabValue("provide a value for -K"); if ("u".equals(eArg) || "U".equals(eArg) || "UTF8".equals(eArg)) { encoding = "UTF-8"; } break; case '-' : if (argument.equals("--version")) { setShowVersion(true); break FOR; } else if(argument.equals("--debug")) { debug = true; verbose = true; break; } else { if (argument.equals("--")) { // ruby interpreter compatibilty // Usage: ruby [switches] [--] [programfile] [arguments]) break FOR; } } default : throw new MainExitException(1, "unknown option " + argument.charAt(characterIndex)); } } } private String grabValue(String errorMessage) { characterIndex++; if (characterIndex < arguments[argumentIndex].length()) { return arguments[argumentIndex].substring(characterIndex); } argumentIndex++; if (argumentIndex < arguments.length) { return arguments[argumentIndex]; } MainExitException mee = new MainExitException(1, "invalid argument " + argumentIndex + "\n" + errorMessage); mee.setUsageError(true); throw mee; } public boolean hasInlineScript() { return inlineScript.length() > 0; } public String inlineScript() { return inlineScript.toString(); } public List requiredLibraries() { return requiredLibraries; } public List loadPaths() { return loadPaths; } public boolean shouldRunInterpreter() { return isShouldRunInterpreter(); } private boolean isSourceFromStdin() { return getScriptFileName() == null; } public Reader getScriptSource() { try { if (hasInlineScript()) { return new StringReader(inlineScript()); } else if (isSourceFromStdin()) { return new InputStreamReader(System.in, encoding); } else { File file = new File(getScriptFileName()); return new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); } } catch (IOException e) { throw new MainExitException(1, "Error opening script file: " + e.getMessage()); } } public String displayedFileName() { if (hasInlineScript()) { return "-e"; } else if (isSourceFromStdin()) { return "-"; } else { return getScriptFileName(); } } private void setScriptFileName(String scriptFileName) { this.scriptFileName = scriptFileName; } public String getScriptFileName() { return scriptFileName; } public boolean isBenchmarking() { return benchmarking; } public boolean isAssumeLoop() { return assumeLoop; } public boolean isAssumePrinting() { return assumePrinting; } public boolean isProcessLineEnds() { return processLineEnds; } public boolean isSplit() { return split; } public boolean isVerbose() { return verbose; } public boolean isDebug() { return debug; } public boolean isShowVersion() { return showVersion; } protected void setShowVersion(boolean showVersion) { this.showVersion = showVersion; this.shouldRunInterpreter = false; } public String[] getScriptArguments() { return scriptArguments; } public boolean isShouldRunInterpreter() { return shouldRunInterpreter; } public boolean isObjectSpaceEnabled() { return objectSpaceEnabled; } public boolean isCompilerEnabled() { return compilerEnabled; } public String getEncoding() { return encoding; } }
true
true
private void processArgument() { String argument = arguments[argumentIndex]; FOR : for (characterIndex = 1; characterIndex < argument.length(); characterIndex++) { switch (argument.charAt(characterIndex)) { case 'h' : main.printUsage(); shouldRunInterpreter = false; break; case 'I' : String s = grabValue(" -I must be followed by a directory name to add to lib path"); String[] ls = s.split(":"); for(int i=0;i<ls.length;i++) { loadPaths.add(ls[i]); } break FOR; case 'r' : requiredLibraries.add(grabValue("-r must be followed by a package to require")); break FOR; case 'e' : inlineScript.append(grabValue(" -e must be followed by an expression to evaluate")); inlineScript.append('\n'); break FOR; case 'b' : benchmarking = true; break; case 'p' : assumePrinting = true; assumeLoop = true; break; case 'O' : objectSpaceEnabled = false; break; case 'C' : compilerEnabled = true; break; case 'n' : assumeLoop = true; break; case 'a' : split = true; break; case 'd' : debug = true; verbose = true; break; case 'l' : processLineEnds = true; break; case 'v' : verbose = true; setShowVersion(true); break; case 'w' : verbose = true; break; case 'K': // FIXME: No argument seems to work for -K in MRI plus this should not // siphon off additional args 'jruby -K ~/scripts/foo'. Also better error // processing. String eArg = grabValue("provide a value for -K"); if ("u".equals(eArg) || "U".equals(eArg) || "UTF8".equals(eArg)) { encoding = "UTF-8"; } break; case '-' : if (argument.equals("--version")) { setShowVersion(true); break FOR; } else if(argument.equals("--debug")) { debug = true; verbose = true; break; } else { if (argument.equals("--")) { // ruby interpreter compatibilty // Usage: ruby [switches] [--] [programfile] [arguments]) break FOR; } } default : throw new MainExitException(1, "unknown option " + argument.charAt(characterIndex)); } } }
private void processArgument() { String argument = arguments[argumentIndex]; FOR : for (characterIndex = 1; characterIndex < argument.length(); characterIndex++) { switch (argument.charAt(characterIndex)) { case 'h' : main.printUsage(); shouldRunInterpreter = false; break; case 'I' : String s = grabValue(" -I must be followed by a directory name to add to lib path"); String[] ls = s.split(java.io.File.pathSeparator); for(int i=0;i<ls.length;i++) { loadPaths.add(ls[i]); } break FOR; case 'r' : requiredLibraries.add(grabValue("-r must be followed by a package to require")); break FOR; case 'e' : inlineScript.append(grabValue(" -e must be followed by an expression to evaluate")); inlineScript.append('\n'); break FOR; case 'b' : benchmarking = true; break; case 'p' : assumePrinting = true; assumeLoop = true; break; case 'O' : objectSpaceEnabled = false; break; case 'C' : compilerEnabled = true; break; case 'n' : assumeLoop = true; break; case 'a' : split = true; break; case 'd' : debug = true; verbose = true; break; case 'l' : processLineEnds = true; break; case 'v' : verbose = true; setShowVersion(true); break; case 'w' : verbose = true; break; case 'K': // FIXME: No argument seems to work for -K in MRI plus this should not // siphon off additional args 'jruby -K ~/scripts/foo'. Also better error // processing. String eArg = grabValue("provide a value for -K"); if ("u".equals(eArg) || "U".equals(eArg) || "UTF8".equals(eArg)) { encoding = "UTF-8"; } break; case '-' : if (argument.equals("--version")) { setShowVersion(true); break FOR; } else if(argument.equals("--debug")) { debug = true; verbose = true; break; } else { if (argument.equals("--")) { // ruby interpreter compatibilty // Usage: ruby [switches] [--] [programfile] [arguments]) break FOR; } } default : throw new MainExitException(1, "unknown option " + argument.charAt(characterIndex)); } } }
diff --git a/src/de/zigapeda/flowspring/data/YoutubeSearch.java b/src/de/zigapeda/flowspring/data/YoutubeSearch.java index 25887d5..8b2db38 100644 --- a/src/de/zigapeda/flowspring/data/YoutubeSearch.java +++ b/src/de/zigapeda/flowspring/data/YoutubeSearch.java @@ -1,112 +1,118 @@ package de.zigapeda.flowspring.data; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.LinkedList; import java.util.List; import de.zigapeda.flowspring.interfaces.TreeRow; public class YoutubeSearch implements TreeRow { private String search = null; public YoutubeSearch(String searchstring) { this.search = searchstring; } public int getId() { return 0; } public Integer getInt() { return null; } public String getName() { return "Youtube"; } public String getArtist() { return null; } public String getAlbum() { return null; } public String getGenre() { return null; } public String getTrack() { return null; } public String getYear() { return null; } public Integer getDuration() { return null; } public String getComment() { return null; } public String getRating() { return null; } public String getPlaycount() { return null; } public Integer getType() { return TreeRow.YoutubeSearch; } public List<DataNode> getYoutubeTracks(DataNode parent) { List<DataNode> list = new LinkedList<>(); search = search.replace(' ', '+'); String searchUrl = "http://www.youtube.com/results?search_query=" + search; try { URL u = new URL(searchUrl); InputStream is = u.openConnection().getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = ""; boolean sr = false; while ((line = br.readLine()) != null) { if(line.contains("<ol id=\"search-results\"")) { sr = true; } if(line.contains("</ol>")) { sr = false; } if(line.contains("<li") && sr == true) { int pos = line.indexOf("data-context-item-title="); if(pos > -1) { pos = pos + 25; String name = line.substring(pos, line.indexOf("\"",pos)); - pos = line.indexOf("data-context-item-id=") + 22; - String url = "http://www.youtube.com/watch?v=" + line.substring(pos, line.indexOf("\"",pos)); - pos = line.indexOf("data-context-item-time=") + 24; - String time = line.substring(pos, line.indexOf("\"",pos)); - list.add(new DataNode(new YoutubeVideo(name, url, time),parent,null)); + pos = line.indexOf("data-context-item-id="); + if(pos > -1) { + pos = pos + 22; + String url = "http://www.youtube.com/watch?v=" + line.substring(pos, line.indexOf("\"",pos)); + pos = line.indexOf("data-context-item-time="); + if(pos > -1) { + pos = pos + 24; + String time = line.substring(pos, line.indexOf("\"",pos)); + list.add(new DataNode(new YoutubeVideo(name, url, time),parent,null)); + } + } } } } is.close(); } catch (MalformedURLException e1) { } catch (IOException e1) { } return list; } }
true
true
public List<DataNode> getYoutubeTracks(DataNode parent) { List<DataNode> list = new LinkedList<>(); search = search.replace(' ', '+'); String searchUrl = "http://www.youtube.com/results?search_query=" + search; try { URL u = new URL(searchUrl); InputStream is = u.openConnection().getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = ""; boolean sr = false; while ((line = br.readLine()) != null) { if(line.contains("<ol id=\"search-results\"")) { sr = true; } if(line.contains("</ol>")) { sr = false; } if(line.contains("<li") && sr == true) { int pos = line.indexOf("data-context-item-title="); if(pos > -1) { pos = pos + 25; String name = line.substring(pos, line.indexOf("\"",pos)); pos = line.indexOf("data-context-item-id=") + 22; String url = "http://www.youtube.com/watch?v=" + line.substring(pos, line.indexOf("\"",pos)); pos = line.indexOf("data-context-item-time=") + 24; String time = line.substring(pos, line.indexOf("\"",pos)); list.add(new DataNode(new YoutubeVideo(name, url, time),parent,null)); } } } is.close(); } catch (MalformedURLException e1) { } catch (IOException e1) { } return list; }
public List<DataNode> getYoutubeTracks(DataNode parent) { List<DataNode> list = new LinkedList<>(); search = search.replace(' ', '+'); String searchUrl = "http://www.youtube.com/results?search_query=" + search; try { URL u = new URL(searchUrl); InputStream is = u.openConnection().getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = ""; boolean sr = false; while ((line = br.readLine()) != null) { if(line.contains("<ol id=\"search-results\"")) { sr = true; } if(line.contains("</ol>")) { sr = false; } if(line.contains("<li") && sr == true) { int pos = line.indexOf("data-context-item-title="); if(pos > -1) { pos = pos + 25; String name = line.substring(pos, line.indexOf("\"",pos)); pos = line.indexOf("data-context-item-id="); if(pos > -1) { pos = pos + 22; String url = "http://www.youtube.com/watch?v=" + line.substring(pos, line.indexOf("\"",pos)); pos = line.indexOf("data-context-item-time="); if(pos > -1) { pos = pos + 24; String time = line.substring(pos, line.indexOf("\"",pos)); list.add(new DataNode(new YoutubeVideo(name, url, time),parent,null)); } } } } } is.close(); } catch (MalformedURLException e1) { } catch (IOException e1) { } return list; }
diff --git a/src/main/java/ly/bit/nsq/lookupd/AbstractLookupd.java b/src/main/java/ly/bit/nsq/lookupd/AbstractLookupd.java index 16c7a53..2e2f76c 100644 --- a/src/main/java/ly/bit/nsq/lookupd/AbstractLookupd.java +++ b/src/main/java/ly/bit/nsq/lookupd/AbstractLookupd.java @@ -1,61 +1,64 @@ package ly.bit.nsq.lookupd; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class AbstractLookupd { private static final Logger log = LoggerFactory.getLogger(AbstractLookupd.class); protected String addr; public String getAddr() { return addr; } /** * This should handle making a request to lookupd, and returning which producers match the channel we want * Netty presumably can wait on the future or something, who knows... */ public abstract List<String> query(String topic); public static List<String> parseResponseForProducers(Reader response){ ObjectMapper mapper = new ObjectMapper(); List<String> outputs = new ArrayList<String>(); try { JsonNode rootNode = mapper.readTree(response); JsonNode producers = rootNode.path("data").path("producers"); Iterator<JsonNode> prodItr = producers.getElements(); while(prodItr.hasNext()){ JsonNode producer = prodItr.next(); - String addr = producer.path("address").getTextValue(); + String addr = producer.path("broadcast_address").getTextValue(); + if ( addr == null ) { // We're keeping previous field compatibility, just in case + addr = producer.path("address").getTextValue(); + } int tcpPort = producer.path("tcp_port").getIntValue(); outputs.add(addr + ":" + tcpPort); } } catch (JsonParseException e) { log.error("Error parsing json from lookupd:", e); } catch (JsonMappingException e) { log.error("Error mapping json from lookupd:", e); } catch (IOException e) { log.error("Error reading response from lookupd:", e); } return outputs; } public static void main(String... args){ String response = "{\"status_code\":200,\"status_txt\":\"OK\",\"data\":{\"channels\":[\"social_graph_input\"],\"producers\":[{\"address\":\"dev.bitly.org\",\"tcp_port\":4150,\"http_port\":4151,\"version\":\"0.2.16-alpha\"}]}}"; // for (String addr : parseResponseForProducers(response)){ // System.out.println(addr); // } } }
true
true
public static List<String> parseResponseForProducers(Reader response){ ObjectMapper mapper = new ObjectMapper(); List<String> outputs = new ArrayList<String>(); try { JsonNode rootNode = mapper.readTree(response); JsonNode producers = rootNode.path("data").path("producers"); Iterator<JsonNode> prodItr = producers.getElements(); while(prodItr.hasNext()){ JsonNode producer = prodItr.next(); String addr = producer.path("address").getTextValue(); int tcpPort = producer.path("tcp_port").getIntValue(); outputs.add(addr + ":" + tcpPort); } } catch (JsonParseException e) { log.error("Error parsing json from lookupd:", e); } catch (JsonMappingException e) { log.error("Error mapping json from lookupd:", e); } catch (IOException e) { log.error("Error reading response from lookupd:", e); } return outputs; }
public static List<String> parseResponseForProducers(Reader response){ ObjectMapper mapper = new ObjectMapper(); List<String> outputs = new ArrayList<String>(); try { JsonNode rootNode = mapper.readTree(response); JsonNode producers = rootNode.path("data").path("producers"); Iterator<JsonNode> prodItr = producers.getElements(); while(prodItr.hasNext()){ JsonNode producer = prodItr.next(); String addr = producer.path("broadcast_address").getTextValue(); if ( addr == null ) { // We're keeping previous field compatibility, just in case addr = producer.path("address").getTextValue(); } int tcpPort = producer.path("tcp_port").getIntValue(); outputs.add(addr + ":" + tcpPort); } } catch (JsonParseException e) { log.error("Error parsing json from lookupd:", e); } catch (JsonMappingException e) { log.error("Error mapping json from lookupd:", e); } catch (IOException e) { log.error("Error reading response from lookupd:", e); } return outputs; }
diff --git a/psl-core/src/main/java/edu/umd/cs/psl/model/formula/traversal/FormulaEventAnalysis.java b/psl-core/src/main/java/edu/umd/cs/psl/model/formula/traversal/FormulaEventAnalysis.java index e9b2f911..7c149028 100644 --- a/psl-core/src/main/java/edu/umd/cs/psl/model/formula/traversal/FormulaEventAnalysis.java +++ b/psl-core/src/main/java/edu/umd/cs/psl/model/formula/traversal/FormulaEventAnalysis.java @@ -1,159 +1,164 @@ /* * This file is part of the PSL software. * Copyright 2011 University of Maryland * * 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 edu.umd.cs.psl.model.formula.traversal; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import edu.umd.cs.psl.database.DatabaseAtomStoreQuery; import edu.umd.cs.psl.model.argument.GroundTerm; import edu.umd.cs.psl.model.argument.Term; import edu.umd.cs.psl.model.argument.Variable; import edu.umd.cs.psl.model.atom.Atom; import edu.umd.cs.psl.model.atom.AtomEventFramework; import edu.umd.cs.psl.model.atom.AtomEventSets; import edu.umd.cs.psl.model.atom.VariableAssignment; import edu.umd.cs.psl.model.formula.Conjunction; import edu.umd.cs.psl.model.formula.Formula; import edu.umd.cs.psl.model.formula.Negation; import edu.umd.cs.psl.model.kernel.Kernel; import edu.umd.cs.psl.model.predicate.Predicate; import edu.umd.cs.psl.model.predicate.StandardPredicate; public class FormulaEventAnalysis { private static final AtomEventSets defaultFactEvent = AtomEventSets.NonDefaultFactEvent; private final Multimap<Predicate,Atom> dependence; private final Formula formula; private final Set<Formula> queries; public FormulaEventAnalysis(Formula f) { formula = f; dependence = ArrayListMultimap.create(); //FormulaTraverser.traverse(formula, new FormulaAnalyser()); queries = new HashSet<Formula>(); Conjunction c = ((Conjunction) formula).flatten(); Vector<Formula> necessary = new Vector<Formula>(c.getNoFormulas()); Vector<Formula> oneOf = new Vector<Formula>(c.getNoFormulas()); Atom a; for (int i = 0; i < c.getNoFormulas(); i++) { if (c.get(i) instanceof Atom) { a = (Atom) c.get(i); if (a.getPredicate().getNumberOfValues() == 1) { if (a.getPredicate().getDefaultValues()[0] == 0.0) { necessary.add(a); dependence.put(a.getPredicate(), a); } else { oneOf.add(a); } } else { oneOf.add(a); } } else if (c.get(i) instanceof Negation) { a = (Atom) ((Negation) c.get(i)).getFormula(); if (a.getPredicate().getNumberOfValues() == 1) { if (a.getPredicate().getDefaultValues()[0] != 0.0) { oneOf.add(a); } } } } - //if (oneOf.isEmpty()) { - queries.add(new Conjunction((Formula[]) necessary.toArray(new Formula[necessary.size()]))); - //} - //else { - // for (Formula formula : oneOf) { - // queries.add(new Conjunction(new Conjunction((Formula[]) necessary.toArray(new Formula[necessary.size()])), formula)); - // } - //} + if (necessary.size() == 1) { + queries.add(necessary.get(0)); + } + else { + //if (oneOf.isEmpty()) { + queries.add(new Conjunction((Formula[]) necessary.toArray(new Formula[necessary.size()]))); + //} + //else { + // for (Formula formula : oneOf) { + // queries.add(new Conjunction(new Conjunction((Formula[]) necessary.toArray(new Formula[necessary.size()])), formula)); + // } + //} + } } public Formula getFormula() { return formula; } public Set<Formula> getQueryFormulas() { return queries; } public List<VariableAssignment> traceAtomEvent(Atom atom) { Collection<Atom> atoms = dependence.get(atom.getPredicate()); List<VariableAssignment> vars = new ArrayList<VariableAssignment>(atoms.size()); for (Atom entry : atoms) { //Check whether arguments match VariableAssignment var = new VariableAssignment(); Term[] argsGround = atom.getArguments(); Term[] argsTemplate = entry.getArguments(); assert argsGround.length==argsTemplate.length; for (int i=0;i<argsGround.length;i++) { if (argsTemplate[i] instanceof Variable) { //Add mapping assert argsGround[i] instanceof GroundTerm; var.assign((Variable)argsTemplate[i], (GroundTerm)argsGround[i]); } else { //They must be the same if (!argsTemplate[i].equals(argsGround[i])) { var = null; break; } } } if (var!=null) vars.add(var); } return vars; } public void registerFormulaForEvents(AtomEventFramework af, Kernel me, AtomEventSets inferenceAtomEvent, DatabaseAtomStoreQuery db) { for (Predicate p : dependence.keySet()) { if (db.isClosed(p)) af.registerAtomEventObserver(p, defaultFactEvent, me); else af.registerAtomEventObserver(p, inferenceAtomEvent, me); } } public void unregisterFormulaForEvents(AtomEventFramework af, Kernel me, AtomEventSets inferenceAtomEvent, DatabaseAtomStoreQuery db) { for (Predicate p : dependence.keySet()) { if (db.isClosed(p)) af.unregisterAtomEventObserver(p, defaultFactEvent, me); else af.unregisterAtomEventObserver(p, inferenceAtomEvent, me); } } private class FormulaAnalyser extends FormulaTraverser { @Override public void visitAtom(Atom atom) { if (atom.getPredicate() instanceof StandardPredicate) { dependence.put(atom.getPredicate(), atom); } } } }
true
true
public FormulaEventAnalysis(Formula f) { formula = f; dependence = ArrayListMultimap.create(); //FormulaTraverser.traverse(formula, new FormulaAnalyser()); queries = new HashSet<Formula>(); Conjunction c = ((Conjunction) formula).flatten(); Vector<Formula> necessary = new Vector<Formula>(c.getNoFormulas()); Vector<Formula> oneOf = new Vector<Formula>(c.getNoFormulas()); Atom a; for (int i = 0; i < c.getNoFormulas(); i++) { if (c.get(i) instanceof Atom) { a = (Atom) c.get(i); if (a.getPredicate().getNumberOfValues() == 1) { if (a.getPredicate().getDefaultValues()[0] == 0.0) { necessary.add(a); dependence.put(a.getPredicate(), a); } else { oneOf.add(a); } } else { oneOf.add(a); } } else if (c.get(i) instanceof Negation) { a = (Atom) ((Negation) c.get(i)).getFormula(); if (a.getPredicate().getNumberOfValues() == 1) { if (a.getPredicate().getDefaultValues()[0] != 0.0) { oneOf.add(a); } } } } //if (oneOf.isEmpty()) { queries.add(new Conjunction((Formula[]) necessary.toArray(new Formula[necessary.size()]))); //} //else { // for (Formula formula : oneOf) { // queries.add(new Conjunction(new Conjunction((Formula[]) necessary.toArray(new Formula[necessary.size()])), formula)); // } //} }
public FormulaEventAnalysis(Formula f) { formula = f; dependence = ArrayListMultimap.create(); //FormulaTraverser.traverse(formula, new FormulaAnalyser()); queries = new HashSet<Formula>(); Conjunction c = ((Conjunction) formula).flatten(); Vector<Formula> necessary = new Vector<Formula>(c.getNoFormulas()); Vector<Formula> oneOf = new Vector<Formula>(c.getNoFormulas()); Atom a; for (int i = 0; i < c.getNoFormulas(); i++) { if (c.get(i) instanceof Atom) { a = (Atom) c.get(i); if (a.getPredicate().getNumberOfValues() == 1) { if (a.getPredicate().getDefaultValues()[0] == 0.0) { necessary.add(a); dependence.put(a.getPredicate(), a); } else { oneOf.add(a); } } else { oneOf.add(a); } } else if (c.get(i) instanceof Negation) { a = (Atom) ((Negation) c.get(i)).getFormula(); if (a.getPredicate().getNumberOfValues() == 1) { if (a.getPredicate().getDefaultValues()[0] != 0.0) { oneOf.add(a); } } } } if (necessary.size() == 1) { queries.add(necessary.get(0)); } else { //if (oneOf.isEmpty()) { queries.add(new Conjunction((Formula[]) necessary.toArray(new Formula[necessary.size()]))); //} //else { // for (Formula formula : oneOf) { // queries.add(new Conjunction(new Conjunction((Formula[]) necessary.toArray(new Formula[necessary.size()])), formula)); // } //} } }
diff --git a/jdbc/src/java/org/apache/hadoop/hive/jdbc/HiveConnection.java b/jdbc/src/java/org/apache/hadoop/hive/jdbc/HiveConnection.java index 1102ee57..f5a56d86 100644 --- a/jdbc/src/java/org/apache/hadoop/hive/jdbc/HiveConnection.java +++ b/jdbc/src/java/org/apache/hadoop/hive/jdbc/HiveConnection.java @@ -1,669 +1,669 @@ /** * 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.hive.jdbc; import org.apache.hadoop.hive.metastore.api.MetaException; import org.apache.hadoop.hive.service.HiveClient; import org.apache.hadoop.hive.service.HiveInterface; import org.apache.hadoop.hive.service.HiveServer; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.Map; import java.util.Properties; /** * HiveConnection. * */ public class HiveConnection implements java.sql.Connection { private TTransport transport; private HiveInterface client; private boolean isClosed = true; private SQLWarning warningChain = null; private static final String URI_PREFIX = "jdbc:hive://"; /** * TODO: - parse uri (use java.net.URI?). */ public HiveConnection(String uri, Properties info) throws SQLException { if (!uri.startsWith(URI_PREFIX)) { throw new SQLException("Invalid URL: " + uri, "08S01"); } // remove prefix uri = uri.substring(URI_PREFIX.length()); // If uri is not specified, use local mode. if (uri.isEmpty()) { try { client = new HiveServer.HiveServerHandler(); } catch (MetaException e) { throw new SQLException("Error accessing Hive metastore: " + e.getMessage(), "08S01"); } } else { // parse uri // form: hostname:port/databasename String[] parts = uri.split("/"); String[] hostport = parts[0].split(":"); int port = 10000; String host = hostport[0]; try { port = Integer.parseInt(hostport[1]); } catch (Exception e) { } transport = new TSocket(host, port); TProtocol protocol = new TBinaryProtocol(transport); client = new HiveClient(protocol); try { transport.open(); } catch (TTransportException e) { - throw new SQLException("Could not establish connecton to " + throw new SQLException("Could not establish connection to " + uri + ": " + e.getMessage(), "08S01"); } } isClosed = false; configureConnection(); } private void configureConnection() throws SQLException { Statement stmt = createStatement(); stmt.execute( "set hive.fetch.output.serde = org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"); stmt.close(); } /* * (non-Javadoc) * * @see java.sql.Connection#clearWarnings() */ public void clearWarnings() throws SQLException { warningChain = null; } /* * (non-Javadoc) * * @see java.sql.Connection#close() */ public void close() throws SQLException { if (!isClosed) { try { client.clean(); } catch (TException e) { throw new SQLException("Error while cleaning up the server resources", e); } finally { isClosed = true; if (transport != null) { transport.close(); } } } } /* * (non-Javadoc) * * @see java.sql.Connection#commit() */ public void commit() throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#createArrayOf(java.lang.String, * java.lang.Object[]) */ public Array createArrayOf(String arg0, Object[] arg1) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#createBlob() */ public Blob createBlob() throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#createClob() */ public Clob createClob() throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#createNClob() */ public NClob createNClob() throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#createSQLXML() */ public SQLXML createSQLXML() throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /** * Creates a Statement object for sending SQL statements to the database. * * @throws SQLException * if a database access error occurs. * @see java.sql.Connection#createStatement() */ public Statement createStatement() throws SQLException { if (isClosed) { throw new SQLException("Can't create Statement, connection is closed"); } return new HiveStatement(client); } /* * (non-Javadoc) * * @see java.sql.Connection#createStatement(int, int) */ public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#createStatement(int, int, int) */ public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#createStruct(java.lang.String, java.lang.Object[]) */ public Struct createStruct(String typeName, Object[] attributes) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#getAutoCommit() */ public boolean getAutoCommit() throws SQLException { return true; } /* * (non-Javadoc) * * @see java.sql.Connection#getCatalog() */ public String getCatalog() throws SQLException { return ""; } /* * (non-Javadoc) * * @see java.sql.Connection#getClientInfo() */ public Properties getClientInfo() throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#getClientInfo(java.lang.String) */ public String getClientInfo(String name) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#getHoldability() */ public int getHoldability() throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#getMetaData() */ public DatabaseMetaData getMetaData() throws SQLException { return new HiveDatabaseMetaData(client); } /* * (non-Javadoc) * * @see java.sql.Connection#getTransactionIsolation() */ public int getTransactionIsolation() throws SQLException { return Connection.TRANSACTION_NONE; } /* * (non-Javadoc) * * @see java.sql.Connection#getTypeMap() */ public Map<String, Class<?>> getTypeMap() throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#getWarnings() */ public SQLWarning getWarnings() throws SQLException { return warningChain; } /* * (non-Javadoc) * * @see java.sql.Connection#isClosed() */ public boolean isClosed() throws SQLException { return isClosed; } /* * (non-Javadoc) * * @see java.sql.Connection#isReadOnly() */ public boolean isReadOnly() throws SQLException { return false; } /* * (non-Javadoc) * * @see java.sql.Connection#isValid(int) */ public boolean isValid(int timeout) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#nativeSQL(java.lang.String) */ public String nativeSQL(String sql) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#prepareCall(java.lang.String) */ public CallableStatement prepareCall(String sql) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#prepareCall(java.lang.String, int, int) */ public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#prepareCall(java.lang.String, int, int, int) */ public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#prepareStatement(java.lang.String) */ public PreparedStatement prepareStatement(String sql) throws SQLException { return new HivePreparedStatement(client, sql); } /* * (non-Javadoc) * * @see java.sql.Connection#prepareStatement(java.lang.String, int) */ public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return new HivePreparedStatement(client, sql); } /* * (non-Javadoc) * * @see java.sql.Connection#prepareStatement(java.lang.String, int[]) */ public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#prepareStatement(java.lang.String, * java.lang.String[]) */ public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#prepareStatement(java.lang.String, int, int) */ public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return new HivePreparedStatement(client, sql); } /* * (non-Javadoc) * * @see java.sql.Connection#prepareStatement(java.lang.String, int, int, int) */ public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#releaseSavepoint(java.sql.Savepoint) */ public void releaseSavepoint(Savepoint savepoint) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#rollback() */ public void rollback() throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#rollback(java.sql.Savepoint) */ public void rollback(Savepoint savepoint) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#setAutoCommit(boolean) */ public void setAutoCommit(boolean autoCommit) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#setCatalog(java.lang.String) */ public void setCatalog(String catalog) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#setClientInfo(java.util.Properties) */ public void setClientInfo(Properties properties) throws SQLClientInfoException { // TODO Auto-generated method stub throw new SQLClientInfoException("Method not supported", null); } /* * (non-Javadoc) * * @see java.sql.Connection#setClientInfo(java.lang.String, java.lang.String) */ public void setClientInfo(String name, String value) throws SQLClientInfoException { // TODO Auto-generated method stub throw new SQLClientInfoException("Method not supported", null); } /* * (non-Javadoc) * * @see java.sql.Connection#setHoldability(int) */ public void setHoldability(int holdability) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#setReadOnly(boolean) */ public void setReadOnly(boolean readOnly) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#setSavepoint() */ public Savepoint setSavepoint() throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#setSavepoint(java.lang.String) */ public Savepoint setSavepoint(String name) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#setTransactionIsolation(int) */ public void setTransactionIsolation(int level) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Connection#setTypeMap(java.util.Map) */ public void setTypeMap(Map<String, Class<?>> map) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Wrapper#isWrapperFor(java.lang.Class) */ public boolean isWrapperFor(Class<?> iface) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } /* * (non-Javadoc) * * @see java.sql.Wrapper#unwrap(java.lang.Class) */ public <T> T unwrap(Class<T> iface) throws SQLException { // TODO Auto-generated method stub throw new SQLException("Method not supported"); } }
true
true
public HiveConnection(String uri, Properties info) throws SQLException { if (!uri.startsWith(URI_PREFIX)) { throw new SQLException("Invalid URL: " + uri, "08S01"); } // remove prefix uri = uri.substring(URI_PREFIX.length()); // If uri is not specified, use local mode. if (uri.isEmpty()) { try { client = new HiveServer.HiveServerHandler(); } catch (MetaException e) { throw new SQLException("Error accessing Hive metastore: " + e.getMessage(), "08S01"); } } else { // parse uri // form: hostname:port/databasename String[] parts = uri.split("/"); String[] hostport = parts[0].split(":"); int port = 10000; String host = hostport[0]; try { port = Integer.parseInt(hostport[1]); } catch (Exception e) { } transport = new TSocket(host, port); TProtocol protocol = new TBinaryProtocol(transport); client = new HiveClient(protocol); try { transport.open(); } catch (TTransportException e) { throw new SQLException("Could not establish connecton to " + uri + ": " + e.getMessage(), "08S01"); } } isClosed = false; configureConnection(); }
public HiveConnection(String uri, Properties info) throws SQLException { if (!uri.startsWith(URI_PREFIX)) { throw new SQLException("Invalid URL: " + uri, "08S01"); } // remove prefix uri = uri.substring(URI_PREFIX.length()); // If uri is not specified, use local mode. if (uri.isEmpty()) { try { client = new HiveServer.HiveServerHandler(); } catch (MetaException e) { throw new SQLException("Error accessing Hive metastore: " + e.getMessage(), "08S01"); } } else { // parse uri // form: hostname:port/databasename String[] parts = uri.split("/"); String[] hostport = parts[0].split(":"); int port = 10000; String host = hostport[0]; try { port = Integer.parseInt(hostport[1]); } catch (Exception e) { } transport = new TSocket(host, port); TProtocol protocol = new TBinaryProtocol(transport); client = new HiveClient(protocol); try { transport.open(); } catch (TTransportException e) { throw new SQLException("Could not establish connection to " + uri + ": " + e.getMessage(), "08S01"); } } isClosed = false; configureConnection(); }
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/Subscription.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/Subscription.java index 396838e74..521c89b36 100644 --- a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/Subscription.java +++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/Subscription.java @@ -1,584 +1,595 @@ /* * Copyright 2010-2011 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.billing.entitlement.api.user; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.UUID; import com.ning.billing.ErrorCode; import com.ning.billing.account.api.IAccount; import org.joda.time.DateTime; import com.ning.billing.catalog.api.ActionPolicy; import com.ning.billing.catalog.api.BillingPeriod; import com.ning.billing.catalog.api.CatalogApiException; import com.ning.billing.catalog.api.ICatalog; import com.ning.billing.catalog.api.IPlan; import com.ning.billing.catalog.api.IPlanPhase; import com.ning.billing.catalog.api.IPriceList; import com.ning.billing.catalog.api.IProduct; import com.ning.billing.catalog.api.PlanChangeResult; import com.ning.billing.catalog.api.PlanPhaseSpecifier; import com.ning.billing.catalog.api.PlanSpecifier; import com.ning.billing.catalog.api.ProductCategory; import com.ning.billing.entitlement.alignment.IPlanAligner; import com.ning.billing.entitlement.alignment.IPlanAligner.TimedPhase; import com.ning.billing.entitlement.engine.core.Engine; import com.ning.billing.entitlement.engine.dao.IEntitlementDao; import com.ning.billing.entitlement.events.IEvent; import com.ning.billing.entitlement.events.IEvent.EventType; import com.ning.billing.entitlement.events.phase.IPhaseEvent; import com.ning.billing.entitlement.events.phase.PhaseEvent; import com.ning.billing.entitlement.events.user.ApiEventCancel; import com.ning.billing.entitlement.events.user.ApiEventChange; import com.ning.billing.entitlement.events.user.ApiEventType; import com.ning.billing.entitlement.events.user.ApiEventUncancel; import com.ning.billing.entitlement.events.user.IApiEvent; import com.ning.billing.entitlement.exceptions.EntitlementError; import com.ning.billing.entitlement.glue.InjectorMagic; import com.ning.billing.util.clock.IClock; public class Subscription extends PrivateFields implements ISubscription { private final UUID id; private final UUID bundleId; private final DateTime startDate; private final DateTime bundleStartDate; private final long activeVersion; private final ProductCategory category; private final IClock clock; private final IEntitlementDao dao; private final ICatalog catalog; private final IPlanAligner planAligner; // STEPH interaction with billing /payment system private final DateTime chargedThroughDate; private final DateTime paidThroughDate; // STEPH non final because of change/ cancel API at the object level private List<SubscriptionTransition> transitions; public static class SubscriptionBuilder { private UUID id; private UUID bundleId; private DateTime startDate; private DateTime bundleStartDate; private Long activeVersion; private ProductCategory category; private DateTime chargedThroughDate; private DateTime paidThroughDate; public SubscriptionBuilder setId(UUID id) { this.id = id; return this; } public SubscriptionBuilder setBundleId(UUID bundleId) { this.bundleId = bundleId; return this; } public SubscriptionBuilder setStartDate(DateTime startDate) { this.startDate = startDate; return this; } public SubscriptionBuilder setBundleStartDate(DateTime bundleStartDate) { this.bundleStartDate = bundleStartDate; return this; } public SubscriptionBuilder setActiveVersion(long activeVersion) { this.activeVersion = activeVersion; return this; } public SubscriptionBuilder setChargedThroughDate(DateTime chargedThroughDate) { this.chargedThroughDate = chargedThroughDate; return this; } public SubscriptionBuilder setPaidThroughDate(DateTime paidThroughDate) { this.paidThroughDate = paidThroughDate; return this; } public SubscriptionBuilder setCategory(ProductCategory category) { this.category = category; return this; } private void checkAllFieldsSet() { for (Field cur : SubscriptionBuilder.class.getDeclaredFields()) { try { Object value = cur.get(this); if (value == null) { throw new EntitlementError(String.format("Field %s has not been set for Subscription", cur.getName())); } } catch (IllegalAccessException e) { throw new EntitlementError(String.format("Failed to access value for field %s for Subscription", cur.getName()), e); } } } public Subscription build() { //checkAllFieldsSet(); return new Subscription(id, bundleId, category, bundleStartDate, startDate, chargedThroughDate, paidThroughDate, activeVersion); } } public Subscription(UUID bundleId, ProductCategory category, DateTime bundleStartDate, DateTime startDate) { this(UUID.randomUUID(), bundleId, category, bundleStartDate, startDate, null, null, SubscriptionEvents.INITIAL_VERSION); } public Subscription(UUID id, UUID bundleId, ProductCategory category, DateTime bundleStartDate, DateTime startDate, DateTime ctd, DateTime ptd, long activeVersion) { super(); this.clock = InjectorMagic.getClock(); this.dao = InjectorMagic.getEntitlementDao(); this.catalog = InjectorMagic.getCatlog(); this.planAligner = InjectorMagic.getPlanAligner(); this.id = id; this.bundleId = bundleId; this.startDate = startDate; this.bundleStartDate = bundleStartDate; this.category = category; this.activeVersion = activeVersion; this.chargedThroughDate = ctd; this.paidThroughDate = ptd; rebuildTransitions(); } @Override public UUID getId() { return id; } @Override public UUID getBundleId() { return bundleId; } @Override public DateTime getStartDate() { return startDate; } @Override public SubscriptionState getState() { return (transitions == null) ? null : getLatestTranstion().getNextState(); } @Override public IPlanPhase getCurrentPhase() { return (transitions == null) ? null : getLatestTranstion().getNextPhase(); } @Override public IPlan getCurrentPlan() { return (transitions == null) ? null : getLatestTranstion().getNextPlan(); } @Override public String getCurrentPriceList() { return (transitions == null) ? null : getLatestTranstion().getNextPriceList(); } @Override public void cancel(DateTime requestedDate, boolean eot) throws EntitlementUserApiException { SubscriptionState currentState = getState(); if (currentState != SubscriptionState.ACTIVE) { throw new EntitlementUserApiException(ErrorCode.ENT_CANCEL_BAD_STATE, id, currentState); } DateTime now = clock.getUTCNow(); if (requestedDate != null && requestedDate.isAfter(now)) { throw new EntitlementUserApiException(ErrorCode.ENT_INVALID_REQUESTED_DATE, requestedDate.toString()); } IPlan currentPlan = getCurrentPlan(); PlanPhaseSpecifier planPhase = new PlanPhaseSpecifier(currentPlan.getProduct().getName(), currentPlan.getProduct().getCategory(), getCurrentPlan().getBillingPeriod(), getCurrentPriceList(), getCurrentPhase().getPhaseType()); //TODO: Correctly handle exception ActionPolicy policy = null; try { policy = catalog.planCancelPolicy(planPhase); } catch (CatalogApiException e) { // TODO Auto-generated catch block e.printStackTrace(); } DateTime effectiveDate = getPlanChangeEffectiveDate(policy, now); IEvent cancelEvent = new ApiEventCancel(id, bundleStartDate, now, now, effectiveDate, activeVersion); dao.cancelSubscription(id, cancelEvent); rebuildTransitions(); } @Override public void uncancel() throws EntitlementUserApiException { if (!isSubscriptionFutureCancelled()) { throw new EntitlementUserApiException(ErrorCode.ENT_UNCANCEL_BAD_STATE, id.toString()); } DateTime now = clock.getUTCNow(); IEvent uncancelEvent = new ApiEventUncancel(id, bundleStartDate, now, now, now, activeVersion); List<IEvent> uncancelEvents = new ArrayList<IEvent>(); uncancelEvents.add(uncancelEvent); DateTime planStartDate = getCurrentPlanStart(); TimedPhase nextTimedPhase = planAligner.getNextTimedPhase(this, getCurrentPlan(), now, planStartDate); IPhaseEvent nextPhaseEvent = PhaseEvent.getNextPhaseEvent(nextTimedPhase, this, now); if (nextPhaseEvent != null) { uncancelEvents.add(nextPhaseEvent); } dao.uncancelSubscription(id, uncancelEvents); rebuildTransitions(); } @Override public void changePlan(String productName, BillingPeriod term, String priceList, DateTime requestedDate) throws EntitlementUserApiException { String currentPriceList = getCurrentPriceList(); SubscriptionState currentState = getState(); if (currentState != SubscriptionState.ACTIVE) { throw new EntitlementUserApiException(ErrorCode.ENT_CHANGE_NON_ACTIVE, id, currentState); } if (isSubscriptionFutureCancelled()) { throw new EntitlementUserApiException(ErrorCode.ENT_CHANGE_FUTURE_CANCELLED, id); } DateTime now = clock.getUTCNow(); PlanChangeResult planChangeResult = null; try { IProduct destProduct = catalog.findProduct(productName); // STEPH really catalog exception if (destProduct == null) { throw new EntitlementUserApiException(ErrorCode.ENT_CREATE_BAD_CATALOG, productName, term.toString(), ""); } IPlan currentPlan = getCurrentPlan(); PlanPhaseSpecifier fromPlanPhase = new PlanPhaseSpecifier(currentPlan.getProduct().getName(), currentPlan.getProduct().getCategory(), currentPlan.getBillingPeriod(), currentPriceList, getCurrentPhase().getPhaseType()); PlanSpecifier toPlanPhase = new PlanSpecifier(productName, destProduct.getCategory(), term, priceList); planChangeResult = catalog.planChange(fromPlanPhase, toPlanPhase); } catch (CatalogApiException e) { throw new EntitlementUserApiException(e); } ActionPolicy policy = planChangeResult.getPolicy(); IPriceList newPriceList = planChangeResult.getNewPriceList(); //TODO: Correctly handle exception IPlan newPlan = null; try { newPlan = catalog.findPlan(productName, term, newPriceList.getName()); } catch (CatalogApiException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (newPlan == null) { throw new EntitlementUserApiException(ErrorCode.ENT_CREATE_BAD_CATALOG, productName, term.toString(), newPriceList.getName()); } DateTime effectiveDate = getPlanChangeEffectiveDate(policy, now); TimedPhase currentTimedPhase = planAligner.getCurrentTimedPhaseOnChange(this, newPlan, newPriceList.getName(), effectiveDate); IEvent changeEvent = new ApiEventChange(id, bundleStartDate, now, newPlan.getName(), currentTimedPhase.getPhase().getName(), newPriceList.getName(), now, effectiveDate, activeVersion); TimedPhase nextTimedPhase = planAligner.getNextTimedPhaseOnChange(this, newPlan, newPriceList.getName(), effectiveDate); IPhaseEvent nextPhaseEvent = PhaseEvent.getNextPhaseEvent(nextTimedPhase, this, now); List<IEvent> changeEvents = new ArrayList<IEvent>(); // Only add the PHASE if it does not coincide with the CHANGE, if not this is 'just' a CHANGE. if (nextPhaseEvent != null && ! nextPhaseEvent.getEffectiveDate().equals(changeEvent.getEffectiveDate())) { changeEvents.add(nextPhaseEvent); } changeEvents.add(changeEvent); dao.changePlan(id, changeEvents); rebuildTransitions(); } @Override public void pause() throws EntitlementUserApiException { throw new EntitlementUserApiException(ErrorCode.NOT_IMPLEMENTED); } @Override public void resume() throws EntitlementUserApiException { throw new EntitlementUserApiException(ErrorCode.NOT_IMPLEMENTED); } public ISubscriptionTransition getLatestTranstion() { if (transitions == null) { return null; } ISubscriptionTransition latestSubscription = null; for (ISubscriptionTransition cur : transitions) { if (cur.getEffectiveTransitionTime().isAfter(clock.getUTCNow())) { break; } latestSubscription = cur; } return latestSubscription; } public long getActiveVersion() { return activeVersion; } public ProductCategory getCategory() { return category; } public DateTime getBundleStartDate() { return bundleStartDate; } public DateTime getChargedThroughDate() { return chargedThroughDate; } public DateTime getPaidThroughDate() { return paidThroughDate; } public DateTime getCurrentPlanStart() { if (transitions == null) { throw new EntitlementError(String.format("No transitions for subscription %s", getId())); } Iterator<SubscriptionTransition> it = ((LinkedList<SubscriptionTransition>) transitions).descendingIterator(); while (it.hasNext()) { SubscriptionTransition cur = it.next(); if (cur.getEffectiveTransitionTime().isAfter(clock.getUTCNow())) { // Skip future events continue; } if (cur.getEventType() == EventType.API_USER && cur.getApiEventType() == ApiEventType.CHANGE) { return cur.getEffectiveTransitionTime(); } } // CREATE event return transitions.get(0).getEffectiveTransitionTime(); } public List<ISubscriptionTransition> getActiveTransitions() { if (transitions == null) { return null; } List<ISubscriptionTransition> activeTransitions = new ArrayList<ISubscriptionTransition>(); for (ISubscriptionTransition cur : transitions) { if (cur.getEffectiveTransitionTime().isAfter(clock.getUTCNow())) { activeTransitions.add(cur); } } return activeTransitions; } private boolean isSubscriptionFutureCancelled() { if (transitions == null) { return false; } for (SubscriptionTransition cur : transitions) { if (cur.getEffectiveTransitionTime().isBefore(clock.getUTCNow()) || cur.getEventType() == EventType.PHASE || cur.getApiEventType() != ApiEventType.CANCEL) { continue; } return true; } return false; } private DateTime getPlanChangeEffectiveDate(ActionPolicy policy, DateTime now) { if (policy == ActionPolicy.IMMEDIATE) { return now; } if (policy != ActionPolicy.END_OF_TERM) { throw new EntitlementError(String.format("Unexpected policy type %s", policy.toString())); } // // If CTD is null or CTD in the past, we default to the start date of the current phase // DateTime effectiveDate = chargedThroughDate; if (chargedThroughDate == null || chargedThroughDate.isBefore(clock.getUTCNow())) { effectiveDate = getCurrentPhaseStart(); } return effectiveDate; } private DateTime getCurrentPhaseStart() { if (transitions == null) { throw new EntitlementError(String.format("No transitions for subscription %s", getId())); } Iterator<SubscriptionTransition> it = ((LinkedList<SubscriptionTransition>) transitions).descendingIterator(); while (it.hasNext()) { SubscriptionTransition cur = it.next(); if (cur.getEffectiveTransitionTime().isAfter(clock.getUTCNow())) { // Skip future events continue; } if (cur.getEventType() == EventType.PHASE) { return cur.getEffectiveTransitionTime(); } } // CREATE event return transitions.get(0).getEffectiveTransitionTime(); } private void rebuildTransitions() { List<IEvent> events = dao.getEventsForSubscription(id); if (events == null) { return; } SubscriptionState nextState = null; String nextPlanName = null; String nextPhaseName = null; String nextPriceList = null; SubscriptionState previousState = null; String previousPlanName = null; String previousPhaseName = null; String previousPriceList = null; this.transitions = new LinkedList<SubscriptionTransition>(); for (final IEvent cur : events) { if (!cur.isActive() || cur.getActiveVersion() < activeVersion) { continue; } ApiEventType apiEventType = null; switch (cur.getType()) { case PHASE: IPhaseEvent phaseEV = (IPhaseEvent) cur; nextPhaseName = phaseEV.getPhase(); break; case API_USER: IApiEvent userEV = (IApiEvent) cur; apiEventType = userEV.getEventType(); switch(apiEventType) { case CREATE: nextState = SubscriptionState.ACTIVE; nextPlanName = userEV.getEventPlan(); nextPhaseName = userEV.getEventPlanPhase(); nextPriceList = userEV.getPriceList(); break; case CHANGE: nextPlanName = userEV.getEventPlan(); nextPhaseName = userEV.getEventPlanPhase(); nextPriceList = userEV.getPriceList(); break; case PAUSE: nextState = SubscriptionState.PAUSED; break; case RESUME: nextState = SubscriptionState.ACTIVE; break; case CANCEL: nextState = SubscriptionState.CANCELLED; nextPlanName = null; nextPhaseName = null; break; case UNCANCEL: break; default: throw new EntitlementError(String.format("Unexpected UserEvent type = %s", userEV.getEventType().toString())); } break; default: throw new EntitlementError(String.format("Unexpected Event type = %s", cur.getType())); } - //TODO: Correctly handle exception + //TODO: Correctly handle exceptions IPlan previousPlan = null; IPlanPhase previousPhase = null; IPlan nextPlan = null; IPlanPhase nextPhase = null; try { previousPlan = catalog.findPlan(previousPlanName); + } catch (CatalogApiException e) { + // TODO: handle exception + } + try { previousPhase = catalog.findPhase(previousPhaseName); + } catch (CatalogApiException e) { + // TODO: handle exception + } + try { nextPlan = catalog.findPlan(nextPlanName); + } catch (CatalogApiException e) { + // TODO: handle exception + } + try { nextPhase = catalog.findPhase(nextPhaseName); } catch (CatalogApiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + // TODO: handle exception } SubscriptionTransition transition = new SubscriptionTransition(id, bundleId, cur.getType(), apiEventType, cur.getRequestedDate(), cur.getEffectiveDate(), previousState, previousPlan, previousPhase, previousPriceList, nextState, nextPlan, nextPhase, nextPriceList); transitions.add(transition); previousState = nextState; previousPlanName = nextPlanName; previousPhaseName = nextPhaseName; previousPriceList = nextPriceList; } } }
false
true
private void rebuildTransitions() { List<IEvent> events = dao.getEventsForSubscription(id); if (events == null) { return; } SubscriptionState nextState = null; String nextPlanName = null; String nextPhaseName = null; String nextPriceList = null; SubscriptionState previousState = null; String previousPlanName = null; String previousPhaseName = null; String previousPriceList = null; this.transitions = new LinkedList<SubscriptionTransition>(); for (final IEvent cur : events) { if (!cur.isActive() || cur.getActiveVersion() < activeVersion) { continue; } ApiEventType apiEventType = null; switch (cur.getType()) { case PHASE: IPhaseEvent phaseEV = (IPhaseEvent) cur; nextPhaseName = phaseEV.getPhase(); break; case API_USER: IApiEvent userEV = (IApiEvent) cur; apiEventType = userEV.getEventType(); switch(apiEventType) { case CREATE: nextState = SubscriptionState.ACTIVE; nextPlanName = userEV.getEventPlan(); nextPhaseName = userEV.getEventPlanPhase(); nextPriceList = userEV.getPriceList(); break; case CHANGE: nextPlanName = userEV.getEventPlan(); nextPhaseName = userEV.getEventPlanPhase(); nextPriceList = userEV.getPriceList(); break; case PAUSE: nextState = SubscriptionState.PAUSED; break; case RESUME: nextState = SubscriptionState.ACTIVE; break; case CANCEL: nextState = SubscriptionState.CANCELLED; nextPlanName = null; nextPhaseName = null; break; case UNCANCEL: break; default: throw new EntitlementError(String.format("Unexpected UserEvent type = %s", userEV.getEventType().toString())); } break; default: throw new EntitlementError(String.format("Unexpected Event type = %s", cur.getType())); } //TODO: Correctly handle exception IPlan previousPlan = null; IPlanPhase previousPhase = null; IPlan nextPlan = null; IPlanPhase nextPhase = null; try { previousPlan = catalog.findPlan(previousPlanName); previousPhase = catalog.findPhase(previousPhaseName); nextPlan = catalog.findPlan(nextPlanName); nextPhase = catalog.findPhase(nextPhaseName); } catch (CatalogApiException e) { // TODO Auto-generated catch block e.printStackTrace(); } SubscriptionTransition transition = new SubscriptionTransition(id, bundleId, cur.getType(), apiEventType, cur.getRequestedDate(), cur.getEffectiveDate(), previousState, previousPlan, previousPhase, previousPriceList, nextState, nextPlan, nextPhase, nextPriceList); transitions.add(transition); previousState = nextState; previousPlanName = nextPlanName; previousPhaseName = nextPhaseName; previousPriceList = nextPriceList; } }
private void rebuildTransitions() { List<IEvent> events = dao.getEventsForSubscription(id); if (events == null) { return; } SubscriptionState nextState = null; String nextPlanName = null; String nextPhaseName = null; String nextPriceList = null; SubscriptionState previousState = null; String previousPlanName = null; String previousPhaseName = null; String previousPriceList = null; this.transitions = new LinkedList<SubscriptionTransition>(); for (final IEvent cur : events) { if (!cur.isActive() || cur.getActiveVersion() < activeVersion) { continue; } ApiEventType apiEventType = null; switch (cur.getType()) { case PHASE: IPhaseEvent phaseEV = (IPhaseEvent) cur; nextPhaseName = phaseEV.getPhase(); break; case API_USER: IApiEvent userEV = (IApiEvent) cur; apiEventType = userEV.getEventType(); switch(apiEventType) { case CREATE: nextState = SubscriptionState.ACTIVE; nextPlanName = userEV.getEventPlan(); nextPhaseName = userEV.getEventPlanPhase(); nextPriceList = userEV.getPriceList(); break; case CHANGE: nextPlanName = userEV.getEventPlan(); nextPhaseName = userEV.getEventPlanPhase(); nextPriceList = userEV.getPriceList(); break; case PAUSE: nextState = SubscriptionState.PAUSED; break; case RESUME: nextState = SubscriptionState.ACTIVE; break; case CANCEL: nextState = SubscriptionState.CANCELLED; nextPlanName = null; nextPhaseName = null; break; case UNCANCEL: break; default: throw new EntitlementError(String.format("Unexpected UserEvent type = %s", userEV.getEventType().toString())); } break; default: throw new EntitlementError(String.format("Unexpected Event type = %s", cur.getType())); } //TODO: Correctly handle exceptions IPlan previousPlan = null; IPlanPhase previousPhase = null; IPlan nextPlan = null; IPlanPhase nextPhase = null; try { previousPlan = catalog.findPlan(previousPlanName); } catch (CatalogApiException e) { // TODO: handle exception } try { previousPhase = catalog.findPhase(previousPhaseName); } catch (CatalogApiException e) { // TODO: handle exception } try { nextPlan = catalog.findPlan(nextPlanName); } catch (CatalogApiException e) { // TODO: handle exception } try { nextPhase = catalog.findPhase(nextPhaseName); } catch (CatalogApiException e) { // TODO: handle exception } SubscriptionTransition transition = new SubscriptionTransition(id, bundleId, cur.getType(), apiEventType, cur.getRequestedDate(), cur.getEffectiveDate(), previousState, previousPlan, previousPhase, previousPriceList, nextState, nextPlan, nextPhase, nextPriceList); transitions.add(transition); previousState = nextState; previousPlanName = nextPlanName; previousPhaseName = nextPhaseName; previousPriceList = nextPriceList; } }
diff --git a/src/com/ikai/photosharing/server/UserImageServiceImpl.java b/src/com/ikai/photosharing/server/UserImageServiceImpl.java index 44776db..661e806 100644 --- a/src/com/ikai/photosharing/server/UserImageServiceImpl.java +++ b/src/com/ikai/photosharing/server/UserImageServiceImpl.java @@ -1,50 +1,50 @@ package com.ikai.photosharing.server; import java.util.List; import com.google.appengine.api.blobstore.BlobstoreService; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.ikai.photosharing.client.services.UserImageService; import com.ikai.photosharing.shared.UploadedImage; @SuppressWarnings("serial") public class UserImageServiceImpl extends RemoteServiceServlet implements UserImageService { @Override public String getBlobstoreUploadUrl() { BlobstoreService blobstoreService = BlobstoreServiceFactory .getBlobstoreService(); return blobstoreService.createUploadUrl("/upload"); } @Override public UploadedImage get(String key) { UploadedImageDao dao = new UploadedImageDao(); UploadedImage image = dao.get(key); return image; } @Override public List<UploadedImage> getRecentlyUploaded() { UploadedImageDao dao = new UploadedImageDao(); List<UploadedImage> images = dao.getRecent(); return images; } @Override public void deleteImage(String key) { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); UploadedImageDao dao = new UploadedImageDao(); UploadedImage image = dao.get(key); - if(image.getOwnerId() == user.getUserId()) { + if(image.getOwnerId().equals(user.getUserId())) { dao.delete(key); } } }
true
true
public void deleteImage(String key) { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); UploadedImageDao dao = new UploadedImageDao(); UploadedImage image = dao.get(key); if(image.getOwnerId() == user.getUserId()) { dao.delete(key); } }
public void deleteImage(String key) { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); UploadedImageDao dao = new UploadedImageDao(); UploadedImage image = dao.get(key); if(image.getOwnerId().equals(user.getUserId())) { dao.delete(key); } }
diff --git a/user/src/main/java/org/tessell/model/dsl/ListBoxIdentityAdaptor.java b/user/src/main/java/org/tessell/model/dsl/ListBoxIdentityAdaptor.java index 1de209f9..f875c457 100644 --- a/user/src/main/java/org/tessell/model/dsl/ListBoxIdentityAdaptor.java +++ b/user/src/main/java/org/tessell/model/dsl/ListBoxIdentityAdaptor.java @@ -1,15 +1,15 @@ package org.tessell.model.dsl; public class ListBoxIdentityAdaptor<P> implements ListBoxAdaptor<P, P> { @Override public String toDisplay(P option) { - return option.toString(); + return option == null ? null : option.toString(); } @Override public P toValue(P option) { return option; } }
true
true
public String toDisplay(P option) { return option.toString(); }
public String toDisplay(P option) { return option == null ? null : option.toString(); }
diff --git a/cat-core/src/main/java/com/dianping/cat/build/StorageComponentConfigurator.java b/cat-core/src/main/java/com/dianping/cat/build/StorageComponentConfigurator.java index d806d74c..558aa11d 100644 --- a/cat-core/src/main/java/com/dianping/cat/build/StorageComponentConfigurator.java +++ b/cat-core/src/main/java/com/dianping/cat/build/StorageComponentConfigurator.java @@ -1,32 +1,33 @@ package com.dianping.cat.build; import java.util.ArrayList; import java.util.List; import com.dianping.cat.message.spi.MessageCodec; import com.dianping.cat.message.spi.MessagePathBuilder; import com.dianping.cat.message.spi.MessageTree; import com.dianping.cat.storage.Bucket; import com.dianping.cat.storage.BucketManager; import com.dianping.cat.storage.internal.DefaultBucketManager; import com.dianping.cat.storage.internal.LocalMessageBucket; import com.dianping.cat.storage.internal.LocalStringBucket; import com.site.lookup.configuration.AbstractResourceConfigurator; import com.site.lookup.configuration.Component; class StorageComponentConfigurator extends AbstractResourceConfigurator { @Override public List<Component> defineComponents() { List<Component> all = new ArrayList<Component>(); all.add(C(Bucket.class, String.class.getName(), LocalStringBucket.class) // .is(PER_LOOKUP) // .req(MessagePathBuilder.class)); all.add(C(Bucket.class, MessageTree.class.getName(), LocalMessageBucket.class) // .is(PER_LOOKUP) // + .req(MessagePathBuilder.class) // .req(MessageCodec.class, "plain-text")); all.add(C(BucketManager.class, DefaultBucketManager.class)); return all; } }
true
true
public List<Component> defineComponents() { List<Component> all = new ArrayList<Component>(); all.add(C(Bucket.class, String.class.getName(), LocalStringBucket.class) // .is(PER_LOOKUP) // .req(MessagePathBuilder.class)); all.add(C(Bucket.class, MessageTree.class.getName(), LocalMessageBucket.class) // .is(PER_LOOKUP) // .req(MessageCodec.class, "plain-text")); all.add(C(BucketManager.class, DefaultBucketManager.class)); return all; }
public List<Component> defineComponents() { List<Component> all = new ArrayList<Component>(); all.add(C(Bucket.class, String.class.getName(), LocalStringBucket.class) // .is(PER_LOOKUP) // .req(MessagePathBuilder.class)); all.add(C(Bucket.class, MessageTree.class.getName(), LocalMessageBucket.class) // .is(PER_LOOKUP) // .req(MessagePathBuilder.class) // .req(MessageCodec.class, "plain-text")); all.add(C(BucketManager.class, DefaultBucketManager.class)); return all; }
diff --git a/src/main/java/jannovar/Jannovar.java b/src/main/java/jannovar/Jannovar.java index 21be3c46..91b880ab 100644 --- a/src/main/java/jannovar/Jannovar.java +++ b/src/main/java/jannovar/Jannovar.java @@ -1,563 +1,563 @@ package jannovar; /** Command line functions from apache */ import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.Parser; import java.io.FileInputStream; import java.io.IOException; import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import jannovar.annotation.Annotation; import jannovar.annotation.AnnotationList; import jannovar.exception.AnnotationException; import jannovar.exception.IntervalTreeException; import jannovar.exception.JannovarException; import jannovar.exception.KGParseException; import jannovar.exception.VCFParseException; import jannovar.exome.Variant; import jannovar.interval.Interval; import jannovar.interval.IntervalTree; import jannovar.io.SerializationManager; import jannovar.io.UCSCDownloader; import jannovar.io.UCSCKGParser; import jannovar.io.VCFLine; import jannovar.io.VCFReader; import jannovar.reference.Chromosome; import jannovar.reference.TranscriptModel; /** * This is the driver class for a program called Jannovar. It has two purposes * <OL> * <LI>Take the UCSC files knownGene.txt, kgXref.txt, knownGeneMrna.txt, and knownToLocusLink.txt, * and to create corresponding {@link jannovar.reference.TranscriptModel TranscriptModel} objects and to * serialize them. The resulting serialized file can be used both by this program itself (see next item) * or by the main Exomizer program to annotated VCF file. * <LI>Using the serialized file of {@link jannovar.reference.TranscriptModel TranscriptModel} objects (see above item) * annotate a VCF file using annovar-type program logic. Note that this functionality is also * used by the main Exomizer program and thus this program can be used as a stand-alone annotator ("Jannovar") * or as a way of testing the code for the Exomizer. * </OL> * <P> * To run the "Jannotator" exectuable: * <P> * {@code java -Xms1G -Xmx1G -jar Jannotator.jar -V xyz.vcf -D $SERIAL} * <P> * This will annotate a VCF file. The results of jannovar annotation are shown in the form * <PRE> * Annotation {original VCF line} * </PRE> * <P> * Just a reminder, to set up annovar to do this, use the following commands. * <PRE> * perl annotate_variation.pl --downdb knownGene --buildver hg19 humandb/ * </PRE> * then, to annotate a VCF file called BLA.vcf, we first need to convert it to Annovar input * format and run the main annovar program as follows. * <PRE> * $ perl convert2annovar.pl BLA.vcf -format vcf4 > BLA.av * $ perl annotate_variation.pl -buildver hg19 --geneanno BLA.av --dbtype knowngene humandb/ * </PRE> * This will create two files with all variants and a special file with exonic variants. * <p> * There are three ways of using this program. * <ol> * <li>To create a serialized version of the UCSC gene definition data. In this case, the command-line * flag <b>- S</b> is provide as is the path to the four UCSC files. Then, {@code anno.serialize()} is true * and a file <b>ucsc.ser</b> is created. * <li>To deserialize the serialized data (<b>ucsc.ser</b>). In this case, the flag <b>- D</b> must be used. * <li>To simply read in the UCSC data without creating a serialized file. * </ol> * Whichever of the three versions is chosen, the user may additionally pass the path to a VCF file using the <b>-v</b> flag. * If so, then this file will be annotated using the UCSC data, and a new version of the file will be written to a file called * test.vcf.jannovar (assuming the original file was named test.vcf). * The * @author Peter N Robinson * @version 0.25 (8 July, 2013) */ public class Jannovar { /** Location of a directory that must contain the files * knownGene.txt, kgXref.txt, knownGeneMrnfile knownGene.txt * (the files may or may not be compressed with gzip. The same variable is * also used to indicate the location of the download directory. The default value * is "ucsc".*/ private String ucscDirPath=null; /** * Flag to indicate that Jannovar should download known gene definitions files from the * UCSC server. */ private boolean downloadUCSC; /** List of all lines from knownGene.txt file from UCSC */ private ArrayList<TranscriptModel> knownGenesList=null; /** Map of Chromosomes */ private HashMap<Byte,Chromosome> chromosomeMap=null; /** List of variants from input file to be analysed. */ private ArrayList<Variant> variantList=null; /** Name of the UCSC serialized data file that will be created by Jannovar. */ private static final String UCSCserializationFileName="ucsc.ser"; /** Flag to indicate that Jannovar should serialize the UCSC data. This flag is set to * true automatically if the user enters --download-ucsc (then, thefour files are downloaded * and subsequently serialized). If the user enters the flag {@code -U path}, then Jannovar * interprets path as the location of a directory that already contains the UCSC files (either * compressed or uncompressed), and sets this flag to true to perform serialization and then * to exit. The name of the serialized file that gets created is "ucsc.ser" (this cannot * be changed from the command line, see {@link #UCSCserializationFileName}). */ private boolean performSerialization=false; /** Name of file with serialized UCSC data. This should be the complete path to the file, * and will be used for annotating VCF files.*/ private String serializedFile=null; /** Path to a VCF file waiting to be annotated. */ private String VCFfilePath=null; /** An FTP proxy for downloading the UCSC files from behind a firewall. */ private String proxy=null; /** An FTP proxy port for downloading the UCSC files from behind a firewall. */ private String proxyPort=null; /** * Flag indicating whether to output annotations in Jannovar format (default: false). */ private boolean jannovarFormat; public static void main(String argv[]) { Jannovar anno = new Jannovar(argv); /* Option 1. Download the UCSC files from the server, create the ucsc.ser file, and return. */ if (anno.downloadUCSC()) { try{ anno.downloadUCSCfiles(); anno.inputTranscriptModelDataFromUCSCFiles(); anno.serializeUCSCdata(); } catch (JannovarException e) { System.err.println("[Jannovar]: " + e.toString()); System.exit(1); } return; } /* Option 2. The UCSC files are already on the local disk. Use them to create the ucsc.ser file and return. */ if (anno.serialize()) { try{ anno.inputTranscriptModelDataFromUCSCFiles(); anno.serializeUCSCdata(); } catch (IntervalTreeException e) { System.out.println("Could not construct interval tree: " + e.toString()); System.exit(1); } catch (JannovarException je) { System.out.println("Could not serialize UCSC data: " + je.toString()); System.exit(1); } return; } /* Option 3. The user must provide the ucsc.set file to do analysis. We can either annotate a VCF file (3a) or create a separate annotation file (3b). */ if (anno.deserialize()) { try { anno.deserializeUCSCdata(); } catch (JannovarException je) { System.out.println("Could not deserialize UCSC data: " + je.toString()); System.exit(1); } } else { System.err.println("[Jannovar] Error: You need to pass ucscs.ser file to perform analysis."); usage(); System.exit(1); } /* When we get here, the program has deserialized data and put it into the Chromosome objects. We can now start to annotate variants. */ if (anno.hasVCFfile()) { anno.annotateVCF(); /* 3a or 3b */ } else { System.out.println("No VCF file found"); } } /** The constructor parses the command-line arguments. */ public Jannovar(String argv[]){ this.ucscDirPath="ucsc/"; /* default */ parseCommandLineArguments(argv); } /** * @return true if user wants to download UCSC files */ public boolean downloadUCSC() { return this.downloadUCSC; } /** * This function creates a * {@link jannovar.io.UCSCDownloader UCSCDownloader} object in order to * download the four required UCSC files. If the user has set the proxy and * proxy port via the command line, we use these to download the files. */ public void downloadUCSCfiles() { UCSCDownloader downloader = null; try { if (this.proxy != null && this.proxyPort != null) { downloader = new UCSCDownloader(this.ucscDirPath,this.proxy,this.proxyPort); } else { downloader = new UCSCDownloader(this.ucscDirPath); } downloader.downloadUCSCfiles(); } catch (KGParseException e) { System.err.println(e); System.exit(1); } } /** * @return true if we should serialize the UCSC data. */ public boolean serialize() { return this.performSerialization; } /** * @return true if we should deserialize a file with UCSC data to perform analysis */ public boolean deserialize() { return this.serializedFile != null; } /** * @return true if we should annotate a VCF file */ public boolean hasVCFfile() { return this.VCFfilePath != null; } /** * Annotate a single line of a VCF file, and output the line together with the new * INFO fields representing the annotations. * @param line an object representing the original VCF line * @param v the Variant object that was parsed from the line * @param out A file handle to write to. */ private void annotateVCFLine(VCFLine line, Variant v, Writer out) throws IOException,AnnotationException { byte chr = v.getChromosomeAsByte(); int pos = v.get_position(); String ref = v.get_ref(); String alt = v.get_alt(); Chromosome c = chromosomeMap.get(chr); if (c==null) { String e = String.format("[Jannovar] Could not identify chromosome \"%d\"", chr ); throw new AnnotationException(e); } AnnotationList anno = c.getAnnotationList(pos,ref,alt); if (anno==null) { String e = String.format("[Jannovar] No annotations found for variant %s", v.toString()); throw new AnnotationException(e); } String annotation = anno.getSingleTranscriptAnnotation(); String effect = anno.getVariantType().toString(); String A[] = line.getOriginalVCFLine().split("\t"); for (int i=0;i<7;++i) out.write(A[i] + "\t"); /* Now add the stuff to the INFO line */ String INFO = String.format("EFFECT=%s;HGVS=%s;%s",effect,annotation,A[7]); out.write(INFO); for (int i=8;i<A.length;++i) out.write(A[i] + "\t"); out.write("\n"); } /** * This function outputs a single line in Jannovar format. * @param n The current number (one for each variant in the VCF file) * @param v The current variant with one or more annotations * @param out File handle to write Jannovar file. */ private void outputJannovarLine(int n,Variant v, Writer out) throws IOException,AnnotationException { byte chr = v.getChromosomeAsByte(); String chrStr = v.get_chromosome_as_string(); int pos = v.get_position(); String ref = v.get_ref(); String alt = v.get_alt(); String gtype = v.getGenotypeAsString(); float qual = v.get_variant_quality(); Chromosome c = chromosomeMap.get(chr); if (c==null) { String e = String.format("[Jannovar] Could not identify chromosome \"%d\"", chr ); throw new AnnotationException(e); } AnnotationList anno = c.getAnnotationList(pos,ref,alt); if (anno==null) { String e = String.format("[Jannovar] No annotations found for variant %s", v.toString()); throw new AnnotationException(e); } String effect = anno.getVariantType().toString(); ArrayList<Annotation> lst = anno.getAnnotationList(); for (Annotation a : lst) { String annt = a.getVariantAnnotation(); String sym = a.getGeneSymbol(); String s = String.format("%d\t%s\t%s\t%s\t%s\t%d\t%s\t%s\t%s\t%.1f", n,effect,sym,annt,chrStr,pos,ref,alt,gtype,qual); out.write(s + "\n"); } } private void outputAnnotatedVCF(VCFReader parser) { this.variantList = parser.getVariantList(); ArrayList<VCFLine> lineList = parser.getVCFLineList(); File f = new File(this.VCFfilePath); String outname = f.getName() + ".jannovar"; try { FileWriter fstream = new FileWriter(outname); BufferedWriter out = new BufferedWriter(fstream); /** Write the header of the new VCF file */ ArrayList<String> lst = parser.getAnnotatedVCFHeader(); for (String s: lst) { out.write(s + "\n"); } /** Now write each of the variants. */ for (VCFLine line : lineList) { Variant v = parser.VCFline2Variant(line); try{ annotateVCFLine(line,v,out); } catch (AnnotationException e) { System.out.println("[Jannovar] Warning: Annotation error: " + e.toString()); } } out.close(); }catch (IOException e){ System.out.println("[Jannovar] Error writing annotated VCF file"); System.out.println("[Jannovar] " + e.toString()); System.exit(1); } } private void outputJannovarFormatFile(VCFReader parser) { this.variantList = parser.getVariantList(); File f = new File(this.VCFfilePath); String outname = f.getName() + ".jannovar"; try { FileWriter fstream = new FileWriter(outname); BufferedWriter out = new BufferedWriter(fstream); /** Output each of the variants. */ int n=0; for (Variant v : variantList) { n++; try{ outputJannovarLine(n,v,out); } catch (AnnotationException e) { System.out.println("[Jannovar] Warning: Annotation error: " + e.toString()); } } out.close(); }catch (IOException e){ System.out.println("[Jannovar] Error writing annotated VCF file"); System.out.println("[Jannovar] " + e.toString()); System.exit(1); } } /** * This function inputs a VCF file, and prints the annotated version thereof * to a file (name of the original file with the suffix .jannovar). */ public void annotateVCF() { VCFReader parser = new VCFReader(); VCFLine.setStoreVCFLines(); try{ parser.parseFile(this.VCFfilePath); } catch (VCFParseException e) { System.err.println("Unable to parse VCF file"); System.err.println(e.toString()); System.exit(1); } if (this.jannovarFormat) { outputJannovarFormatFile(parser); } else { outputAnnotatedVCF(parser); } } /** * Inputs the KnownGenes data from UCSC files, convert the * resulting {@link jannovar.reference.TranscriptModel TranscriptModel} * objects to {@link jannovar.interval.Interval Interval} objects, and * store these in a serialized file. */ public void serializeUCSCdata() throws JannovarException { SerializationManager manager = new SerializationManager(); System.out.println("Serializing known gene data as " + this.UCSCserializationFileName); manager.serializeKnownGeneList(this.UCSCserializationFileName, this.knownGenesList); } public void deserializeUCSCdata() throws JannovarException { ArrayList<TranscriptModel> kgList=null; SerializationManager manager = new SerializationManager(); kgList = manager.deserializeKnownGeneList(this.serializedFile); this.chromosomeMap = Chromosome.constructChromosomeMapWithIntervalTree(kgList); } /** * Input the four UCSC files for the KnownGene data. */ private void inputTranscriptModelDataFromUCSCFiles() { UCSCKGParser parser = new UCSCKGParser(this.ucscDirPath); try{ parser.parseUCSCFiles(); } catch (Exception e) { System.out.println("Unable to input data from the UCSC files"); e.printStackTrace(); System.exit(1); } this.knownGenesList = parser.getKnownGeneList(); } /** * A simple printout of the chromosome map for debugging purposes. */ public void debugShowChromosomeMap() { for (Byte c: chromosomeMap.keySet()) { Chromosome chromo = chromosomeMap.get(c); System.out.println("Chrom. " + c + ": " + chromo.getNumberOfGenes() + " genes"); } } /** * Parse the command line. The important options are -n: path to the directory with the NSFP files, * and -C a flag indicating that we want the program to delete the current table in the postgres * database and to create an empty table (using JDBC connection). * @param args Copy of the command line arguments. */ private void parseCommandLineArguments(String[] args) { try { Options options = new Options(); options.addOption(new Option("h","help",false,"Shows this help")); options.addOption(new Option("U","nfsp",true,"Path to directory with UCSC files.")); options.addOption(new Option("S","serialize",false,"Serialize")); options.addOption(new Option("D","deserialize",true,"Path to serialized file with UCSC data")); options.addOption(new Option("V","vcf",true,"Path to VCF file")); options.addOption(new Option("J","janno",false,"Output Jannovar format")); options.addOption(new Option(null,"download-ucsc",false,"Download UCSC KnownGene data")); - options.addOption(new Option(null,"ftp-proxy",true,"FTP Proxy")); - options.addOption(new Option(null,"ftp-proxy-port",true,"FTP Proxy Port")); + options.addOption(new Option(null,"proxy",true,"FTP Proxy")); + options.addOption(new Option(null,"proxy-port",true,"FTP Proxy Port")); Parser parser = new GnuParser(); CommandLine cmd = parser.parse(options,args); if (cmd.hasOption("h") || cmd.hasOption("H") || args.length==0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar Jannovar.jar [-options]", options); usage(); System.exit(0); } if (cmd.hasOption("J")) { this.jannovarFormat = true; } else { this.jannovarFormat = false; } if (cmd.hasOption("download-ucsc")) { this.downloadUCSC = true; this.performSerialization = true; } else { this.downloadUCSC = false; } if (cmd.hasOption('S')) { this.performSerialization = true; } if (cmd.hasOption("proxy")) { this.proxy = cmd.getOptionValue("proxy"); } if (cmd.hasOption("proxy-port")) { this.proxyPort = cmd.getOptionValue("proxy-port"); } if (cmd.hasOption("U")) { this.ucscDirPath = getRequiredOptionValue(cmd,'U'); } if (cmd.hasOption('D')) { this.serializedFile = cmd.getOptionValue('D'); } if (cmd.hasOption("V")) this.VCFfilePath = cmd.getOptionValue("V"); } catch (ParseException pe) { System.err.println("Error parsing command line options"); System.err.println(pe.getMessage()); System.exit(1); } } /** * This function is used to ensure that certain options are passed to the * program before we start execution. * * @param cmd An apache CommandLine object that stores the command line arguments * @param name Name of the argument that must be present * @return Value of the required option as a String. */ private static String getRequiredOptionValue(CommandLine cmd, char name) { String val = cmd.getOptionValue(name); if (val == null) { System.err.println("Aborting because the required argument \"-" + name + "\" wasn't specified! Use the -h for more help."); System.exit(-1); } return val; } private static void usage() { System.out.println("*** Jannovar: Usage ****"); System.out.println("Use case 1: Download UCSC data and create transcript data file (ucsc.ser)"); System.out.println("$ java -jar Jannovar.jar --download-ucsc"); System.out.println("Use case 2: Add annotations to a VCF file"); System.out.println("$ java -jar Jannovar.jar -D ucsc.ser -V example.vcf"); System.out.println("Use case 3: Write new file with Jannovar-format annotations of a VCF file"); System.out.println("$ java -jar Jannovar -D ucsc.ser -V vcfPath -J"); System.out.println("*** See the tutorial for details ***"); } }
true
true
private void parseCommandLineArguments(String[] args) { try { Options options = new Options(); options.addOption(new Option("h","help",false,"Shows this help")); options.addOption(new Option("U","nfsp",true,"Path to directory with UCSC files.")); options.addOption(new Option("S","serialize",false,"Serialize")); options.addOption(new Option("D","deserialize",true,"Path to serialized file with UCSC data")); options.addOption(new Option("V","vcf",true,"Path to VCF file")); options.addOption(new Option("J","janno",false,"Output Jannovar format")); options.addOption(new Option(null,"download-ucsc",false,"Download UCSC KnownGene data")); options.addOption(new Option(null,"ftp-proxy",true,"FTP Proxy")); options.addOption(new Option(null,"ftp-proxy-port",true,"FTP Proxy Port")); Parser parser = new GnuParser(); CommandLine cmd = parser.parse(options,args); if (cmd.hasOption("h") || cmd.hasOption("H") || args.length==0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar Jannovar.jar [-options]", options); usage(); System.exit(0); } if (cmd.hasOption("J")) { this.jannovarFormat = true; } else { this.jannovarFormat = false; } if (cmd.hasOption("download-ucsc")) { this.downloadUCSC = true; this.performSerialization = true; } else { this.downloadUCSC = false; } if (cmd.hasOption('S')) { this.performSerialization = true; } if (cmd.hasOption("proxy")) { this.proxy = cmd.getOptionValue("proxy"); } if (cmd.hasOption("proxy-port")) { this.proxyPort = cmd.getOptionValue("proxy-port"); } if (cmd.hasOption("U")) { this.ucscDirPath = getRequiredOptionValue(cmd,'U'); } if (cmd.hasOption('D')) { this.serializedFile = cmd.getOptionValue('D'); } if (cmd.hasOption("V")) this.VCFfilePath = cmd.getOptionValue("V"); } catch (ParseException pe) { System.err.println("Error parsing command line options"); System.err.println(pe.getMessage()); System.exit(1); } }
private void parseCommandLineArguments(String[] args) { try { Options options = new Options(); options.addOption(new Option("h","help",false,"Shows this help")); options.addOption(new Option("U","nfsp",true,"Path to directory with UCSC files.")); options.addOption(new Option("S","serialize",false,"Serialize")); options.addOption(new Option("D","deserialize",true,"Path to serialized file with UCSC data")); options.addOption(new Option("V","vcf",true,"Path to VCF file")); options.addOption(new Option("J","janno",false,"Output Jannovar format")); options.addOption(new Option(null,"download-ucsc",false,"Download UCSC KnownGene data")); options.addOption(new Option(null,"proxy",true,"FTP Proxy")); options.addOption(new Option(null,"proxy-port",true,"FTP Proxy Port")); Parser parser = new GnuParser(); CommandLine cmd = parser.parse(options,args); if (cmd.hasOption("h") || cmd.hasOption("H") || args.length==0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar Jannovar.jar [-options]", options); usage(); System.exit(0); } if (cmd.hasOption("J")) { this.jannovarFormat = true; } else { this.jannovarFormat = false; } if (cmd.hasOption("download-ucsc")) { this.downloadUCSC = true; this.performSerialization = true; } else { this.downloadUCSC = false; } if (cmd.hasOption('S')) { this.performSerialization = true; } if (cmd.hasOption("proxy")) { this.proxy = cmd.getOptionValue("proxy"); } if (cmd.hasOption("proxy-port")) { this.proxyPort = cmd.getOptionValue("proxy-port"); } if (cmd.hasOption("U")) { this.ucscDirPath = getRequiredOptionValue(cmd,'U'); } if (cmd.hasOption('D')) { this.serializedFile = cmd.getOptionValue('D'); } if (cmd.hasOption("V")) this.VCFfilePath = cmd.getOptionValue("V"); } catch (ParseException pe) { System.err.println("Error parsing command line options"); System.err.println(pe.getMessage()); System.exit(1); } }
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tests/src/org/eclipse/tcf/te/tests/concurrent/ConcurrentTestCase.java b/target_explorer/plugins/org.eclipse.tcf.te.tests/src/org/eclipse/tcf/te/tests/concurrent/ConcurrentTestCase.java index 3274f418a..99a62e812 100644 --- a/target_explorer/plugins/org.eclipse.tcf.te.tests/src/org/eclipse/tcf/te/tests/concurrent/ConcurrentTestCase.java +++ b/target_explorer/plugins/org.eclipse.tcf.te.tests/src/org/eclipse/tcf/te/tests/concurrent/ConcurrentTestCase.java @@ -1,332 +1,332 @@ /******************************************************************************* * Copyright (c) 2012, 2013 Wind River Systems, Inc. and others. All rights reserved. * This program and the accompanying materials are made available under the terms * of the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.tcf.te.tests.concurrent; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.tcf.te.runtime.concurrent.Executors; import org.eclipse.tcf.te.runtime.concurrent.executors.AbstractDelegatingExecutorService; import org.eclipse.tcf.te.runtime.concurrent.interfaces.IExecutor; import org.eclipse.tcf.te.runtime.concurrent.interfaces.INestableExecutor; import org.eclipse.tcf.te.runtime.concurrent.interfaces.ISingleThreadedExecutor; import org.eclipse.tcf.te.runtime.concurrent.util.ExecutorsUtil; import org.eclipse.tcf.te.tests.CoreTestCase; /** * Concurrent test cases. */ public class ConcurrentTestCase extends CoreTestCase { /** * Provides a test suite to the caller which combines all single * test bundled within this category. * * @return Test suite containing all test for this test category. */ public static Test getTestSuite() { TestSuite testSuite = new TestSuite("Test concurrent framework"); //$NON-NLS-1$ // add ourself to the test suite testSuite.addTestSuite(ConcurrentTestCase.class); return testSuite; } //***** BEGIN SECTION: Single test methods ***** //NOTE: All method which represents a single test case must // start with 'test'! public void testPrivateOrInternalClasses() { ExecutorsUtil executorsUtil = new ExecutorsUtil(); assertNotNull(executorsUtil); try { Constructor<?>[] constructors = Executors.class.getDeclaredConstructors(); for (Constructor<?> constructor : constructors) { assertNotNull("Failed to get default constructor of Executors!", constructors); //$NON-NLS-1$ constructor.setAccessible(true); Object instance = constructor.newInstance((Object[])null); assertNotNull("Failed to invoke default constructor of Executors!", instance); //$NON-NLS-1$ } } catch (Exception e) {} } public void testSingleThreadExecutorService() { // Get the execution service instance IExecutor executor = Executors.newExecutor("org.eclipse.tcf.te.runtime.concurrent.executors.singleThreaded"); //$NON-NLS-1$ assertNotNull("Failed to get executor instance!", executor); //$NON-NLS-1$ assertTrue("Executor not implementing ISingleThreadedExecutor", executor instanceof ISingleThreadedExecutor); //$NON-NLS-1$ final ISingleThreadedExecutor singleThreadedExecutor = (ISingleThreadedExecutor)executor; // Within here, we have to be outside the execution thread assertFalse("Is execution thread but should not!", singleThreadedExecutor.isExecutorThread()); //$NON-NLS-1$ // Create a runnable to be executed with the executor thread final Boolean[] result = new Boolean[1]; result[0] = Boolean.FALSE; Runnable runnable = new Runnable() { @Override public void run() { result[0] = Boolean.valueOf(singleThreadedExecutor.isExecutorThread()); } }; // Execute singleThreadedExecutor.execute(runnable); // Give it a little bit time to run AtomicInteger counter = new AtomicInteger(); while (Boolean.FALSE.equals(result[0]) && counter.getAndIncrement() < 20) { try { Thread.sleep(100); } catch (InterruptedException e) { /* ignored on purpose */ } } assertTrue("Runnable not executed within the executor thread!", result[0].booleanValue()); //$NON-NLS-1$ // If the executor is implementing the ExecutorService interface, we can shutdown the executor if (executor instanceof ExecutorService) { ExecutorService service = (ExecutorService)executor; // Shutdown the executor service assertFalse("Executor service instance is marked as shutdowned, but should not!", service.isShutdown()); //$NON-NLS-1$ service.shutdown(); assertTrue("Executor service instance is not marked as shutdowned, but should!", service.isShutdown()); //$NON-NLS-1$ } // Get the shared executor service instance IExecutor sharedExecutor = Executors.getSharedExecutor("org.eclipse.tcf.te.runtime.concurrent.executors.singleThreaded"); //$NON-NLS-1$ assertNotNull("Failed to get shared executor instance!"); //$NON-NLS-1$ assertNotSame("Shared executor instance is same instance as the newly created executor!", executor, sharedExecutor); //$NON-NLS-1$ // If the shared executor service is not a nestable service, our tests are done here if (!(sharedExecutor instanceof INestableExecutor)) return; // Test the nestable executor functionality final INestableExecutor nestedExecutor = (INestableExecutor)sharedExecutor; result[0] = Boolean.FALSE; final List<String> result2 = new ArrayList<String>(); // Single threaded and nested --> means maxDepth == 1 assertEquals("Single threaded nested executor has invalid maxDepth set!", 1, nestedExecutor.getMaxDepth()); //$NON-NLS-1$ Runnable runnable1 = new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) {} result2.add("1"); //$NON-NLS-1$ while (nestedExecutor.readAndExecute()) {} result2.add("3"); //$NON-NLS-1$ result[0] = Boolean.TRUE; } }; Runnable runnable2 = new Runnable() { @Override public void run() { result2.add("2"); //$NON-NLS-1$ } }; nestedExecutor.execute(runnable1); nestedExecutor.execute(runnable2); // Give it a little bit time to run counter = new AtomicInteger(); - while (Boolean.FALSE.equals(result[0]) && counter.getAndIncrement() < 20) { + while (Boolean.FALSE.equals(result[0]) && counter.getAndIncrement() < 40) { try { Thread.sleep(100); } catch (InterruptedException e) { /* ignored on purpose */ } } assertTrue("Runnable not executed within the executor thread!", result[0].booleanValue()); //$NON-NLS-1$ // The result list should contain "1", "2", "3" in this order. assertEquals("Unexpected result list size!", 3, result2.size()); //$NON-NLS-1$ assertEquals("Unexpected result at position 1!", "1", result2.get(0)); //$NON-NLS-1$ //$NON-NLS-2$ assertEquals("Unexpected result at position 2!", "2", result2.get(1)); //$NON-NLS-1$ //$NON-NLS-2$ assertEquals("Unexpected result at position 3!", "3", result2.get(2)); //$NON-NLS-1$ //$NON-NLS-2$ // Get all shared executor service instances IExecutor[] executors = Executors.getAllSharedExecutors(); assertTrue("Unexpected emply list returned!", executors.length > 0); //$NON-NLS-1$ } class InternalTestAbstractDelegatingExecutorServiceImplementation extends AbstractDelegatingExecutorService { final Map<String, Object> fResultMap; /** * Constructor. * */ public InternalTestAbstractDelegatingExecutorServiceImplementation(Map<String, Object> resultMap) { super(); assertNotNull("Invalid constructor parameter resultMap. Must not be null!", resultMap); //$NON-NLS-1$ fResultMap = resultMap; } /* (non-Javadoc) * @see org.eclipse.tcf.te.runtime.concurrent.executors.AbstractDelegatingExecutorService#createExecutorServiceDelegate() */ @Override protected ExecutorService createExecutorServiceDelegate() { return new ExecutorService() { @Override public void execute(Runnable command) { fResultMap.put("ExecutorService.execute", Boolean.TRUE); //$NON-NLS-1$ } @Override public <T> Future<T> submit(Runnable task, T result) { fResultMap.put("ExecutorService.submit1", Boolean.TRUE); //$NON-NLS-1$ return null; } @Override public Future<?> submit(Runnable task) { fResultMap.put("ExecutorService.submit2", Boolean.TRUE); //$NON-NLS-1$ return null; } @Override public <T> Future<T> submit(Callable<T> task) { fResultMap.put("ExecutorService.submit3", Boolean.TRUE); //$NON-NLS-1$ return null; } @Override public List<Runnable> shutdownNow() { fResultMap.put("ExecutorService.shutdownNow", Boolean.TRUE); //$NON-NLS-1$ return null; } @Override public void shutdown() { fResultMap.put("ExecutorService.shutdown", Boolean.TRUE); //$NON-NLS-1$ } @Override public boolean isTerminated() { fResultMap.put("ExecutorService.isTerminated", Boolean.TRUE); //$NON-NLS-1$ return false; } @Override public boolean isShutdown() { fResultMap.put("ExecutorService.isShutdown", Boolean.TRUE); //$NON-NLS-1$ return false; } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { fResultMap.put("ExecutorService.invokeAny1", Boolean.TRUE); //$NON-NLS-1$ return null; } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { fResultMap.put("ExecutorService.invokeAny2", Boolean.TRUE); //$NON-NLS-1$ return null; } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { fResultMap.put("ExecutorService.invokeAll1", Boolean.TRUE); //$NON-NLS-1$ return null; } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { fResultMap.put("ExecutorService.invokeAll2", Boolean.TRUE); //$NON-NLS-1$ return null; } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { fResultMap.put("ExecutorService.awaitTermination", Boolean.TRUE); //$NON-NLS-1$ return false; } }; } } public void testAbstractDelegatingExecutorService() { // To test the AbstractDelegatingExecutorService, we create a special // executor storing the signature of the invoked method into a map // Create the result map final Map<String, Object> result = new HashMap<String, Object>(); // Construct the test service AbstractDelegatingExecutorService service = new InternalTestAbstractDelegatingExecutorServiceImplementation(result); service.initializeExecutorServiceDelegate(); assertNotNull("Failed to instanciate and to initialize the test executor service implementation!", service); //$NON-NLS-1$ Runnable runnable = new Runnable() { @Override public void run() { } }; Callable<Object> callable = new Callable<Object>() { @Override public Object call() throws Exception { return null; } }; List<Callable<Object>> callables = new ArrayList<Callable<Object>>(); callables.add(callable); // Invoke each method now service.execute(runnable); service.submit(callable); service.submit(runnable); service.submit(runnable, new Object()); service.shutdown(); service.shutdownNow(); service.isShutdown(); service.isTerminated(); try { service.invokeAny(callables); service.invokeAny(callables, 0, TimeUnit.MICROSECONDS); service.invokeAll(callables); service.invokeAll(callables, 0, TimeUnit.MICROSECONDS); service.awaitTermination(0, TimeUnit.MICROSECONDS); } catch (Exception e) {} assertTrue(((Boolean)result.get("ExecutorService.execute")).booleanValue()); //$NON-NLS-1$ assertTrue(((Boolean)result.get("ExecutorService.submit1")).booleanValue()); //$NON-NLS-1$ assertTrue(((Boolean)result.get("ExecutorService.submit2")).booleanValue()); //$NON-NLS-1$ assertTrue(((Boolean)result.get("ExecutorService.submit3")).booleanValue()); //$NON-NLS-1$ assertTrue(((Boolean)result.get("ExecutorService.shutdown")).booleanValue()); //$NON-NLS-1$ assertTrue(((Boolean)result.get("ExecutorService.shutdownNow")).booleanValue()); //$NON-NLS-1$ assertTrue(((Boolean)result.get("ExecutorService.isShutdown")).booleanValue()); //$NON-NLS-1$ assertTrue(((Boolean)result.get("ExecutorService.isTerminated")).booleanValue()); //$NON-NLS-1$ assertTrue(((Boolean)result.get("ExecutorService.invokeAny1")).booleanValue()); //$NON-NLS-1$ assertTrue(((Boolean)result.get("ExecutorService.invokeAny2")).booleanValue()); //$NON-NLS-1$ assertTrue(((Boolean)result.get("ExecutorService.invokeAll1")).booleanValue()); //$NON-NLS-1$ assertTrue(((Boolean)result.get("ExecutorService.invokeAll2")).booleanValue()); //$NON-NLS-1$ assertTrue(((Boolean)result.get("ExecutorService.awaitTermination")).booleanValue()); //$NON-NLS-1$ } //***** END SECTION: Single test methods ***** }
true
true
public void testSingleThreadExecutorService() { // Get the execution service instance IExecutor executor = Executors.newExecutor("org.eclipse.tcf.te.runtime.concurrent.executors.singleThreaded"); //$NON-NLS-1$ assertNotNull("Failed to get executor instance!", executor); //$NON-NLS-1$ assertTrue("Executor not implementing ISingleThreadedExecutor", executor instanceof ISingleThreadedExecutor); //$NON-NLS-1$ final ISingleThreadedExecutor singleThreadedExecutor = (ISingleThreadedExecutor)executor; // Within here, we have to be outside the execution thread assertFalse("Is execution thread but should not!", singleThreadedExecutor.isExecutorThread()); //$NON-NLS-1$ // Create a runnable to be executed with the executor thread final Boolean[] result = new Boolean[1]; result[0] = Boolean.FALSE; Runnable runnable = new Runnable() { @Override public void run() { result[0] = Boolean.valueOf(singleThreadedExecutor.isExecutorThread()); } }; // Execute singleThreadedExecutor.execute(runnable); // Give it a little bit time to run AtomicInteger counter = new AtomicInteger(); while (Boolean.FALSE.equals(result[0]) && counter.getAndIncrement() < 20) { try { Thread.sleep(100); } catch (InterruptedException e) { /* ignored on purpose */ } } assertTrue("Runnable not executed within the executor thread!", result[0].booleanValue()); //$NON-NLS-1$ // If the executor is implementing the ExecutorService interface, we can shutdown the executor if (executor instanceof ExecutorService) { ExecutorService service = (ExecutorService)executor; // Shutdown the executor service assertFalse("Executor service instance is marked as shutdowned, but should not!", service.isShutdown()); //$NON-NLS-1$ service.shutdown(); assertTrue("Executor service instance is not marked as shutdowned, but should!", service.isShutdown()); //$NON-NLS-1$ } // Get the shared executor service instance IExecutor sharedExecutor = Executors.getSharedExecutor("org.eclipse.tcf.te.runtime.concurrent.executors.singleThreaded"); //$NON-NLS-1$ assertNotNull("Failed to get shared executor instance!"); //$NON-NLS-1$ assertNotSame("Shared executor instance is same instance as the newly created executor!", executor, sharedExecutor); //$NON-NLS-1$ // If the shared executor service is not a nestable service, our tests are done here if (!(sharedExecutor instanceof INestableExecutor)) return; // Test the nestable executor functionality final INestableExecutor nestedExecutor = (INestableExecutor)sharedExecutor; result[0] = Boolean.FALSE; final List<String> result2 = new ArrayList<String>(); // Single threaded and nested --> means maxDepth == 1 assertEquals("Single threaded nested executor has invalid maxDepth set!", 1, nestedExecutor.getMaxDepth()); //$NON-NLS-1$ Runnable runnable1 = new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) {} result2.add("1"); //$NON-NLS-1$ while (nestedExecutor.readAndExecute()) {} result2.add("3"); //$NON-NLS-1$ result[0] = Boolean.TRUE; } }; Runnable runnable2 = new Runnable() { @Override public void run() { result2.add("2"); //$NON-NLS-1$ } }; nestedExecutor.execute(runnable1); nestedExecutor.execute(runnable2); // Give it a little bit time to run counter = new AtomicInteger(); while (Boolean.FALSE.equals(result[0]) && counter.getAndIncrement() < 20) { try { Thread.sleep(100); } catch (InterruptedException e) { /* ignored on purpose */ } } assertTrue("Runnable not executed within the executor thread!", result[0].booleanValue()); //$NON-NLS-1$ // The result list should contain "1", "2", "3" in this order. assertEquals("Unexpected result list size!", 3, result2.size()); //$NON-NLS-1$ assertEquals("Unexpected result at position 1!", "1", result2.get(0)); //$NON-NLS-1$ //$NON-NLS-2$ assertEquals("Unexpected result at position 2!", "2", result2.get(1)); //$NON-NLS-1$ //$NON-NLS-2$ assertEquals("Unexpected result at position 3!", "3", result2.get(2)); //$NON-NLS-1$ //$NON-NLS-2$ // Get all shared executor service instances IExecutor[] executors = Executors.getAllSharedExecutors(); assertTrue("Unexpected emply list returned!", executors.length > 0); //$NON-NLS-1$ }
public void testSingleThreadExecutorService() { // Get the execution service instance IExecutor executor = Executors.newExecutor("org.eclipse.tcf.te.runtime.concurrent.executors.singleThreaded"); //$NON-NLS-1$ assertNotNull("Failed to get executor instance!", executor); //$NON-NLS-1$ assertTrue("Executor not implementing ISingleThreadedExecutor", executor instanceof ISingleThreadedExecutor); //$NON-NLS-1$ final ISingleThreadedExecutor singleThreadedExecutor = (ISingleThreadedExecutor)executor; // Within here, we have to be outside the execution thread assertFalse("Is execution thread but should not!", singleThreadedExecutor.isExecutorThread()); //$NON-NLS-1$ // Create a runnable to be executed with the executor thread final Boolean[] result = new Boolean[1]; result[0] = Boolean.FALSE; Runnable runnable = new Runnable() { @Override public void run() { result[0] = Boolean.valueOf(singleThreadedExecutor.isExecutorThread()); } }; // Execute singleThreadedExecutor.execute(runnable); // Give it a little bit time to run AtomicInteger counter = new AtomicInteger(); while (Boolean.FALSE.equals(result[0]) && counter.getAndIncrement() < 20) { try { Thread.sleep(100); } catch (InterruptedException e) { /* ignored on purpose */ } } assertTrue("Runnable not executed within the executor thread!", result[0].booleanValue()); //$NON-NLS-1$ // If the executor is implementing the ExecutorService interface, we can shutdown the executor if (executor instanceof ExecutorService) { ExecutorService service = (ExecutorService)executor; // Shutdown the executor service assertFalse("Executor service instance is marked as shutdowned, but should not!", service.isShutdown()); //$NON-NLS-1$ service.shutdown(); assertTrue("Executor service instance is not marked as shutdowned, but should!", service.isShutdown()); //$NON-NLS-1$ } // Get the shared executor service instance IExecutor sharedExecutor = Executors.getSharedExecutor("org.eclipse.tcf.te.runtime.concurrent.executors.singleThreaded"); //$NON-NLS-1$ assertNotNull("Failed to get shared executor instance!"); //$NON-NLS-1$ assertNotSame("Shared executor instance is same instance as the newly created executor!", executor, sharedExecutor); //$NON-NLS-1$ // If the shared executor service is not a nestable service, our tests are done here if (!(sharedExecutor instanceof INestableExecutor)) return; // Test the nestable executor functionality final INestableExecutor nestedExecutor = (INestableExecutor)sharedExecutor; result[0] = Boolean.FALSE; final List<String> result2 = new ArrayList<String>(); // Single threaded and nested --> means maxDepth == 1 assertEquals("Single threaded nested executor has invalid maxDepth set!", 1, nestedExecutor.getMaxDepth()); //$NON-NLS-1$ Runnable runnable1 = new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) {} result2.add("1"); //$NON-NLS-1$ while (nestedExecutor.readAndExecute()) {} result2.add("3"); //$NON-NLS-1$ result[0] = Boolean.TRUE; } }; Runnable runnable2 = new Runnable() { @Override public void run() { result2.add("2"); //$NON-NLS-1$ } }; nestedExecutor.execute(runnable1); nestedExecutor.execute(runnable2); // Give it a little bit time to run counter = new AtomicInteger(); while (Boolean.FALSE.equals(result[0]) && counter.getAndIncrement() < 40) { try { Thread.sleep(100); } catch (InterruptedException e) { /* ignored on purpose */ } } assertTrue("Runnable not executed within the executor thread!", result[0].booleanValue()); //$NON-NLS-1$ // The result list should contain "1", "2", "3" in this order. assertEquals("Unexpected result list size!", 3, result2.size()); //$NON-NLS-1$ assertEquals("Unexpected result at position 1!", "1", result2.get(0)); //$NON-NLS-1$ //$NON-NLS-2$ assertEquals("Unexpected result at position 2!", "2", result2.get(1)); //$NON-NLS-1$ //$NON-NLS-2$ assertEquals("Unexpected result at position 3!", "3", result2.get(2)); //$NON-NLS-1$ //$NON-NLS-2$ // Get all shared executor service instances IExecutor[] executors = Executors.getAllSharedExecutors(); assertTrue("Unexpected emply list returned!", executors.length > 0); //$NON-NLS-1$ }
diff --git a/bamboo-sonar-tasks/src/main/java/com/marvelution/bamboo/plugins/sonar/tasks/configuration/AbstractSonarMavenBuildTaskConfigurator.java b/bamboo-sonar-tasks/src/main/java/com/marvelution/bamboo/plugins/sonar/tasks/configuration/AbstractSonarMavenBuildTaskConfigurator.java index d0abd0c..0c78c7d 100644 --- a/bamboo-sonar-tasks/src/main/java/com/marvelution/bamboo/plugins/sonar/tasks/configuration/AbstractSonarMavenBuildTaskConfigurator.java +++ b/bamboo-sonar-tasks/src/main/java/com/marvelution/bamboo/plugins/sonar/tasks/configuration/AbstractSonarMavenBuildTaskConfigurator.java @@ -1,148 +1,149 @@ /* * Licensed to Marvelution under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Marvelution 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.marvelution.bamboo.plugins.sonar.tasks.configuration; import com.atlassian.bamboo.collections.ActionParametersMap; import com.atlassian.bamboo.task.AbstractTaskConfigurator; import com.atlassian.bamboo.task.TaskDefinition; import com.atlassian.bamboo.utils.error.ErrorCollection; import com.google.common.collect.ImmutableList; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; /** * {@link AbstractTaskConfigurator} implementation for the Sonar Maven builders * * @author <a href="mailto:markrekveld@marvelution.com">Mark Rekveld</a> */ public abstract class AbstractSonarMavenBuildTaskConfigurator extends AbstractSonarBuildTaskConfigurator { private static final Logger LOGGER = Logger.getLogger(AbstractSonarMavenBuildTaskConfigurator.class); private static final List<String> FIELDS_TO_COPY = ImmutableList.of(CFG_GOALS, CFG_SONAR_JDBC_PROFILE, CFG_SONAR_JDBC_OPTION, CFG_SONAR_PLUGIN_PREINSTALLED); /** * {@inheritDoc} */ @NotNull @Override public Map<String, String> generateTaskConfigMap(@NotNull final ActionParametersMap params, @Nullable final TaskDefinition previousTaskDefinition) { Map<String, String> config = super.generateTaskConfigMap(params, previousTaskDefinition); taskConfiguratorHelper.populateTaskConfigMapWithActionParameters(config, params, FIELDS_TO_COPY); StringBuilder goals = new StringBuilder(); if (params.getBoolean(CFG_SONAR_PLUGIN_PREINSTALLED)) { goals.append(SONAR_PLUGIN_GOAL); } else { goals.append(SONAR_PLUGIN_GROUPID).append(":").append(SONAR_PLUGIN_ARTIFACTID).append(":") .append(getSonarMavenPluginVersion()); } goals.append(":").append(SONAR_PLUGIN_GOAL); if (StringUtils.isNotBlank(params.getString(CFG_SONAR_EXTRA_CUSTOM_PARAMETERS))) { goals.append(" ").append(params.getString(CFG_SONAR_EXTRA_CUSTOM_PARAMETERS)); } + config.put(CFG_GOALS, goals.toString()); return config; } /** * {@inheritDoc} */ @Override public void populateContextForCreate(Map<String, Object> context) { super.populateContextForCreate(context); context.put(CFG_SONAR_JDBC_OPTION, CFG_SONAR_JDBC_USE_FORM); } /** * {@inheritDoc} */ @Override public void populateContextForEdit(@NotNull Map<String, Object> context, @NotNull TaskDefinition taskDefinition) { super.populateContextForEdit(context, taskDefinition); taskConfiguratorHelper.populateContextWithConfiguration(context, taskDefinition, FIELDS_TO_COPY); } /** * {@inheritDoc} */ @Override public void populateContextForView(@NotNull Map<String, Object> context, @NotNull TaskDefinition taskDefinition) { super.populateContextForView(context, taskDefinition); taskConfiguratorHelper.populateContextWithConfiguration(context, taskDefinition, FIELDS_TO_COPY); context.put(CTX_USES_PROFILE, CFG_SONAR_JDBC_USE_PROFILE.equals(taskDefinition.getConfiguration().get(CFG_SONAR_JDBC_OPTION))); } /** * {@inheritDoc} */ @Override protected void populateContextForAllOperations(Map<String, Object> context) { super.populateContextForAllOperations(context); context.put(CTX_SONAR_JDBC_OPTIONS, CFG_SONAR_JDBC_OPTIONS); } /** * {@inheritDoc} */ @Override public void validate(@NotNull ActionParametersMap params, @NotNull ErrorCollection errorCollection) { super.validate(params, errorCollection); validateSonarServer(params, errorCollection); } /** * {@inheritDoc} */ @Override public void validateSonarServer(ActionParametersMap params, ErrorCollection errorCollection) { LOGGER.debug("Validating Sonar JDBC Properties"); if (CFG_SONAR_JDBC_USE_PROFILE.equals(params.getString(CFG_SONAR_JDBC_OPTION))) { if (StringUtils.isBlank(params.getString(CFG_SONAR_JDBC_PROFILE))) { errorCollection.addError(CFG_SONAR_JDBC_PROFILE, textProvider.getText("sonar.jdbc.profile.mandatory")); } } else { super.validateSonarServer(params, errorCollection); } } /** * {@inheritDoc} */ @Override public void validateSonarProject(ActionParametersMap params, ErrorCollection errorCollection) { LOGGER.debug("Validating Sonar Project Properties"); // Not needed yet for this task } /** * Getter for the Maven plugin org.codehaus.mojo:sonar-maven-plugin * * @return the version string */ protected abstract String getSonarMavenPluginVersion(); }
true
true
public Map<String, String> generateTaskConfigMap(@NotNull final ActionParametersMap params, @Nullable final TaskDefinition previousTaskDefinition) { Map<String, String> config = super.generateTaskConfigMap(params, previousTaskDefinition); taskConfiguratorHelper.populateTaskConfigMapWithActionParameters(config, params, FIELDS_TO_COPY); StringBuilder goals = new StringBuilder(); if (params.getBoolean(CFG_SONAR_PLUGIN_PREINSTALLED)) { goals.append(SONAR_PLUGIN_GOAL); } else { goals.append(SONAR_PLUGIN_GROUPID).append(":").append(SONAR_PLUGIN_ARTIFACTID).append(":") .append(getSonarMavenPluginVersion()); } goals.append(":").append(SONAR_PLUGIN_GOAL); if (StringUtils.isNotBlank(params.getString(CFG_SONAR_EXTRA_CUSTOM_PARAMETERS))) { goals.append(" ").append(params.getString(CFG_SONAR_EXTRA_CUSTOM_PARAMETERS)); } return config; }
public Map<String, String> generateTaskConfigMap(@NotNull final ActionParametersMap params, @Nullable final TaskDefinition previousTaskDefinition) { Map<String, String> config = super.generateTaskConfigMap(params, previousTaskDefinition); taskConfiguratorHelper.populateTaskConfigMapWithActionParameters(config, params, FIELDS_TO_COPY); StringBuilder goals = new StringBuilder(); if (params.getBoolean(CFG_SONAR_PLUGIN_PREINSTALLED)) { goals.append(SONAR_PLUGIN_GOAL); } else { goals.append(SONAR_PLUGIN_GROUPID).append(":").append(SONAR_PLUGIN_ARTIFACTID).append(":") .append(getSonarMavenPluginVersion()); } goals.append(":").append(SONAR_PLUGIN_GOAL); if (StringUtils.isNotBlank(params.getString(CFG_SONAR_EXTRA_CUSTOM_PARAMETERS))) { goals.append(" ").append(params.getString(CFG_SONAR_EXTRA_CUSTOM_PARAMETERS)); } config.put(CFG_GOALS, goals.toString()); return config; }
diff --git a/tests/sprints/sprint0_3/src/test/java/luminis/CompleteAlarmsWorkflowTest.java b/tests/sprints/sprint0_3/src/test/java/luminis/CompleteAlarmsWorkflowTest.java index 93ef63f30..b4af20f69 100644 --- a/tests/sprints/sprint0_3/src/test/java/luminis/CompleteAlarmsWorkflowTest.java +++ b/tests/sprints/sprint0_3/src/test/java/luminis/CompleteAlarmsWorkflowTest.java @@ -1,207 +1,207 @@ package luminis; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.OptionUtils.combine; import java.util.ArrayList; import java.util.Date; import java.util.Dictionary; import java.util.Hashtable; import java.util.List; import junit.framework.Assert; import net.i2cat.luminis.protocols.wonesys.WonesysProtocolSession; import net.i2cat.luminis.transports.wonesys.rawsocket.RawSocketTransport; import net.i2cat.nexus.tests.IntegrationTestsHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.karaf.testing.AbstractIntegrationTest; import org.junit.Test; import org.junit.runner.RunWith; import org.opennaas.core.events.IEventManager; import org.opennaas.core.resources.ILifecycle; import org.opennaas.core.resources.IResource; import org.opennaas.core.resources.IResourceManager; import org.opennaas.core.resources.ResourceException; import org.opennaas.core.resources.alarms.IAlarmsRepository; import org.opennaas.core.resources.alarms.ResourceAlarm; import org.opennaas.core.resources.capability.ICapabilityFactory; import org.opennaas.core.resources.descriptor.ResourceDescriptor; import org.opennaas.core.resources.helpers.ResourceDescriptorFactory; import org.opennaas.core.resources.protocol.IProtocolManager; import org.opennaas.core.resources.protocol.IProtocolSession; import org.opennaas.core.resources.protocol.IProtocolSessionManager; import org.opennaas.core.resources.protocol.ProtocolException; import org.opennaas.core.resources.protocol.ProtocolSessionContext; import org.ops4j.pax.exam.Inject; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.osgi.framework.BundleContext; import org.osgi.service.event.Event; @RunWith(JUnit4TestRunner.class) public class CompleteAlarmsWorkflowTest extends AbstractIntegrationTest { // import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption; static Log log = LogFactory.getLog(CompleteAlarmsWorkflowTest.class); @Inject BundleContext bundleContext = null; List<Event> receivedEvents = new ArrayList<Event>(); final Object lock = new Object(); IEventManager eventManager; IResourceManager resourceManager; IProtocolManager protocolManager; IAlarmsRepository alarmsRepo; @Configuration public static Option[] configuration() throws Exception { Option[] options = combine( IntegrationTestsHelper.getLuminisTestOptions(), mavenBundle().groupId("org.opennaas").artifactId( "opennaas-core-events"), mavenBundle().groupId("net.i2cat.nexus").artifactId( "net.i2cat.nexus.tests.helper") // , vmOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005") ); return options; } private void initBundles() { IntegrationTestsHelper.waitForAllBundlesActive(bundleContext); eventManager = getOsgiService(IEventManager.class, 5000); resourceManager = getOsgiService(IResourceManager.class, 5000); protocolManager = getOsgiService(IProtocolManager.class, 5000); alarmsRepo = getOsgiService(IAlarmsRepository.class, 5000); ICapabilityFactory monitoringFactory = getOsgiService(ICapabilityFactory.class, "capability=monitoring", 5000); Assert.assertNotNull(monitoringFactory); } private TestInitInfo setUp() throws ResourceException, ProtocolException { initBundles(); //clear resource repo List<IResource> resources = resourceManager.listResources(); for (IResource resource : resources){ if (resource.getState().equals(ILifecycle.State.ACTIVE)) resourceManager.stopResource(resource.getResourceIdentifier()); - resourceManager.stopResource(resource.getResourceIdentifier()); + resourceManager.removeResource(resource.getResourceIdentifier()); } IResource resource = resourceManager.createResource(createResourceDescriptorWithMonitoring()); // create session IProtocolSessionManager sessionManager = protocolManager.getProtocolSessionManagerWithContext(resource.getResourceIdentifier().getId(), createWonesysSessionContextMock()); IProtocolSession session = sessionManager.obtainSessionByProtocol("wonesys", false); // start resource resourceManager.startResource(resource.getResourceIdentifier()); String transportId = ((WonesysProtocolSession)session).getWonesysTransport().getTransportID(); alarmsRepo.clear(); TestInitInfo info = new TestInitInfo(); info.resource = resource; info.sessionManager = sessionManager; info.session = (WonesysProtocolSession) session; info.transportId = transportId; return info; } private void tearDown(TestInitInfo initInfo) throws ResourceException, ProtocolException { resourceManager.stopResource(initInfo.resource.getResourceIdentifier()); resourceManager.removeResource(initInfo.resource.getResourceIdentifier()); initInfo.sessionManager.destroyProtocolSession(initInfo.session.getSessionId()); alarmsRepo.clear(); } @Test public void completeAlarmsWorkflowTest() throws ResourceException, ProtocolException { TestInitInfo initInfo = setUp(); // ChannelPlan Changed message String chassis = "00"; String slot = "01"; String alarmMessage = "FFFF0000" + chassis + slot + "01FF80"; generateRawSocketEvent(initInfo.transportId, alarmMessage); try { Thread.sleep(20000); List<ResourceAlarm> alarms = alarmsRepo.getResourceAlarms(initInfo.resource.getResourceIdentifier().getId()); Assert.assertFalse(alarms.isEmpty()); Assert.assertTrue(alarms.size() == 1); //Check alarm is identified as Channel plan changed alarm Assert.assertTrue(alarms.get(0).getProperty(ResourceAlarm.ALARM_CODE_PROPERTY).equals("CPLANCHANGED")); } catch(Exception e) { Assert.fail(e.getLocalizedMessage()); } finally { tearDown(initInfo); } } private ResourceDescriptor createResourceDescriptorWithMonitoring() { List<String> capabilities = new ArrayList<String>(); capabilities.add("monitoring"); capabilities.add("queue"); return ResourceDescriptorFactory.newResourceDescriptorProteus("TestProteus", "roadm", capabilities); } private ProtocolSessionContext createWonesysSessionContextMock() { ProtocolSessionContext protocolSessionContext = new ProtocolSessionContext(); protocolSessionContext.addParameter("protocol.mock", "true"); protocolSessionContext.addParameter(ProtocolSessionContext.PROTOCOL,"wonesys"); return protocolSessionContext; } private void generateRawSocketEvent(String transportId, String message) { Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put(RawSocketTransport.MESSAGE_PROPERTY_NAME, message); properties.put(RawSocketTransport.TRANSPORT_ID_PROPERTY_NAME, transportId); long creationTime = new Date().getTime(); properties.put(RawSocketTransport.ARRIVAL_TIME_PROPERTY_NAME, creationTime); Event event = new Event(RawSocketTransport.MSG_RCVD_EVENT_TOPIC, properties); eventManager.publishEvent(event); log.debug("RawSocketTransport Event generated! " + message + " at " + creationTime); } class TestInitInfo { public WonesysProtocolSession session; public IProtocolSessionManager sessionManager; public IResource resource; public String transportId; } }
true
true
private TestInitInfo setUp() throws ResourceException, ProtocolException { initBundles(); //clear resource repo List<IResource> resources = resourceManager.listResources(); for (IResource resource : resources){ if (resource.getState().equals(ILifecycle.State.ACTIVE)) resourceManager.stopResource(resource.getResourceIdentifier()); resourceManager.stopResource(resource.getResourceIdentifier()); } IResource resource = resourceManager.createResource(createResourceDescriptorWithMonitoring()); // create session IProtocolSessionManager sessionManager = protocolManager.getProtocolSessionManagerWithContext(resource.getResourceIdentifier().getId(), createWonesysSessionContextMock()); IProtocolSession session = sessionManager.obtainSessionByProtocol("wonesys", false); // start resource resourceManager.startResource(resource.getResourceIdentifier()); String transportId = ((WonesysProtocolSession)session).getWonesysTransport().getTransportID(); alarmsRepo.clear(); TestInitInfo info = new TestInitInfo(); info.resource = resource; info.sessionManager = sessionManager; info.session = (WonesysProtocolSession) session; info.transportId = transportId; return info; }
private TestInitInfo setUp() throws ResourceException, ProtocolException { initBundles(); //clear resource repo List<IResource> resources = resourceManager.listResources(); for (IResource resource : resources){ if (resource.getState().equals(ILifecycle.State.ACTIVE)) resourceManager.stopResource(resource.getResourceIdentifier()); resourceManager.removeResource(resource.getResourceIdentifier()); } IResource resource = resourceManager.createResource(createResourceDescriptorWithMonitoring()); // create session IProtocolSessionManager sessionManager = protocolManager.getProtocolSessionManagerWithContext(resource.getResourceIdentifier().getId(), createWonesysSessionContextMock()); IProtocolSession session = sessionManager.obtainSessionByProtocol("wonesys", false); // start resource resourceManager.startResource(resource.getResourceIdentifier()); String transportId = ((WonesysProtocolSession)session).getWonesysTransport().getTransportID(); alarmsRepo.clear(); TestInitInfo info = new TestInitInfo(); info.resource = resource; info.sessionManager = sessionManager; info.session = (WonesysProtocolSession) session; info.transportId = transportId; return info; }
diff --git a/modules/activiti-rest/src/main/java/org/activiti/rest/util/ActivitiWebScript.java b/modules/activiti-rest/src/main/java/org/activiti/rest/util/ActivitiWebScript.java index 1bd3eb86..19d94ade 100644 --- a/modules/activiti-rest/src/main/java/org/activiti/rest/util/ActivitiWebScript.java +++ b/modules/activiti-rest/src/main/java/org/activiti/rest/util/ActivitiWebScript.java @@ -1,464 +1,470 @@ /* 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.activiti.rest.util; import org.activiti.*; import org.activiti.identity.Group; import org.activiti.impl.json.JSONObject; import org.activiti.rest.Config; import org.springframework.extensions.surf.util.Base64; import org.springframework.extensions.webscripts.*; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Helper class for all activiti webscripts. * * @author Erik Winlöf */ public class ActivitiWebScript extends DeclarativeWebScript { /** * The activiti config bean */ protected Config config; /** * Setter for the activiti config bean * * @param config The activiti config bean */ public void setConfig(Config config) { this.config = config; } /** * The entry point for the webscript. * * Will create a model and call the executeWebScript() so extending activiti webscripts may implement custom logic. * * @param req The webscript request * @param status The webscripts status * @param cache The webscript cache * @return The webscript template model */ @Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { // Prepare model with process engine info Map<String, Object> model = new HashMap<String, Object>(); // todo: set the current user context when the core api implements security checks // Let implementing webscript do something useful executeWebScript(req, status, cache, model); // Return model return model; } /** * Override this class to implement custom logic. * * @param req The webscript request * @param status The webscript * @param cache * @param model */ protected void executeWebScript(WebScriptRequest req, Status status, Cache cache, Map<String, Object> model){ // Override to make something useful } /** * Returns the process engine info. * * @return The process engine info */ protected ProcessEngineInfo getProcessEngineInfo() { return ProcessEngines.getProcessEngineInfo(config.getEngine()); } /** * Returns the process engine. * * @return The process engine */ protected ProcessEngine getProcessEngine() { return ProcessEngines.getProcessEngine(config.getEngine()); } /** * Returns the identity service. * * @return The identity service */ protected IdentityService getIdentityService() { return getProcessEngine().getIdentityService(); } /** * Returns the management service. * * @return The management service. */ protected ManagementService getManagementService() { return getProcessEngine().getManagementService(); } /** * Returns The process service. * * @return The process service */ protected ProcessService getProcessService() { return getProcessEngine().getProcessService(); } /** * Returns the task service. * * @return The task service */ protected TaskService getTaskService() { return getProcessEngine().getTaskService(); } /** * Returns the webscript request body in an abstracted form so multiple formats may be * implemented seamlessly in the future. * * @param req The webscript request * @return The webscript requests body */ protected ActivitiWebScriptBody getBody(WebScriptRequest req) { try { return new ActivitiWebScriptBody(req); } catch (IOException e) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Can't read body"); } } /** * Gets a path parameter value and throws an exception if its not present. * * @param req The webscript request * @param param The name of the path parameter * @return The value of the path parameter * @throws WebScriptException if parameter isn't present */ protected String getMandatoryPathParameter(WebScriptRequest req, String param) { return checkString(req.getServiceMatch().getTemplateVars().get(param), param, true); } /** * Gets a path parameter value. * * @param req The webscript request * @param param The name of the path parameter * @return The path parameter value or null if not present */ protected String getPathParameter(WebScriptRequest req, String param) { return checkString(req.getServiceMatch().getTemplateVars().get(param), param, false); } /** * Gets an int parameter value. * * @param req The webscript request * @param param The name of the int parameter * @return The int parameter value or Integer.MIN_VALUE if not present */ protected int getInt(WebScriptRequest req, String param) { String value = getString(req, param); return value != null ? Integer.parseInt(value) : Integer.MIN_VALUE; } /** * Gets a mandatory int parameter and throws an exception if its not present. * * @param req The webscript request * @param param The name of the path parameter * @return The int parameter value * @throws WebScriptException if parameter isn't present */ protected int getMandatoryInt(WebScriptRequest req, String param) { String value = getMandatoryString(req, param); return value != null ? Integer.parseInt(value) : Integer.MIN_VALUE; } /** * Gets an int parameter value * * @param req The webscript request * @param param The name of the int parameter * @param defaultValue THe value to return if the parameter isn't present * @return The int parameter value of defaultValue if the parameter isn't present */ protected int getInt(WebScriptRequest req, String param, int defaultValue) { String value = getString(req, param); return value != null ? Integer.parseInt(value) : defaultValue; } /** * Gets the string parameter value. * * @param req The webscript request * @param param The name of the string parameter * @return The string parameter value or null if the parameter isn't present */ protected String getString(WebScriptRequest req, String param) { return checkString(req.getParameter(param), param, false); } /** * Gets a mandatory string parameter value of throws an exception if the parameter isn't present. * * @param req The webscript request * @param param The name of the string parameter value * @return The string parameter value * @throws WebScriptException if the parameter isn't present */ protected String getMandatoryString(WebScriptRequest req, String param) { return checkString(req.getParameter(param), param, true); } /** * Gets the string parameter value. * * @param req The webscript request. * @param param The name of the string parameter value * @param defaultValue The value to return if the parameter isn't present * @return The value of the string parameter or the default value if parameter isn't present */ protected String getString(WebScriptRequest req, String param, String defaultValue) { String value = checkString(req.getParameter(param), param, false); return value != null ? value : defaultValue; } /** * Gets a string parameter from the body * @param body The activiti webscript request body * @param param The name of the string parameter * @return The value of the string body parameter * @throws WebScriptException if string body parameter isn't present */ protected String getMandatoryString(ActivitiWebScriptBody body, String param) { return checkString(body.getString(param), param, true); } /** * Gets a parameter as Map * @param body The activiti webscript request body * @return The value of the string body parameter * @throws WebScriptException if string body parameter isn't present */ protected Map<String, Object> getFormVariables(ActivitiWebScriptBody body) { return body.getFormVariables(); } /** * Throws and exception if the parameter value is null or empty and mandatory is true * * @param value The parameter value to test * @param param The name of the parameter * @param mandatory If true the value wil be tested * @return The parameter value * @throws WebScriptException if mandatory is true and value is null or empty */ protected String checkString(String value, String param, boolean mandatory) { if (value != null && value.isEmpty()) { value = null; } return (String) checkObject(value, param, mandatory); } /** * Throws and exception if the parameter value is null or empty and mandatory is true * * @param value The parameter value to test * @param param The name of the parameter * @param mandatory If true the value wil be tested * @return The parameter value * @throws WebScriptException if mandatory is true and value is null or empty */ protected Object checkObject(Object value, String param, boolean mandatory) { if (value == null) { if (mandatory) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + param + "' is missing"); } else { return null; } } return value; } /** * Returns the username for the current user. * * @param req The webscript request * @return THe username of the current user */ protected String getCurrentUserId(WebScriptRequest req) { String authorization = req.getHeader("Authorization"); if (authorization != null) { String [] parts = authorization.split(" "); if (parts.length == 2) { return new String(Base64.decode(parts[1])).split(":")[0]; } } return null; } /** * Tests if user is in group. * * @param req The webscript request * @param userId The id of the user to test * @param groupId The if of the group to test the user against * @return true of user is in group */ protected boolean isUserInGroup(WebScriptRequest req, String userId, String groupId) { if (userId != null) { List<Group> groups = getIdentityService().findGroupsByUser(userId); for (Group group : groups) { if (config.getAdminGroupId().equals(group.getId())) { return true; } } } return false; } /** * Tests if user has manager role. * * @param req The webscript request. * @return true if the user has manager role */ protected boolean isManager(WebScriptRequest req) { return isUserInGroup(req, getCurrentUserId(req), config.getManagerGroupId()); } /** * Tests if user has admin role. * * @param req The webscript request * @return true if the user has admin role */ protected boolean isAdmin(WebScriptRequest req) { return isUserInGroup(req, getCurrentUserId(req), config.getAdminGroupId()); } /** * A class that wraps the webscripts request body so multiple formats * such as XML may be supported in the future. */ public class ActivitiWebScriptBody { /** * The json body */ private JSONObject jsonBody = null; /** * Constructor * * @param req The webscript request * @throws IOException if body of correct format cannot be created */ ActivitiWebScriptBody(WebScriptRequest req) throws IOException { jsonBody = new JSONObject(req.getContent().getContent()); } /** * Gets a body parameter string value. * * @param param The name of the parameter * @return The string value of the parameter */ String getString(String param) { return jsonBody.getString(param); } /** * Gets a body parameter string value. * * @param param The name of the parameter * @return The string value of the parameter */ int getInt(String param) { return jsonBody.getInt(param); } /** * Gets the body as a map. * * @return The body as a map */ Map<String, Object> getFormVariables() { Map<String, Object> map = new HashMap<String, Object>(); Iterator keys = jsonBody.keys(); String key, typeKey, type; String[] keyPair; Object value; while (keys.hasNext()) { key = (String) keys.next(); keyPair = key.split("_"); if (keyPair.length == 1) { typeKey = keyPair[0] + "_type"; if (jsonBody.has(typeKey)) { type = jsonBody.getString(typeKey); if (type.equals("Integer")) { value = jsonBody.getInt(key); } else if (type.equals("Boolean")) { value = jsonBody.getBoolean(key); } + else if (type.equals("Date")) { + value = jsonBody.getString(key); + } + else if (type.equals("User")) { + value = jsonBody.getString(key); + } else { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + keyPair[0] + "' is of unknown type '" + type + "'"); } } else { value = jsonBody.get(key); } map.put(key, value); } else if (keyPair.length == 2) { if (keyPair[1].equals("required")) { if (!jsonBody.has(keyPair[0]) || jsonBody.get(keyPair[0]) == null) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + keyPair[0] + "' has no value"); } } } } return map; } } }
true
true
Map<String, Object> getFormVariables() { Map<String, Object> map = new HashMap<String, Object>(); Iterator keys = jsonBody.keys(); String key, typeKey, type; String[] keyPair; Object value; while (keys.hasNext()) { key = (String) keys.next(); keyPair = key.split("_"); if (keyPair.length == 1) { typeKey = keyPair[0] + "_type"; if (jsonBody.has(typeKey)) { type = jsonBody.getString(typeKey); if (type.equals("Integer")) { value = jsonBody.getInt(key); } else if (type.equals("Boolean")) { value = jsonBody.getBoolean(key); } else { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + keyPair[0] + "' is of unknown type '" + type + "'"); } } else { value = jsonBody.get(key); } map.put(key, value); } else if (keyPair.length == 2) { if (keyPair[1].equals("required")) { if (!jsonBody.has(keyPair[0]) || jsonBody.get(keyPair[0]) == null) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + keyPair[0] + "' has no value"); } } } } return map; }
Map<String, Object> getFormVariables() { Map<String, Object> map = new HashMap<String, Object>(); Iterator keys = jsonBody.keys(); String key, typeKey, type; String[] keyPair; Object value; while (keys.hasNext()) { key = (String) keys.next(); keyPair = key.split("_"); if (keyPair.length == 1) { typeKey = keyPair[0] + "_type"; if (jsonBody.has(typeKey)) { type = jsonBody.getString(typeKey); if (type.equals("Integer")) { value = jsonBody.getInt(key); } else if (type.equals("Boolean")) { value = jsonBody.getBoolean(key); } else if (type.equals("Date")) { value = jsonBody.getString(key); } else if (type.equals("User")) { value = jsonBody.getString(key); } else { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + keyPair[0] + "' is of unknown type '" + type + "'"); } } else { value = jsonBody.get(key); } map.put(key, value); } else if (keyPair.length == 2) { if (keyPair[1].equals("required")) { if (!jsonBody.has(keyPair[0]) || jsonBody.get(keyPair[0]) == null) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter '" + keyPair[0] + "' has no value"); } } } } return map; }
diff --git a/src/ttree/pipin/i2c/MD25Test.java b/src/ttree/pipin/i2c/MD25Test.java index c1663c5..b85b3d3 100644 --- a/src/ttree/pipin/i2c/MD25Test.java +++ b/src/ttree/pipin/i2c/MD25Test.java @@ -1,57 +1,57 @@ package ttree.pipin.i2c; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; /** * Test MD 25 device attached to I2C bus * * @author michael */ public class MD25Test { /** * Main for Motor Test * @throws IOException */ public static void main(String[] args) throws IOException { // RPi external I2C bus final I2CBus piExtBus = I2CFactory.getInstance(1); // Default address for MD25 board final I2CDevice md25 = piExtBus.getDevice(0x58); int revision = md25.read(MD25.REG_REVISION); System.out.print("MD25 revision " + revision + " "); md25.write(MD25.REG_MODE, (byte)1); int mode = md25.read(MD25.REG_MODE); System.out.println("in mode " + mode); // open up standard input final BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); for (;;) { System.out.print("MD25 motor 1 speed (-128..127) : "); final String input = sin.readLine(); if (input.isEmpty() == true) break; try { final int value = Integer.parseInt(input); - if (value < -127 || value > 128) { + if (value < -128 || value > 127) { throw new NumberFormatException(); } md25.write(MD25.REG_SPEED1, (byte)value); } catch (NumberFormatException e) { System.err.println("Expecting -128..127\n"); } } } }
true
true
public static void main(String[] args) throws IOException { // RPi external I2C bus final I2CBus piExtBus = I2CFactory.getInstance(1); // Default address for MD25 board final I2CDevice md25 = piExtBus.getDevice(0x58); int revision = md25.read(MD25.REG_REVISION); System.out.print("MD25 revision " + revision + " "); md25.write(MD25.REG_MODE, (byte)1); int mode = md25.read(MD25.REG_MODE); System.out.println("in mode " + mode); // open up standard input final BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); for (;;) { System.out.print("MD25 motor 1 speed (-128..127) : "); final String input = sin.readLine(); if (input.isEmpty() == true) break; try { final int value = Integer.parseInt(input); if (value < -127 || value > 128) { throw new NumberFormatException(); } md25.write(MD25.REG_SPEED1, (byte)value); } catch (NumberFormatException e) { System.err.println("Expecting -128..127\n"); } } }
public static void main(String[] args) throws IOException { // RPi external I2C bus final I2CBus piExtBus = I2CFactory.getInstance(1); // Default address for MD25 board final I2CDevice md25 = piExtBus.getDevice(0x58); int revision = md25.read(MD25.REG_REVISION); System.out.print("MD25 revision " + revision + " "); md25.write(MD25.REG_MODE, (byte)1); int mode = md25.read(MD25.REG_MODE); System.out.println("in mode " + mode); // open up standard input final BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); for (;;) { System.out.print("MD25 motor 1 speed (-128..127) : "); final String input = sin.readLine(); if (input.isEmpty() == true) break; try { final int value = Integer.parseInt(input); if (value < -128 || value > 127) { throw new NumberFormatException(); } md25.write(MD25.REG_SPEED1, (byte)value); } catch (NumberFormatException e) { System.err.println("Expecting -128..127\n"); } } }
diff --git a/src/main/java/cz/muni/fi/xklinec/whiteboxAES/generator/AEShelper.java b/src/main/java/cz/muni/fi/xklinec/whiteboxAES/generator/AEShelper.java index a39c74c..0c036c7 100644 --- a/src/main/java/cz/muni/fi/xklinec/whiteboxAES/generator/AEShelper.java +++ b/src/main/java/cz/muni/fi/xklinec/whiteboxAES/generator/AEShelper.java @@ -1,566 +1,566 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cz.muni.fi.xklinec.whiteboxAES.generator; import cz.muni.fi.xklinec.whiteboxAES.AES; import cz.muni.fi.xklinec.whiteboxAES.State; import org.bouncycastle.pqc.math.linearalgebra.GF2mField; /** * * @author ph4r05 */ public class AEShelper { public static final int POLYNOMIAL = 0x11B; public static final int GENERATOR = 0x03; public static final int DEGREE = 8; public static final int AES_FIELD_SIZE = 1<<8; public static final int AES_TESTVECTORS = 4; public static final byte testVect128_key[] = new byte[]{ (byte)0x2b, (byte)0x7e, (byte)0x15, (byte)0x16, (byte)0x28, (byte)0xae, (byte)0xd2, (byte)0xa6, (byte)0xab, (byte)0xf7, (byte)0x15, (byte)0x88, (byte)0x09, (byte)0xcf, (byte)0x4f, (byte)0x3c }; public static final byte testVect128_plain[][] = new byte[][]{ {(byte)0x32, (byte)0x43, (byte)0xf6, (byte)0xa8, (byte)0x88, (byte)0x5a, (byte)0x30, (byte)0x8d, (byte)0x31, (byte)0x31, (byte)0x98, (byte)0xa2, (byte)0xe0, (byte)0x37, (byte)0x07, (byte)0x34}, {(byte)0x6b, (byte)0xc1, (byte)0xbe, (byte)0xe2, (byte)0x2e, (byte)0x40, (byte)0x9f, (byte)0x96, (byte)0xe9, (byte)0x3d, (byte)0x7e, (byte)0x11, (byte)0x73, (byte)0x93, (byte)0x17, (byte)0x2a}, {(byte)0xae, (byte)0x2d, (byte)0x8a, (byte)0x57, (byte)0x1e, (byte)0x03, (byte)0xac, (byte)0x9c, (byte)0x9e, (byte)0xb7, (byte)0x6f, (byte)0xac, (byte)0x45, (byte)0xaf, (byte)0x8e, (byte)0x51}, {(byte)0x30, (byte)0xc8, (byte)0x1c, (byte)0x46, (byte)0xa3, (byte)0x5c, (byte)0xe4, (byte)0x11, (byte)0xe5, (byte)0xfb, (byte)0xc1, (byte)0x19, (byte)0x1a, (byte)0x0a, (byte)0x52, (byte)0xef}, {(byte)0xf6, (byte)0x9f, (byte)0x24, (byte)0x45, (byte)0xdf, (byte)0x4f, (byte)0x9b, (byte)0x17, (byte)0xad, (byte)0x2b, (byte)0x41, (byte)0x7b, (byte)0xe6, (byte)0x6c, (byte)0x37, (byte)0x10} }; public static final byte testVect128_cipher[][] = new byte[][]{ {(byte)0x39, (byte)0x25, (byte)0x84, (byte)0x1d, (byte)0x02, (byte)0xdc, (byte)0x09, (byte)0xfb, (byte)0xdc, (byte)0x11, (byte)0x85, (byte)0x97, (byte)0x19, (byte)0x6a, (byte)0x0b, (byte)0x32}, {(byte)0x3a, (byte)0xd7, (byte)0x7b, (byte)0xb4, (byte)0x0d, (byte)0x7a, (byte)0x36, (byte)0x60, (byte)0xa8, (byte)0x9e, (byte)0xca, (byte)0xf3, (byte)0x24, (byte)0x66, (byte)0xef, (byte)0x97}, {(byte)0xf5, (byte)0xd3, (byte)0xd5, (byte)0x85, (byte)0x03, (byte)0xb9, (byte)0x69, (byte)0x9d, (byte)0xe7, (byte)0x85, (byte)0x89, (byte)0x5a, (byte)0x96, (byte)0xfd, (byte)0xba, (byte)0xaf}, {(byte)0x43, (byte)0xb1, (byte)0xcd, (byte)0x7f, (byte)0x59, (byte)0x8e, (byte)0xce, (byte)0x23, (byte)0x88, (byte)0x1b, (byte)0x00, (byte)0xe3, (byte)0xed, (byte)0x03, (byte)0x06, (byte)0x88}, {(byte)0x7b, (byte)0x0c, (byte)0x78, (byte)0x5e, (byte)0x27, (byte)0xe8, (byte)0xad, (byte)0x3f, (byte)0x82, (byte)0x23, (byte)0x20, (byte)0x71, (byte)0x04, (byte)0x72, (byte)0x5d, (byte)0xd4} }; public static final byte testVect256_key[] = new byte[]{ (byte)0x60, (byte)0x3d, (byte)0xeb, (byte)0x10, (byte)0x15, (byte)0xca, (byte)0x71, (byte)0xbe, (byte)0x2b, (byte)0x73, (byte)0xae, (byte)0xf0, (byte)0x85, (byte)0x7d, (byte)0x77, (byte)0x81, (byte)0x1f, (byte)0x35, (byte)0x2c, (byte)0x07, (byte)0x3b, (byte)0x61, (byte)0x08, (byte)0xd7, (byte)0x2d, (byte)0x98, (byte)0x10, (byte)0xa3, (byte)0x09, (byte)0x14, (byte)0xdf, (byte)0xf4 }; public static final byte testVect256_plain[][] = new byte[][]{ {(byte)0x6b, (byte)0xc1, (byte)0xbe, (byte)0xe2, (byte)0x2e, (byte)0x40, (byte)0x9f, (byte)0x96, (byte)0xe9, (byte)0x3d, (byte)0x7e, (byte)0x11, (byte)0x73, (byte)0x93, (byte)0x17, (byte)0x2a}, {(byte)0xae, (byte)0x2d, (byte)0x8a, (byte)0x57, (byte)0x1e, (byte)0x03, (byte)0xac, (byte)0x9c, (byte)0x9e, (byte)0xb7, (byte)0x6f, (byte)0xac, (byte)0x45, (byte)0xaf, (byte)0x8e, (byte)0x51}, {(byte)0x30, (byte)0xc8, (byte)0x1c, (byte)0x46, (byte)0xa3, (byte)0x5c, (byte)0xe4, (byte)0x11, (byte)0xe5, (byte)0xfb, (byte)0xc1, (byte)0x19, (byte)0x1a, (byte)0x0a, (byte)0x52, (byte)0xef}, {(byte)0xf6, (byte)0x9f, (byte)0x24, (byte)0x45, (byte)0xdf, (byte)0x4f, (byte)0x9b, (byte)0x17, (byte)0xad, (byte)0x2b, (byte)0x41, (byte)0x7b, (byte)0xe6, (byte)0x6c, (byte)0x37, (byte)0x10} }; public static final byte testVect256_cipher[][] = new byte[][]{ {(byte)0xf3, (byte)0xee, (byte)0xd1, (byte)0xbd, (byte)0xb5, (byte)0xd2, (byte)0xa0, (byte)0x3c, (byte)0x06, (byte)0x4b, (byte)0x5a, (byte)0x7e, (byte)0x3d, (byte)0xb1, (byte)0x81, (byte)0xf8}, {(byte)0x59, (byte)0x1c, (byte)0xcb, (byte)0x10, (byte)0xd4, (byte)0x10, (byte)0xed, (byte)0x26, (byte)0xdc, (byte)0x5b, (byte)0xa7, (byte)0x4a, (byte)0x31, (byte)0x36, (byte)0x28, (byte)0x70}, {(byte)0xb6, (byte)0xed, (byte)0x21, (byte)0xb9, (byte)0x9c, (byte)0xa6, (byte)0xf4, (byte)0xf9, (byte)0xf1, (byte)0x53, (byte)0xe7, (byte)0xb1, (byte)0xbe, (byte)0xaf, (byte)0xed, (byte)0x1d}, {(byte)0x23, (byte)0x30, (byte)0x4b, (byte)0x7a, (byte)0x39, (byte)0xf9, (byte)0xf3, (byte)0xff, (byte)0x06, (byte)0x7d, (byte)0x8d, (byte)0x8f, (byte)0x9e, (byte)0x24, (byte)0xec, (byte)0xc7} }; protected GF2mField field; protected int g[] = new int[AES_FIELD_SIZE]; protected int gInv[] = new int[AES_FIELD_SIZE]; protected int sbox[] = new int[AES_FIELD_SIZE]; protected int sboxAffine[] = new int[AES_FIELD_SIZE]; protected int sboxAffineInv[] = new int[AES_FIELD_SIZE]; protected int mixColModulus[] = new int[5]; protected int mixColMultiply[] = new int[4]; protected int mixColMultiplyInv[] = new int[4]; public static final int RCNUM = 16; protected int RC[] = new int[RCNUM]; protected GF2mMatrixEx mixColMat; protected GF2mMatrixEx mixColInvMat; /** * Initializes AES constans (S-box, T-box, RC for key schedule). * * @param encrypt */ public void build(boolean encrypt){ field = new GF2mField(8, POLYNOMIAL); System.out.println(field); int i,c,cur = 1; gInv[0] = -1; for(i=0; i<AES_FIELD_SIZE; i++){ g[i] = cur; gInv[cur] = i; cur = field.mult(cur, GENERATOR); } // 2. compute GF(256) element inverses in terms of generator exponent sbox[0] = -1; for(i=1; i<AES_FIELD_SIZE; i++){ sbox[i] = 255-i; } GF2MatrixEx tmpM = new GF2MatrixEx(8, 1); - GF2MatrixEx afM = getDefaultAffineMatrix(encrypt); - byte afC = getDefaultAffineConstByte(encrypt); + GF2MatrixEx afM = getDefaultAffineMatrix(true); + byte afC = getDefaultAffineConstByte(true); // Computing whole Sboxes with inversion + affine transformation in generic AES // Normal Sbox: S(x) = const + A(x^{-1}) // Sbox in Dual AES: G(x) = T(const) + T(A(T^{-1}(x^{-1}))) for(i=0; i<AES_FIELD_SIZE; i++){ int tmpRes; // i is now long representation, gInv transforms it to exponent power to obtain inverse. // Also getLong(g[gInv[i]]) == i int transValue = i==0 ? 0 : g[255-gInv[i]]; // tmpM = col vector of transValue NTLUtils.zero(tmpM); NTLUtils.putByteAsColVector(tmpM, (byte)transValue, 0, 0); // const + A(x^{-1}) GF2MatrixEx resMatrix = (GF2MatrixEx) afM.rightMultiply(tmpM); tmpRes = (byte) field.add(NTLUtils.colBinaryVectorToByte(resMatrix, 0, 0), afC) & 0xff; sboxAffine[i] = tmpRes; sboxAffineInv[tmpRes] = i; // Inversion, idea is the same, i is the long representation of element in GF, apply inverted affine transformation and take inverse // Ax^{-1} + c is input to this transformation // [A^{-1} * (A{x^-1} + c) + d]^{-1} is this transformation; // correctness: [A^{-1} * (Ax^-1 + c) + d]^{-1} = // [A^{-1}Ax^{-1} + A^{-1}c + d]^{-1} = // A^{-1}c = d // [x^{-1} + 0]^{-1} = // x // // Computation is useless, we have inversion of transformation right from transformation above // by simply swapping indexes. This is just for validation purposes to show, that it really works and how } // 6. MixColumn operations // modulus x^4 + 1 mixColModulus[0] = g[0]; mixColModulus[4] = g[0]; // 03 x^3 + 01 x^2 + 01 x + 02 mixColMultiply[0] = g[25]; mixColMultiply[1] = g[0]; mixColMultiply[2] = g[0]; mixColMultiply[3] = g[1]; // inverse polynomial mixColMultiplyInv[0] = g[223]; mixColMultiplyInv[1] = g[199]; mixColMultiplyInv[2] = g[238]; mixColMultiplyInv[3] = g[104]; // MixCols multiplication matrix based on mult polynomial - see Rijndael description of this. // Polynomials have coefficients in GF(256). mixColMat = new GF2mMatrixEx(field, 4, 4); mixColInvMat = new GF2mMatrixEx(field, 4, 4); for(i=0; i<4; i++){ for(c=0; c<4; c++){ mixColMat.set(i, c, mixColMultiply[(i+4-c) % 4]); mixColInvMat.set(i, c, mixColMultiplyInv[(i+4-c) % 4]); } } // Round key constant RC (for key schedule) obeys this reccurence: // RC[0] = 1 // RC[i] = '02' * RC[i-1] = x * RC[i-1] = x^{i-1} `mod` R(X) RC[0] = g[0]; for(i=1; i<RCNUM; i++){ RC[i] = field.mult(g[25], RC[i-1]); } } /** * Number of rounds of AES depends on key size */ public static int getNumberOfRounds(int keySize){ return keySize/4+6; } /** * Positive modulo 4 * @param a * @return */ public static int mod4(int a){ int c = a % 4; return c<0 ? c+4 : c; } /** * Returns default affine matrix transformation for S-box. * @param encrypt * @return */ public static GF2MatrixEx getDefaultAffineMatrix(boolean encrypt){ GF2MatrixEx r = new GF2MatrixEx(8, 8); if (encrypt){ NTLUtils.putByteAsRowVector(r, (byte)0x8F, 0, 0); NTLUtils.putByteAsRowVector(r, (byte)0xC7, 1, 0); NTLUtils.putByteAsRowVector(r, (byte)0xE3, 2, 0); NTLUtils.putByteAsRowVector(r, (byte)0xF1, 3, 0); NTLUtils.putByteAsRowVector(r, (byte)0xF8, 4, 0); NTLUtils.putByteAsRowVector(r, (byte)0x7C, 5, 0); NTLUtils.putByteAsRowVector(r, (byte)0x3E, 6, 0); NTLUtils.putByteAsRowVector(r, (byte)0x1F, 7, 0); } else { NTLUtils.putByteAsRowVector(r, (byte)0x25, 0, 0); NTLUtils.putByteAsRowVector(r, (byte)0x92, 1, 0); NTLUtils.putByteAsRowVector(r, (byte)0x49, 2, 0); NTLUtils.putByteAsRowVector(r, (byte)0xA4, 3, 0); NTLUtils.putByteAsRowVector(r, (byte)0x52, 4, 0); NTLUtils.putByteAsRowVector(r, (byte)0x29, 5, 0); NTLUtils.putByteAsRowVector(r, (byte)0x94, 6, 0); NTLUtils.putByteAsRowVector(r, (byte)0x4A, 7, 0); } return r; } /** * Default affine constant for affine transformation for S-box. * @param encrypt * @return */ public static byte getDefaultAffineConstByte(boolean encrypt){ return encrypt ? (byte)0x63 : (byte)0x05; } /** * Returns affine constant for affine transformation for S-box as a col vector. * @param encrypt * @return */ public static GF2MatrixEx getDefaultAffineConst(boolean encrypt){ GF2MatrixEx r = new GF2MatrixEx(8,1); NTLUtils.putByteAsColVector(r, getDefaultAffineConstByte(encrypt), 0, 0); return r; } /** * Returns number of all round keys together. * * @param keySize * @return */ public static int getRoundKeysSize(int keySize){ return (4 * State.COLS * (getNumberOfRounds(keySize) + 1)); } /** * AES key schedule. * * @param roundKeys * @param key * @param keySize */ public byte[] keySchedule(byte[] key, int size, boolean debug){ /* current expanded keySize, in bytes */ int currentSize = 0; int rconIteration = 0; int i,j; int roundKeysSize = getRoundKeysSize(size); byte tmp; byte[] t = new byte[4]; //vec_GF2E t(INIT_SIZE, 4); byte[] roundKeys = new byte[roundKeysSize]; if (debug) { System.out.println("Expanded key size will be: " + roundKeysSize); } /* set the 16,24,32 bytes of the expanded key to the input key */ for (i = 0; i < size; i++) { roundKeys[i] = key[i]; } currentSize += size; while (currentSize < roundKeysSize) { if (debug) { System.out.println("CurrentSize: " + currentSize + "; expandedKeySize: " + roundKeysSize); } /* assign the previous 4 bytes to the temporary value t */ for (i = 0; i < 4; i++) { t[i] = roundKeys[(currentSize - 4) + i]; } /** * every 16,24,32 bytes we apply the core schedule to t and * increment rconIteration afterwards */ if (currentSize % size == 0) { //core(t, rconIteration++); /* rotate the 32-bit word 8 bits to the left */ tmp = t[0]; t[0] = t[1]; t[1] = t[2]; t[2] = t[3]; t[3] = tmp; /* apply S-Box substitution on all 4 parts of the 32-bit word */ for (j = 0; j < 4; ++j) { if (debug) { System.out.println("Sboxing key t[" + j + "]=" + t[j] + "=" + NTLUtils.chex(t[j]) + "; sboxval: " + NTLUtils.chex(sboxAffine[t[j]])); } // Apply S-box to t[j] t[j] = (byte) (sboxAffine[t[j] & 0xff] & 0xff); if (debug) { System.out.println(" after Sbox = " + t[j] + "=" + NTLUtils.chex(t[j])); } } /* XOR the output of the rcon operation with i to the first part (leftmost) only */ t[0] = (byte) ((byte) field.add(t[0], RC[rconIteration++]) & 0xff); if (debug) { System.out.println("; after XOR with RC[" + NTLUtils.chex(RC[rconIteration - 1]) + "] = " + t[0] + " = " + NTLUtils.chex(t[0])); } } /* For 256-bit keys, we add an extra sbox to the calculation */ if (size == 32 && ((currentSize % size) == 16)) { for (i = 0; i < 4; i++) { t[i] = (byte) (sboxAffine[t[i] & 0xff] & 0xff); } } /* We XOR t with the four-byte block 16,24,32 bytes before the new expanded key. * This becomes the next four bytes in the expanded key. */ for (i = 0; i < 4; i++) { roundKeys[currentSize] = (byte) ((byte) field.add(roundKeys[currentSize - size], t[i]) & 0xff); if (debug) { System.out.println("t[" + i + "] = " + NTLUtils.chex(t[i])); } currentSize++; } } return roundKeys; } /** * AES S-box. * @param e * @return */ public int ByteSub(int e){ return sboxAffine[AES.posIdx(e)]; } /** * AES S-box on whole state array. * @param state */ public void ByteSub(State state) { int i, j; for (i = 0; i < State.ROWS; i++) { for (j = 0; j < State.COLS; j++) { state.set((byte) sboxAffine[state.get(i, j)], i, j); } } } /** * AES S-box inverse. * @param e * @return */ public int ByteSubInv(int e){ return sboxAffineInv[AES.posIdx(e)]; } /** * AES S-box inverse on whole state array. * @param state */ public void ByteSubInv(State state){ int i, j; for (i = 0; i < State.ROWS; i++) { for (j = 0; j < State.COLS; j++) { state.set((byte) sboxAffineInv[state.get(i, j)], i, j); } } } /** * Adds specified round key to state array. * @param state * @param expandedKey * @param offset */ public void AddRoundKey(State state, byte[] expandedKey, int offset){ int i,j; for(i=0; i<State.ROWS; i++){ for(j=0; j<State.COLS; j++){ state.set((byte) field.add(state.get(i, j), expandedKey[offset + j*4+i]) , i, j); } } } /** * Shift Rows operation on state array, in-place. * @param state */ public void ShiftRows(State state) { // 1. row = no shift. 2. row = cyclic shift to the left by 1 // for AES with Nb=4, left shift for rows are: 1=1, 2=2, 3=3. byte tmp; int i, j; for (i = 1; i < State.ROWS; i++) { for (j = 1; j <= i; j++) { tmp = state.get(i, 0); state.set(state.get(i, 1), i, 0); state.set(state.get(i, 2), i, 1); state.set(state.get(i, 3), i, 2); state.set(tmp, i, 3); } } } /** * Inverse of Shift Rows operation on state array, in-place. * @param state */ public void ShiftRowsInv(State state) { // 1. row = no shift. 2. row = cyclic shift to the left by 1 // for AES with Nb=4, left shift for rows are: 1=1, 2=2, 3=3. byte tmp; int i, j; for (i = 1; i < State.ROWS; i++) { for (j = 1; j <= i; j++) { tmp = state.get(i, 3); state.set(state.get(i, 2), i, 3); state.set(state.get(i, 1), i, 2); state.set(state.get(i, 0), i, 1); state.set(tmp, i, 0); } } } /** * MixColumn operation on all columns on state matrix. * @param state */ public void MixColumn(State state) { int i, j; GF2mMatrixEx resMat; GF2mMatrixEx tmpMat = new GF2mMatrixEx(field, 4, 1); for (i = 0; i < State.COLS; i++) { // copy i-th column to 4*1 matrix - for multiplication for (j = 0; j < State.ROWS; j++) { tmpMat.set(j, 0, state.get(j, i)); } resMat = mixColMat.rightMultiply(tmpMat); // copy result back to i-th column for (j = 0; j < State.ROWS; j++) { state.set((byte) resMat.get(j, 0), j, i); } } } /** * Inverse MixColumn operation on all columns on state matrix. * @param state */ public void MixColumnInv(State state){ int i,j; GF2mMatrixEx resMat; GF2mMatrixEx tmpMat = new GF2mMatrixEx(field, 4, 1); for (i = 0; i < State.COLS; i++) { // copy i-th column to 4*1 matrix - for multiplication for (j = 0; j < State.ROWS; j++) { tmpMat.set(j, 0, state.get(j, i)); } resMat = mixColInvMat.rightMultiply(tmpMat); // copy result back to i-th column for (j = 0; j < State.ROWS; j++) { state.set((byte) resMat.get(j, 0), j, i); } } } public GF2mField getField() { return field; } public int[] getG() { return g; } public int[] getgInv() { return gInv; } public int[] getSbox() { return sbox; } public int[] getSboxAffine() { return sboxAffine; } public int[] getSboxAffineInv() { return sboxAffineInv; } public int[] getMixColModulus() { return mixColModulus; } public int[] getMixColMultiply() { return mixColMultiply; } public int[] getMixColMultiplyInv() { return mixColMultiplyInv; } public int[] getRC() { return RC; } public GF2mMatrixEx getMixColMat() { return mixColMat; } public GF2mMatrixEx getMixColInvMat() { return mixColInvMat; } }
true
true
public void build(boolean encrypt){ field = new GF2mField(8, POLYNOMIAL); System.out.println(field); int i,c,cur = 1; gInv[0] = -1; for(i=0; i<AES_FIELD_SIZE; i++){ g[i] = cur; gInv[cur] = i; cur = field.mult(cur, GENERATOR); } // 2. compute GF(256) element inverses in terms of generator exponent sbox[0] = -1; for(i=1; i<AES_FIELD_SIZE; i++){ sbox[i] = 255-i; } GF2MatrixEx tmpM = new GF2MatrixEx(8, 1); GF2MatrixEx afM = getDefaultAffineMatrix(encrypt); byte afC = getDefaultAffineConstByte(encrypt); // Computing whole Sboxes with inversion + affine transformation in generic AES // Normal Sbox: S(x) = const + A(x^{-1}) // Sbox in Dual AES: G(x) = T(const) + T(A(T^{-1}(x^{-1}))) for(i=0; i<AES_FIELD_SIZE; i++){ int tmpRes; // i is now long representation, gInv transforms it to exponent power to obtain inverse. // Also getLong(g[gInv[i]]) == i int transValue = i==0 ? 0 : g[255-gInv[i]]; // tmpM = col vector of transValue NTLUtils.zero(tmpM); NTLUtils.putByteAsColVector(tmpM, (byte)transValue, 0, 0); // const + A(x^{-1}) GF2MatrixEx resMatrix = (GF2MatrixEx) afM.rightMultiply(tmpM); tmpRes = (byte) field.add(NTLUtils.colBinaryVectorToByte(resMatrix, 0, 0), afC) & 0xff; sboxAffine[i] = tmpRes; sboxAffineInv[tmpRes] = i; // Inversion, idea is the same, i is the long representation of element in GF, apply inverted affine transformation and take inverse // Ax^{-1} + c is input to this transformation // [A^{-1} * (A{x^-1} + c) + d]^{-1} is this transformation; // correctness: [A^{-1} * (Ax^-1 + c) + d]^{-1} = // [A^{-1}Ax^{-1} + A^{-1}c + d]^{-1} = // A^{-1}c = d // [x^{-1} + 0]^{-1} = // x // // Computation is useless, we have inversion of transformation right from transformation above // by simply swapping indexes. This is just for validation purposes to show, that it really works and how } // 6. MixColumn operations // modulus x^4 + 1 mixColModulus[0] = g[0]; mixColModulus[4] = g[0]; // 03 x^3 + 01 x^2 + 01 x + 02 mixColMultiply[0] = g[25]; mixColMultiply[1] = g[0]; mixColMultiply[2] = g[0]; mixColMultiply[3] = g[1]; // inverse polynomial mixColMultiplyInv[0] = g[223]; mixColMultiplyInv[1] = g[199]; mixColMultiplyInv[2] = g[238]; mixColMultiplyInv[3] = g[104]; // MixCols multiplication matrix based on mult polynomial - see Rijndael description of this. // Polynomials have coefficients in GF(256). mixColMat = new GF2mMatrixEx(field, 4, 4); mixColInvMat = new GF2mMatrixEx(field, 4, 4); for(i=0; i<4; i++){ for(c=0; c<4; c++){ mixColMat.set(i, c, mixColMultiply[(i+4-c) % 4]); mixColInvMat.set(i, c, mixColMultiplyInv[(i+4-c) % 4]); } } // Round key constant RC (for key schedule) obeys this reccurence: // RC[0] = 1 // RC[i] = '02' * RC[i-1] = x * RC[i-1] = x^{i-1} `mod` R(X) RC[0] = g[0]; for(i=1; i<RCNUM; i++){ RC[i] = field.mult(g[25], RC[i-1]); } }
public void build(boolean encrypt){ field = new GF2mField(8, POLYNOMIAL); System.out.println(field); int i,c,cur = 1; gInv[0] = -1; for(i=0; i<AES_FIELD_SIZE; i++){ g[i] = cur; gInv[cur] = i; cur = field.mult(cur, GENERATOR); } // 2. compute GF(256) element inverses in terms of generator exponent sbox[0] = -1; for(i=1; i<AES_FIELD_SIZE; i++){ sbox[i] = 255-i; } GF2MatrixEx tmpM = new GF2MatrixEx(8, 1); GF2MatrixEx afM = getDefaultAffineMatrix(true); byte afC = getDefaultAffineConstByte(true); // Computing whole Sboxes with inversion + affine transformation in generic AES // Normal Sbox: S(x) = const + A(x^{-1}) // Sbox in Dual AES: G(x) = T(const) + T(A(T^{-1}(x^{-1}))) for(i=0; i<AES_FIELD_SIZE; i++){ int tmpRes; // i is now long representation, gInv transforms it to exponent power to obtain inverse. // Also getLong(g[gInv[i]]) == i int transValue = i==0 ? 0 : g[255-gInv[i]]; // tmpM = col vector of transValue NTLUtils.zero(tmpM); NTLUtils.putByteAsColVector(tmpM, (byte)transValue, 0, 0); // const + A(x^{-1}) GF2MatrixEx resMatrix = (GF2MatrixEx) afM.rightMultiply(tmpM); tmpRes = (byte) field.add(NTLUtils.colBinaryVectorToByte(resMatrix, 0, 0), afC) & 0xff; sboxAffine[i] = tmpRes; sboxAffineInv[tmpRes] = i; // Inversion, idea is the same, i is the long representation of element in GF, apply inverted affine transformation and take inverse // Ax^{-1} + c is input to this transformation // [A^{-1} * (A{x^-1} + c) + d]^{-1} is this transformation; // correctness: [A^{-1} * (Ax^-1 + c) + d]^{-1} = // [A^{-1}Ax^{-1} + A^{-1}c + d]^{-1} = // A^{-1}c = d // [x^{-1} + 0]^{-1} = // x // // Computation is useless, we have inversion of transformation right from transformation above // by simply swapping indexes. This is just for validation purposes to show, that it really works and how } // 6. MixColumn operations // modulus x^4 + 1 mixColModulus[0] = g[0]; mixColModulus[4] = g[0]; // 03 x^3 + 01 x^2 + 01 x + 02 mixColMultiply[0] = g[25]; mixColMultiply[1] = g[0]; mixColMultiply[2] = g[0]; mixColMultiply[3] = g[1]; // inverse polynomial mixColMultiplyInv[0] = g[223]; mixColMultiplyInv[1] = g[199]; mixColMultiplyInv[2] = g[238]; mixColMultiplyInv[3] = g[104]; // MixCols multiplication matrix based on mult polynomial - see Rijndael description of this. // Polynomials have coefficients in GF(256). mixColMat = new GF2mMatrixEx(field, 4, 4); mixColInvMat = new GF2mMatrixEx(field, 4, 4); for(i=0; i<4; i++){ for(c=0; c<4; c++){ mixColMat.set(i, c, mixColMultiply[(i+4-c) % 4]); mixColInvMat.set(i, c, mixColMultiplyInv[(i+4-c) % 4]); } } // Round key constant RC (for key schedule) obeys this reccurence: // RC[0] = 1 // RC[i] = '02' * RC[i-1] = x * RC[i-1] = x^{i-1} `mod` R(X) RC[0] = g[0]; for(i=1; i<RCNUM; i++){ RC[i] = field.mult(g[25], RC[i-1]); } }
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java b/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java index 9fd47e6b..8026b9d6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java @@ -1,83 +1,83 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Essentials; import com.earth2me.essentials.InventoryWorkaround; import com.earth2me.essentials.ItemDb; import com.earth2me.essentials.User; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.craftbukkit.inventory.CraftInventory; import org.bukkit.inventory.ItemStack; public class Commandunlimited extends EssentialsCommand { public Commandunlimited() { super("unlimited"); } @Override public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { if (args.length < 1) { user.sendMessage("§cUsage: /" + commandLabel + " [list|item] <player>"); return; } User target = user; if (args.length > 1 && user.isAuthorized("essentials.unlimited.others")) { target = getPlayer(server, args, 1); } if (args[0].equalsIgnoreCase("list")) { StringBuilder sb = new StringBuilder(); sb.append("Unlimited items: "); boolean first = true; for (Integer integer : target.getUnlimited()) { if (!first) { sb.append(", "); first = false; } String matname = Material.getMaterial(integer).toString().toLowerCase().replace("_", ""); sb.append(matname); } user.sendMessage(sb.toString()); return; } ItemStack stack = ItemDb.get(args[0], 1); String itemname = stack.getType().toString().toLowerCase().replace("_", ""); - if (!user.isAuthorized("essentials.unlimited.item-add") && + if (!user.isAuthorized("essentials.unlimited.item-all") && !user.isAuthorized("essentials.unlimited.item-"+itemname) && !user.isAuthorized("essentials.unlimited.item-"+stack.getTypeId()) && !((stack.getType() == Material.WATER_BUCKET || stack.getType() == Material.LAVA_BUCKET) && user.isAuthorized("essentials.unlimited.item-bucket"))) { user.sendMessage(ChatColor.RED + "No permission for unlimited item "+itemname+"."); return; } if (target.hasUnlimited(stack)) { if (user != target) { user.sendMessage("§7Disable unlimited placing of " + itemname + " for " + user.getDisplayName() + "."); } target.sendMessage("§7Disable unlimited placing of " + itemname + " for " + user.getDisplayName() + "."); target.setUnlimited(stack, false); return; } user.charge(this); if (user != target) { user.sendMessage("§7Giving unlimited amount of " + itemname + " to " + user.getDisplayName() + "."); } target.sendMessage("§7Giving unlimited amount of " + itemname + " to " + user.getDisplayName() + "."); if (!InventoryWorkaround.containsItem((CraftInventory)target.getInventory(), true, stack)) { target.getInventory().addItem(stack); } target.setUnlimited(stack, true); } }
true
true
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { if (args.length < 1) { user.sendMessage("§cUsage: /" + commandLabel + " [list|item] <player>"); return; } User target = user; if (args.length > 1 && user.isAuthorized("essentials.unlimited.others")) { target = getPlayer(server, args, 1); } if (args[0].equalsIgnoreCase("list")) { StringBuilder sb = new StringBuilder(); sb.append("Unlimited items: "); boolean first = true; for (Integer integer : target.getUnlimited()) { if (!first) { sb.append(", "); first = false; } String matname = Material.getMaterial(integer).toString().toLowerCase().replace("_", ""); sb.append(matname); } user.sendMessage(sb.toString()); return; } ItemStack stack = ItemDb.get(args[0], 1); String itemname = stack.getType().toString().toLowerCase().replace("_", ""); if (!user.isAuthorized("essentials.unlimited.item-add") && !user.isAuthorized("essentials.unlimited.item-"+itemname) && !user.isAuthorized("essentials.unlimited.item-"+stack.getTypeId()) && !((stack.getType() == Material.WATER_BUCKET || stack.getType() == Material.LAVA_BUCKET) && user.isAuthorized("essentials.unlimited.item-bucket"))) { user.sendMessage(ChatColor.RED + "No permission for unlimited item "+itemname+"."); return; } if (target.hasUnlimited(stack)) { if (user != target) { user.sendMessage("§7Disable unlimited placing of " + itemname + " for " + user.getDisplayName() + "."); } target.sendMessage("§7Disable unlimited placing of " + itemname + " for " + user.getDisplayName() + "."); target.setUnlimited(stack, false); return; } user.charge(this); if (user != target) { user.sendMessage("§7Giving unlimited amount of " + itemname + " to " + user.getDisplayName() + "."); } target.sendMessage("§7Giving unlimited amount of " + itemname + " to " + user.getDisplayName() + "."); if (!InventoryWorkaround.containsItem((CraftInventory)target.getInventory(), true, stack)) { target.getInventory().addItem(stack); } target.setUnlimited(stack, true); }
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { if (args.length < 1) { user.sendMessage("§cUsage: /" + commandLabel + " [list|item] <player>"); return; } User target = user; if (args.length > 1 && user.isAuthorized("essentials.unlimited.others")) { target = getPlayer(server, args, 1); } if (args[0].equalsIgnoreCase("list")) { StringBuilder sb = new StringBuilder(); sb.append("Unlimited items: "); boolean first = true; for (Integer integer : target.getUnlimited()) { if (!first) { sb.append(", "); first = false; } String matname = Material.getMaterial(integer).toString().toLowerCase().replace("_", ""); sb.append(matname); } user.sendMessage(sb.toString()); return; } ItemStack stack = ItemDb.get(args[0], 1); String itemname = stack.getType().toString().toLowerCase().replace("_", ""); if (!user.isAuthorized("essentials.unlimited.item-all") && !user.isAuthorized("essentials.unlimited.item-"+itemname) && !user.isAuthorized("essentials.unlimited.item-"+stack.getTypeId()) && !((stack.getType() == Material.WATER_BUCKET || stack.getType() == Material.LAVA_BUCKET) && user.isAuthorized("essentials.unlimited.item-bucket"))) { user.sendMessage(ChatColor.RED + "No permission for unlimited item "+itemname+"."); return; } if (target.hasUnlimited(stack)) { if (user != target) { user.sendMessage("§7Disable unlimited placing of " + itemname + " for " + user.getDisplayName() + "."); } target.sendMessage("§7Disable unlimited placing of " + itemname + " for " + user.getDisplayName() + "."); target.setUnlimited(stack, false); return; } user.charge(this); if (user != target) { user.sendMessage("§7Giving unlimited amount of " + itemname + " to " + user.getDisplayName() + "."); } target.sendMessage("§7Giving unlimited amount of " + itemname + " to " + user.getDisplayName() + "."); if (!InventoryWorkaround.containsItem((CraftInventory)target.getInventory(), true, stack)) { target.getInventory().addItem(stack); } target.setUnlimited(stack, true); }
diff --git a/src/java/org/apache/nutch/crawl/CrawlDbReducer.java b/src/java/org/apache/nutch/crawl/CrawlDbReducer.java index cbfaf38b..13d8b749 100644 --- a/src/java/org/apache/nutch/crawl/CrawlDbReducer.java +++ b/src/java/org/apache/nutch/crawl/CrawlDbReducer.java @@ -1,129 +1,130 @@ /** * Copyright 2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nutch.crawl; import java.util.Iterator; import java.io.IOException; import org.apache.hadoop.io.*; import org.apache.hadoop.mapred.*; /** Merge new page entries with existing entries. */ public class CrawlDbReducer implements Reducer { private int retryMax; private CrawlDatum result = new CrawlDatum(); public void configure(JobConf job) { retryMax = job.getInt("db.fetch.retry.max", 3); } public void close() {} public void reduce(WritableComparable key, Iterator values, OutputCollector output, Reporter reporter) throws IOException { CrawlDatum highest = null; CrawlDatum old = null; byte[] signature = null; float scoreIncrement = 0.0f; while (values.hasNext()) { CrawlDatum datum = (CrawlDatum)values.next(); if (highest == null || datum.getStatus() > highest.getStatus()) { highest = datum; // find highest status } switch (datum.getStatus()) { // find old entry, if any case CrawlDatum.STATUS_DB_UNFETCHED: case CrawlDatum.STATUS_DB_FETCHED: case CrawlDatum.STATUS_DB_GONE: old = datum; break; case CrawlDatum.STATUS_LINKED: scoreIncrement += datum.getScore(); break; case CrawlDatum.STATUS_SIGNATURE: signature = datum.getSignature(); } } // initialize with the latest version result.set(highest); if (old != null) { // copy metadata from old, if exists if (old.getMetaData() != null) { + if (result.getMetaData() == null) result.setMetaData(new MapWritable()); result.getMetaData().putAll(old.getMetaData()); // overlay with new, if any if (highest.getMetaData() != null) result.getMetaData().putAll(highest.getMetaData()); } // set the most recent valid value of modifiedTime if (old.getModifiedTime() > 0 && highest.getModifiedTime() == 0) { result.setModifiedTime(old.getModifiedTime()); } } switch (highest.getStatus()) { // determine new status case CrawlDatum.STATUS_DB_UNFETCHED: // no new entry case CrawlDatum.STATUS_DB_FETCHED: case CrawlDatum.STATUS_DB_GONE: result.set(old); // use old break; case CrawlDatum.STATUS_LINKED: // highest was link if (old != null) { // if old exists result.set(old); // use it } else { result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED); result.setScore(1.0f); } break; case CrawlDatum.STATUS_FETCH_SUCCESS: // succesful fetch if (highest.getSignature() == null) result.setSignature(signature); result.setStatus(CrawlDatum.STATUS_DB_FETCHED); result.setNextFetchTime(); break; case CrawlDatum.STATUS_FETCH_RETRY: // temporary failure if (old != null) result.setSignature(old.getSignature()); // use old signature if (highest.getRetriesSinceFetch() < retryMax) { result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED); } else { result.setStatus(CrawlDatum.STATUS_DB_GONE); } break; case CrawlDatum.STATUS_FETCH_GONE: // permanent failure if (old != null) result.setSignature(old.getSignature()); // use old signature result.setStatus(CrawlDatum.STATUS_DB_GONE); break; default: throw new RuntimeException("Unknown status: "+highest.getStatus()); } result.setScore(result.getScore() + scoreIncrement); output.collect(key, result); } }
true
true
public void reduce(WritableComparable key, Iterator values, OutputCollector output, Reporter reporter) throws IOException { CrawlDatum highest = null; CrawlDatum old = null; byte[] signature = null; float scoreIncrement = 0.0f; while (values.hasNext()) { CrawlDatum datum = (CrawlDatum)values.next(); if (highest == null || datum.getStatus() > highest.getStatus()) { highest = datum; // find highest status } switch (datum.getStatus()) { // find old entry, if any case CrawlDatum.STATUS_DB_UNFETCHED: case CrawlDatum.STATUS_DB_FETCHED: case CrawlDatum.STATUS_DB_GONE: old = datum; break; case CrawlDatum.STATUS_LINKED: scoreIncrement += datum.getScore(); break; case CrawlDatum.STATUS_SIGNATURE: signature = datum.getSignature(); } } // initialize with the latest version result.set(highest); if (old != null) { // copy metadata from old, if exists if (old.getMetaData() != null) { result.getMetaData().putAll(old.getMetaData()); // overlay with new, if any if (highest.getMetaData() != null) result.getMetaData().putAll(highest.getMetaData()); } // set the most recent valid value of modifiedTime if (old.getModifiedTime() > 0 && highest.getModifiedTime() == 0) { result.setModifiedTime(old.getModifiedTime()); } } switch (highest.getStatus()) { // determine new status case CrawlDatum.STATUS_DB_UNFETCHED: // no new entry case CrawlDatum.STATUS_DB_FETCHED: case CrawlDatum.STATUS_DB_GONE: result.set(old); // use old break; case CrawlDatum.STATUS_LINKED: // highest was link if (old != null) { // if old exists result.set(old); // use it } else { result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED); result.setScore(1.0f); } break; case CrawlDatum.STATUS_FETCH_SUCCESS: // succesful fetch if (highest.getSignature() == null) result.setSignature(signature); result.setStatus(CrawlDatum.STATUS_DB_FETCHED); result.setNextFetchTime(); break; case CrawlDatum.STATUS_FETCH_RETRY: // temporary failure if (old != null) result.setSignature(old.getSignature()); // use old signature if (highest.getRetriesSinceFetch() < retryMax) { result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED); } else { result.setStatus(CrawlDatum.STATUS_DB_GONE); } break; case CrawlDatum.STATUS_FETCH_GONE: // permanent failure if (old != null) result.setSignature(old.getSignature()); // use old signature result.setStatus(CrawlDatum.STATUS_DB_GONE); break; default: throw new RuntimeException("Unknown status: "+highest.getStatus()); } result.setScore(result.getScore() + scoreIncrement); output.collect(key, result); }
public void reduce(WritableComparable key, Iterator values, OutputCollector output, Reporter reporter) throws IOException { CrawlDatum highest = null; CrawlDatum old = null; byte[] signature = null; float scoreIncrement = 0.0f; while (values.hasNext()) { CrawlDatum datum = (CrawlDatum)values.next(); if (highest == null || datum.getStatus() > highest.getStatus()) { highest = datum; // find highest status } switch (datum.getStatus()) { // find old entry, if any case CrawlDatum.STATUS_DB_UNFETCHED: case CrawlDatum.STATUS_DB_FETCHED: case CrawlDatum.STATUS_DB_GONE: old = datum; break; case CrawlDatum.STATUS_LINKED: scoreIncrement += datum.getScore(); break; case CrawlDatum.STATUS_SIGNATURE: signature = datum.getSignature(); } } // initialize with the latest version result.set(highest); if (old != null) { // copy metadata from old, if exists if (old.getMetaData() != null) { if (result.getMetaData() == null) result.setMetaData(new MapWritable()); result.getMetaData().putAll(old.getMetaData()); // overlay with new, if any if (highest.getMetaData() != null) result.getMetaData().putAll(highest.getMetaData()); } // set the most recent valid value of modifiedTime if (old.getModifiedTime() > 0 && highest.getModifiedTime() == 0) { result.setModifiedTime(old.getModifiedTime()); } } switch (highest.getStatus()) { // determine new status case CrawlDatum.STATUS_DB_UNFETCHED: // no new entry case CrawlDatum.STATUS_DB_FETCHED: case CrawlDatum.STATUS_DB_GONE: result.set(old); // use old break; case CrawlDatum.STATUS_LINKED: // highest was link if (old != null) { // if old exists result.set(old); // use it } else { result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED); result.setScore(1.0f); } break; case CrawlDatum.STATUS_FETCH_SUCCESS: // succesful fetch if (highest.getSignature() == null) result.setSignature(signature); result.setStatus(CrawlDatum.STATUS_DB_FETCHED); result.setNextFetchTime(); break; case CrawlDatum.STATUS_FETCH_RETRY: // temporary failure if (old != null) result.setSignature(old.getSignature()); // use old signature if (highest.getRetriesSinceFetch() < retryMax) { result.setStatus(CrawlDatum.STATUS_DB_UNFETCHED); } else { result.setStatus(CrawlDatum.STATUS_DB_GONE); } break; case CrawlDatum.STATUS_FETCH_GONE: // permanent failure if (old != null) result.setSignature(old.getSignature()); // use old signature result.setStatus(CrawlDatum.STATUS_DB_GONE); break; default: throw new RuntimeException("Unknown status: "+highest.getStatus()); } result.setScore(result.getScore() + scoreIncrement); output.collect(key, result); }
diff --git a/src/com/modcrafting/diablodrops/listeners/TomeListener.java b/src/com/modcrafting/diablodrops/listeners/TomeListener.java index e19390d..d15b0ef 100644 --- a/src/com/modcrafting/diablodrops/listeners/TomeListener.java +++ b/src/com/modcrafting/diablodrops/listeners/TomeListener.java @@ -1,131 +1,129 @@ package com.modcrafting.diablodrops.listeners; import java.util.Iterator; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.Event.Result; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; import com.modcrafting.diablodrops.DiabloDrops; import com.modcrafting.diablodrops.events.IdentifyItemEvent; import com.modcrafting.diablodrops.items.IdentifyTome; public class TomeListener implements Listener { private final DiabloDrops plugin; public TomeListener(final DiabloDrops plugin) { this.plugin = plugin; } public ChatColor findColor(final String s) { char[] c = s.toCharArray(); for (int i = 0; i < c.length; i++) if ((c[i] == new Character((char) 167)) && ((i + 1) < c.length)) return ChatColor.getByChar(c[i + 1]); return null; } @EventHandler public void onCraftItem(final CraftItemEvent e) { ItemStack item = e.getCurrentItem(); if (item.getType().equals(Material.WRITTEN_BOOK)) { if (e.isShiftClick()) { e.setCancelled(true); } e.setCurrentItem(new IdentifyTome()); } } @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.LOWEST) public void onRightClick(final PlayerInteractEvent e) { if ((e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction() .equals(Action.RIGHT_CLICK_BLOCK)) && e.getPlayer().getItemInHand().getType() .equals(Material.WRITTEN_BOOK)) { ItemStack inh = e.getPlayer().getItemInHand(); BookMeta b = (BookMeta) inh.getItemMeta(); if (b == null) return; - if (b.getTitle().contains("Identity Tome")|| - b.getTitle().contains("Diablo Tome")) + if (b.getTitle().contains("Identity Tome") && b.getAuthor().endsWith("AAAA")) { Player p = e.getPlayer(); PlayerInventory pi = p.getInventory(); p.updateInventory(); Iterator<ItemStack> itis = pi.iterator(); while (itis.hasNext()) { ItemStack tool = itis.next(); if ((tool == null) || !plugin.dropsAPI.canBeItem(tool.getType())) { continue; } ItemMeta meta = tool.getItemMeta(); String name = meta.getDisplayName(); - if(!b.getTitle().contains("Diablo Tome")) if ((!ChatColor.getLastColors(name).equalsIgnoreCase(ChatColor.MAGIC.name()) && !ChatColor.getLastColors(name).equalsIgnoreCase( ChatColor.MAGIC.toString())) && (!name.contains(ChatColor.MAGIC.name()) && !name .contains(ChatColor.MAGIC.toString()))) { continue; } IdentifyItemEvent iie = new IdentifyItemEvent(tool); plugin.getServer().getPluginManager().callEvent(iie); if (iie.isCancelled()) { p.sendMessage(ChatColor.RED + "You are unable to identify right now."); p.closeInventory(); e.setUseItemInHand(Result.DENY); e.setCancelled(true); return; } pi.setItemInHand(null); ItemStack item = plugin.dropsAPI.getItem(tool); while ((item == null) || item.getItemMeta().getDisplayName().contains( ChatColor.MAGIC.toString())) { item = plugin.dropsAPI.getItem(tool); } pi.removeItem(tool); pi.addItem(item); p.sendMessage(ChatColor.GREEN + "You have identified an item!"); p.updateInventory(); e.setUseItemInHand(Result.DENY); e.setCancelled(true); p.closeInventory(); return; } p.sendMessage(ChatColor.RED + "You have no items to identify."); p.closeInventory(); e.setUseItemInHand(Result.DENY); e.setCancelled(true); return; } } } }
false
true
public void onRightClick(final PlayerInteractEvent e) { if ((e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction() .equals(Action.RIGHT_CLICK_BLOCK)) && e.getPlayer().getItemInHand().getType() .equals(Material.WRITTEN_BOOK)) { ItemStack inh = e.getPlayer().getItemInHand(); BookMeta b = (BookMeta) inh.getItemMeta(); if (b == null) return; if (b.getTitle().contains("Identity Tome")|| b.getTitle().contains("Diablo Tome")) { Player p = e.getPlayer(); PlayerInventory pi = p.getInventory(); p.updateInventory(); Iterator<ItemStack> itis = pi.iterator(); while (itis.hasNext()) { ItemStack tool = itis.next(); if ((tool == null) || !plugin.dropsAPI.canBeItem(tool.getType())) { continue; } ItemMeta meta = tool.getItemMeta(); String name = meta.getDisplayName(); if(!b.getTitle().contains("Diablo Tome")) if ((!ChatColor.getLastColors(name).equalsIgnoreCase(ChatColor.MAGIC.name()) && !ChatColor.getLastColors(name).equalsIgnoreCase( ChatColor.MAGIC.toString())) && (!name.contains(ChatColor.MAGIC.name()) && !name .contains(ChatColor.MAGIC.toString()))) { continue; } IdentifyItemEvent iie = new IdentifyItemEvent(tool); plugin.getServer().getPluginManager().callEvent(iie); if (iie.isCancelled()) { p.sendMessage(ChatColor.RED + "You are unable to identify right now."); p.closeInventory(); e.setUseItemInHand(Result.DENY); e.setCancelled(true); return; } pi.setItemInHand(null); ItemStack item = plugin.dropsAPI.getItem(tool); while ((item == null) || item.getItemMeta().getDisplayName().contains( ChatColor.MAGIC.toString())) { item = plugin.dropsAPI.getItem(tool); } pi.removeItem(tool); pi.addItem(item); p.sendMessage(ChatColor.GREEN + "You have identified an item!"); p.updateInventory(); e.setUseItemInHand(Result.DENY); e.setCancelled(true); p.closeInventory(); return; } p.sendMessage(ChatColor.RED + "You have no items to identify."); p.closeInventory(); e.setUseItemInHand(Result.DENY); e.setCancelled(true); return; } } }
public void onRightClick(final PlayerInteractEvent e) { if ((e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction() .equals(Action.RIGHT_CLICK_BLOCK)) && e.getPlayer().getItemInHand().getType() .equals(Material.WRITTEN_BOOK)) { ItemStack inh = e.getPlayer().getItemInHand(); BookMeta b = (BookMeta) inh.getItemMeta(); if (b == null) return; if (b.getTitle().contains("Identity Tome") && b.getAuthor().endsWith("AAAA")) { Player p = e.getPlayer(); PlayerInventory pi = p.getInventory(); p.updateInventory(); Iterator<ItemStack> itis = pi.iterator(); while (itis.hasNext()) { ItemStack tool = itis.next(); if ((tool == null) || !plugin.dropsAPI.canBeItem(tool.getType())) { continue; } ItemMeta meta = tool.getItemMeta(); String name = meta.getDisplayName(); if ((!ChatColor.getLastColors(name).equalsIgnoreCase(ChatColor.MAGIC.name()) && !ChatColor.getLastColors(name).equalsIgnoreCase( ChatColor.MAGIC.toString())) && (!name.contains(ChatColor.MAGIC.name()) && !name .contains(ChatColor.MAGIC.toString()))) { continue; } IdentifyItemEvent iie = new IdentifyItemEvent(tool); plugin.getServer().getPluginManager().callEvent(iie); if (iie.isCancelled()) { p.sendMessage(ChatColor.RED + "You are unable to identify right now."); p.closeInventory(); e.setUseItemInHand(Result.DENY); e.setCancelled(true); return; } pi.setItemInHand(null); ItemStack item = plugin.dropsAPI.getItem(tool); while ((item == null) || item.getItemMeta().getDisplayName().contains( ChatColor.MAGIC.toString())) { item = plugin.dropsAPI.getItem(tool); } pi.removeItem(tool); pi.addItem(item); p.sendMessage(ChatColor.GREEN + "You have identified an item!"); p.updateInventory(); e.setUseItemInHand(Result.DENY); e.setCancelled(true); p.closeInventory(); return; } p.sendMessage(ChatColor.RED + "You have no items to identify."); p.closeInventory(); e.setUseItemInHand(Result.DENY); e.setCancelled(true); return; } } }
diff --git a/eol-globi-data-tool/src/test/java/org/eol/globi/service/EOLServiceIT.java b/eol-globi-data-tool/src/test/java/org/eol/globi/service/EOLServiceIT.java index 4b2d4ba9..6ec47a5b 100644 --- a/eol-globi-data-tool/src/test/java/org/eol/globi/service/EOLServiceIT.java +++ b/eol-globi-data-tool/src/test/java/org/eol/globi/service/EOLServiceIT.java @@ -1,82 +1,82 @@ package org.eol.globi.service; import org.junit.Test; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class EOLServiceIT { @Test public void lookupByName() throws TaxonPropertyLookupServiceException { assertThat(lookupPageIdByScientificName("Homo sapiens"), is("EOL:327955")); assertThat(lookupPageIdByScientificName("Puccinia caricina var. ribesii-pendulae"), is(nullValue())); assertThat(lookupPageIdByScientificName("Hesperocharis paranensis"), is("EOL:176594")); // TODO need to find a way to include only pages that have at least one external taxonomy assertThat(lookupPageIdByScientificName("Dead roots"), is("EOL:19665069")); assertThat(lookupPageIdByScientificName("Prunella (Bot)"), is("EOL:70879")); assertThat(lookupPageIdByScientificName("Prunella (Bird)"), is("EOL:77930")); assertThat(lookupPageIdByScientificName("Pseudobaeospora dichroa"), is("EOL:1001400")); } /** Regarding multiple symbol in taxonomic names: * * From: xxx Subject: RE: question about taxonomy name normalization Date: April 12, 2013 4:24:11 AM PDT To: xxx And another thing! The "x" in hybrids, whether "Genus species1 x species2" or "Genus xHybridName" is strictly not the letter "x". It's the multiply symbol: HTML: &times; http://www.fileformat.info/info/unicode/char/d7/index.htm But of course you'll equally receive it as "x". Malcolm * @throws TaxonPropertyLookupServiceException */ @Test public void multiplySymbolNotSupportedByEOL() throws TaxonPropertyLookupServiceException { assertThat(lookupPageIdByScientificName("Salix cinerea x phylicifolia"), is("EOL:584272")); assertThat(lookupPageIdByScientificName("Salix cinerea \u00D7 phylicifolia"), is(nullValue())); assertThat(lookupPageIdByScientificName("Salix cinerea × phylicifolia"), is(nullValue())); } @Test public void lookupByNameYieldsMoreThanOneMatches() throws TaxonPropertyLookupServiceException { // this species has two matches http://eol.org/27383107 and http://eol.org/209714, first is picked - assertThat(lookupPageIdByScientificName("Copadichromis insularis"), is("EOL:27383107")); + assertThat(lookupPageIdByScientificName("Copadichromis insularis"), is("EOL:209714")); // below matches both http://eol.org/4443282 and http://eol.org/310363, but first is picked assertThat(lookupPageIdByScientificName("Spilogale putorius gracilis"), is("EOL:4443282")); // etc assertThat(lookupPageIdByScientificName("Crocethia alba"), is("EOL:4373991")); assertThat(lookupPageIdByScientificName("Ecdyonuridae"), is("EOL:19663261")); assertThat(lookupPageIdByScientificName("Catasticta hegemon"), is("EOL:173526")); assertThat(lookupPageIdByScientificName("Theridion ovatum"), is("EOL:3180388")); assertThat(lookupPageIdByScientificName("Cambarus propinquus"), is("EOL:31345356")); assertThat(lookupPageIdByScientificName("Zoanthus flosmarinus"), is("EOL:13029466")); assertThat(lookupPageIdByScientificName("Vellidae"), is("EOL:644")); assertThat(lookupPageIdByScientificName("Mylothris spica"), is("EOL:180160")); assertThat(lookupPageIdByScientificName("Mylothris rueppellii"), is("EOL:180170")); } @Test public void lookupByNameYieldsNoMatches() throws TaxonPropertyLookupServiceException { assertThat(lookupPageIdByScientificName("Clio acicula"), is(nullValue())); assertThat(lookupPageIdByScientificName("Aegires oritzi"), is(nullValue())); } private String lookupPageIdByScientificName(String taxonName) throws TaxonPropertyLookupServiceException { return new EOLService().lookupLSIDByTaxonName(taxonName); } }
true
true
public void lookupByNameYieldsMoreThanOneMatches() throws TaxonPropertyLookupServiceException { // this species has two matches http://eol.org/27383107 and http://eol.org/209714, first is picked assertThat(lookupPageIdByScientificName("Copadichromis insularis"), is("EOL:27383107")); // below matches both http://eol.org/4443282 and http://eol.org/310363, but first is picked assertThat(lookupPageIdByScientificName("Spilogale putorius gracilis"), is("EOL:4443282")); // etc assertThat(lookupPageIdByScientificName("Crocethia alba"), is("EOL:4373991")); assertThat(lookupPageIdByScientificName("Ecdyonuridae"), is("EOL:19663261")); assertThat(lookupPageIdByScientificName("Catasticta hegemon"), is("EOL:173526")); assertThat(lookupPageIdByScientificName("Theridion ovatum"), is("EOL:3180388")); assertThat(lookupPageIdByScientificName("Cambarus propinquus"), is("EOL:31345356")); assertThat(lookupPageIdByScientificName("Zoanthus flosmarinus"), is("EOL:13029466")); assertThat(lookupPageIdByScientificName("Vellidae"), is("EOL:644")); assertThat(lookupPageIdByScientificName("Mylothris spica"), is("EOL:180160")); assertThat(lookupPageIdByScientificName("Mylothris rueppellii"), is("EOL:180170")); }
public void lookupByNameYieldsMoreThanOneMatches() throws TaxonPropertyLookupServiceException { // this species has two matches http://eol.org/27383107 and http://eol.org/209714, first is picked assertThat(lookupPageIdByScientificName("Copadichromis insularis"), is("EOL:209714")); // below matches both http://eol.org/4443282 and http://eol.org/310363, but first is picked assertThat(lookupPageIdByScientificName("Spilogale putorius gracilis"), is("EOL:4443282")); // etc assertThat(lookupPageIdByScientificName("Crocethia alba"), is("EOL:4373991")); assertThat(lookupPageIdByScientificName("Ecdyonuridae"), is("EOL:19663261")); assertThat(lookupPageIdByScientificName("Catasticta hegemon"), is("EOL:173526")); assertThat(lookupPageIdByScientificName("Theridion ovatum"), is("EOL:3180388")); assertThat(lookupPageIdByScientificName("Cambarus propinquus"), is("EOL:31345356")); assertThat(lookupPageIdByScientificName("Zoanthus flosmarinus"), is("EOL:13029466")); assertThat(lookupPageIdByScientificName("Vellidae"), is("EOL:644")); assertThat(lookupPageIdByScientificName("Mylothris spica"), is("EOL:180160")); assertThat(lookupPageIdByScientificName("Mylothris rueppellii"), is("EOL:180170")); }
diff --git a/ProjectRSC/Server/src/org/darkquest/gs/plugins/npcs/Boat.java b/ProjectRSC/Server/src/org/darkquest/gs/plugins/npcs/Boat.java index ce50e11..a55c30e 100644 --- a/ProjectRSC/Server/src/org/darkquest/gs/plugins/npcs/Boat.java +++ b/ProjectRSC/Server/src/org/darkquest/gs/plugins/npcs/Boat.java @@ -1,129 +1,129 @@ package org.darkquest.gs.plugins.npcs; import org.darkquest.gs.event.ShortEvent; import org.darkquest.gs.model.ChatMessage; import org.darkquest.gs.model.MenuHandler; import org.darkquest.gs.model.Npc; import org.darkquest.gs.model.Player; import org.darkquest.gs.model.Point; import org.darkquest.gs.plugins.listeners.action.TalkToNpcListener; import org.darkquest.gs.plugins.listeners.executive.TalkToNpcExecutiveListener; import org.darkquest.gs.tools.DataConversions; import org.darkquest.gs.world.World; public final class Boat implements TalkToNpcListener, TalkToNpcExecutiveListener { /** * World instance */ public static final World world = World.getWorld(); /* private static final String[] destinationNames = { "Karamja", "Brimhaven", "Port Sarim", "Ardougne", "Port Khazard", "Catherby", "Shilo" }; */ private static final String[] destinationNames = { "Yes please", "No thanks" }; private static final Point[] destinationCoords = { Point.location(324, 713), Point.location(467, 649), Point.location(268, 650), Point.location(538, 616), Point.location(541, 702), Point.location(439, 506), Point.location(471, 853) }; int[] boatMen = new int[]{ 166, 170, 171, 163, 317, 316, 280, 764 }; @Override public void onTalkToNpc(Player player, final Npc npc) { if(!DataConversions.inArray(boatMen, npc.getID())) { return; } if(npc.getID() == 163) { player.informOfNpcMessage(new ChatMessage(npc, "G'day sailor, would you like a free trip to Port Sarim", player)); player.setBusy(true); world.getDelayedEventHandler().add(new ShortEvent(player) { public void action() { owner.setBusy(false); owner.setMenuHandler(new MenuHandler(destinationNames) { public void handleReply(final int option, final String reply) { if(owner.isBusy() || option < 0 || option >= destinationNames.length) { npc.unblock(); return; } owner.informOfChatMessage(new ChatMessage(owner, reply, npc)); if(option == 1) { owner.setBusy(false); npc.unblock(); return; } owner.setBusy(true); world.getDelayedEventHandler().add(new ShortEvent(owner) { public void action() { owner.getActionSender().sendMessage("You board the ship"); world.getDelayedEventHandler().add(new ShortEvent(owner) { public void action() { Point p = Point.location(268, 650); // port sarim owner.teleport(p.getX(), p.getY(), false); owner.getActionSender().sendMessage("The ship arrives at Port Sarim"); owner.setBusy(false); npc.unblock(); } }); } }); } }); owner.getActionSender().sendMenu(destinationNames); } }); } else { player.informOfNpcMessage(new ChatMessage(npc, "G'day sailor, would you like a free trip to Karamja", player)); player.setBusy(true); world.getDelayedEventHandler().add(new ShortEvent(player) { public void action() { owner.setBusy(false); owner.setMenuHandler(new MenuHandler(destinationNames) { public void handleReply(final int option, final String reply) { if(owner.isBusy() || option < 0 || option >= destinationNames.length) { npc.unblock(); return; } owner.informOfChatMessage(new ChatMessage(owner, reply, npc)); if(option == 1) { owner.setBusy(false); npc.unblock(); return; } owner.setBusy(true); world.getDelayedEventHandler().add(new ShortEvent(owner) { public void action() { owner.getActionSender().sendMessage("You board the ship"); world.getDelayedEventHandler().add(new ShortEvent(owner) { public void action() { Point p = Point.location(324, 713); // karamja owner.teleport(p.getX(), p.getY(), false); - owner.getActionSender().sendMessage("The ship arrives at Karamja" + reply); + owner.getActionSender().sendMessage("The ship arrives at Karamja"); owner.setBusy(false); npc.unblock(); } }); } }); } }); owner.getActionSender().sendMenu(destinationNames); } }); } npc.blockedBy(player); } @Override public boolean blockTalkToNpc(Player p, Npc n) { return DataConversions.inArray(boatMen, n.getID()); } }
true
true
public void onTalkToNpc(Player player, final Npc npc) { if(!DataConversions.inArray(boatMen, npc.getID())) { return; } if(npc.getID() == 163) { player.informOfNpcMessage(new ChatMessage(npc, "G'day sailor, would you like a free trip to Port Sarim", player)); player.setBusy(true); world.getDelayedEventHandler().add(new ShortEvent(player) { public void action() { owner.setBusy(false); owner.setMenuHandler(new MenuHandler(destinationNames) { public void handleReply(final int option, final String reply) { if(owner.isBusy() || option < 0 || option >= destinationNames.length) { npc.unblock(); return; } owner.informOfChatMessage(new ChatMessage(owner, reply, npc)); if(option == 1) { owner.setBusy(false); npc.unblock(); return; } owner.setBusy(true); world.getDelayedEventHandler().add(new ShortEvent(owner) { public void action() { owner.getActionSender().sendMessage("You board the ship"); world.getDelayedEventHandler().add(new ShortEvent(owner) { public void action() { Point p = Point.location(268, 650); // port sarim owner.teleport(p.getX(), p.getY(), false); owner.getActionSender().sendMessage("The ship arrives at Port Sarim"); owner.setBusy(false); npc.unblock(); } }); } }); } }); owner.getActionSender().sendMenu(destinationNames); } }); } else { player.informOfNpcMessage(new ChatMessage(npc, "G'day sailor, would you like a free trip to Karamja", player)); player.setBusy(true); world.getDelayedEventHandler().add(new ShortEvent(player) { public void action() { owner.setBusy(false); owner.setMenuHandler(new MenuHandler(destinationNames) { public void handleReply(final int option, final String reply) { if(owner.isBusy() || option < 0 || option >= destinationNames.length) { npc.unblock(); return; } owner.informOfChatMessage(new ChatMessage(owner, reply, npc)); if(option == 1) { owner.setBusy(false); npc.unblock(); return; } owner.setBusy(true); world.getDelayedEventHandler().add(new ShortEvent(owner) { public void action() { owner.getActionSender().sendMessage("You board the ship"); world.getDelayedEventHandler().add(new ShortEvent(owner) { public void action() { Point p = Point.location(324, 713); // karamja owner.teleport(p.getX(), p.getY(), false); owner.getActionSender().sendMessage("The ship arrives at Karamja" + reply); owner.setBusy(false); npc.unblock(); } }); } }); } }); owner.getActionSender().sendMenu(destinationNames); } }); } npc.blockedBy(player); }
public void onTalkToNpc(Player player, final Npc npc) { if(!DataConversions.inArray(boatMen, npc.getID())) { return; } if(npc.getID() == 163) { player.informOfNpcMessage(new ChatMessage(npc, "G'day sailor, would you like a free trip to Port Sarim", player)); player.setBusy(true); world.getDelayedEventHandler().add(new ShortEvent(player) { public void action() { owner.setBusy(false); owner.setMenuHandler(new MenuHandler(destinationNames) { public void handleReply(final int option, final String reply) { if(owner.isBusy() || option < 0 || option >= destinationNames.length) { npc.unblock(); return; } owner.informOfChatMessage(new ChatMessage(owner, reply, npc)); if(option == 1) { owner.setBusy(false); npc.unblock(); return; } owner.setBusy(true); world.getDelayedEventHandler().add(new ShortEvent(owner) { public void action() { owner.getActionSender().sendMessage("You board the ship"); world.getDelayedEventHandler().add(new ShortEvent(owner) { public void action() { Point p = Point.location(268, 650); // port sarim owner.teleport(p.getX(), p.getY(), false); owner.getActionSender().sendMessage("The ship arrives at Port Sarim"); owner.setBusy(false); npc.unblock(); } }); } }); } }); owner.getActionSender().sendMenu(destinationNames); } }); } else { player.informOfNpcMessage(new ChatMessage(npc, "G'day sailor, would you like a free trip to Karamja", player)); player.setBusy(true); world.getDelayedEventHandler().add(new ShortEvent(player) { public void action() { owner.setBusy(false); owner.setMenuHandler(new MenuHandler(destinationNames) { public void handleReply(final int option, final String reply) { if(owner.isBusy() || option < 0 || option >= destinationNames.length) { npc.unblock(); return; } owner.informOfChatMessage(new ChatMessage(owner, reply, npc)); if(option == 1) { owner.setBusy(false); npc.unblock(); return; } owner.setBusy(true); world.getDelayedEventHandler().add(new ShortEvent(owner) { public void action() { owner.getActionSender().sendMessage("You board the ship"); world.getDelayedEventHandler().add(new ShortEvent(owner) { public void action() { Point p = Point.location(324, 713); // karamja owner.teleport(p.getX(), p.getY(), false); owner.getActionSender().sendMessage("The ship arrives at Karamja"); owner.setBusy(false); npc.unblock(); } }); } }); } }); owner.getActionSender().sendMenu(destinationNames); } }); } npc.blockedBy(player); }
diff --git a/src/Region.java b/src/Region.java index 6cbeed8..02b6467 100644 --- a/src/Region.java +++ b/src/Region.java @@ -1,25 +1,27 @@ import java.util.HashMap; class Region extends Zone{ private HashMap<String, Zone> zones; public Region(String name){ this(name,0); } public Region(String name,int populationSize){ super(name,populationSize); zones = new HashMap<String, Zone>(); } public void addZone(Zone z){ zones.put(z.getName(), z); } public Zone getZone(String zoneName){ - // add zone to the hashmap if it isn't found - if (!zones.containsKey(zoneName)) - zones.put(zoneName, new Zone(zoneName)); + // if a zone is not in the map, throw an exception + // we don't instantiate because we don't know the type + // of Zone (can be Region or Town) + if (!zones.containsKey(zoneName)) + throw new IllegalArgumentException(); return zones.get(zoneName); } }
true
true
public Zone getZone(String zoneName){ // add zone to the hashmap if it isn't found if (!zones.containsKey(zoneName)) zones.put(zoneName, new Zone(zoneName)); return zones.get(zoneName); }
public Zone getZone(String zoneName){ // if a zone is not in the map, throw an exception // we don't instantiate because we don't know the type // of Zone (can be Region or Town) if (!zones.containsKey(zoneName)) throw new IllegalArgumentException(); return zones.get(zoneName); }
diff --git a/src/main/java/org/subethamail/smtp/command/AuthCommand.java b/src/main/java/org/subethamail/smtp/command/AuthCommand.java index a191e4e..c278ee4 100644 --- a/src/main/java/org/subethamail/smtp/command/AuthCommand.java +++ b/src/main/java/org/subethamail/smtp/command/AuthCommand.java @@ -1,113 +1,113 @@ package org.subethamail.smtp.command; import java.io.IOException; import java.util.Locale; import org.subethamail.smtp.AuthenticationHandler; import org.subethamail.smtp.AuthenticationHandlerFactory; import org.subethamail.smtp.RejectException; import org.subethamail.smtp.io.CRLFTerminatedReader; import org.subethamail.smtp.server.BaseCommand; import org.subethamail.smtp.server.Session; /** * @author Marco Trevisan <mrctrevisan@yahoo.it> * @author Jeff Schnitzer * @author Scott Hernandez */ public class AuthCommand extends BaseCommand { public static final String VERB = "AUTH"; public static final String AUTH_CANCEL_COMMAND = "*"; /** Creates a new instance of AuthCommand */ public AuthCommand() { super( VERB, "Authentication service", VERB + " <mechanism> [initial-response] \n" + "\t mechanism = a string identifying a SASL authentication mechanism,\n" + "\t an optional base64-encoded response"); } /** */ @Override public void execute(String commandString, Session sess) throws IOException { if (sess.isAuthenticated()) { sess.sendResponse("503 Refusing any other AUTH command."); return; } AuthenticationHandlerFactory authFactory = sess.getServer().getAuthenticationHandlerFactory(); if (authFactory == null) { sess.sendResponse("502 Authentication not supported"); return; } AuthenticationHandler authHandler = authFactory.create(); String[] args = this.getArgs(commandString); // Let's check the command syntax if (args.length < 2) { sess.sendResponse("501 Syntax: " + VERB + " mechanism [initial-response]"); return; } // Let's check if we support the required authentication mechanism String mechanism = args[1]; if (!authFactory.getAuthenticationMechanisms().contains(mechanism.toUpperCase(Locale.ENGLISH))) { sess.sendResponse("504 The requested authentication mechanism is not supported"); return; } // OK, let's go trough the authentication process. try { // The authentication process may require a series of challenge-responses CRLFTerminatedReader reader = sess.getReader(); String response = authHandler.auth(commandString); if (response != null) { // challenge-response iteration sess.sendResponse(response); } while (response != null) { String clientInput = reader.readLine(); if (clientInput.trim().equals(AUTH_CANCEL_COMMAND)) { // RFC 2554 explicitly states this: sess.sendResponse("501 Authentication canceled by client."); return; } else { response = authHandler.auth(clientInput); if (response != null) { // challenge-response iteration sess.sendResponse(response); } } } sess.sendResponse("235 Authentication successful."); sess.setAuthenticationHandler(authHandler); } catch (RejectException authFailed) { - sess.sendResponse("535 Authentication failure."); + sess.sendResponse(authFailed.getErrorResponse()); } } }
true
true
public void execute(String commandString, Session sess) throws IOException { if (sess.isAuthenticated()) { sess.sendResponse("503 Refusing any other AUTH command."); return; } AuthenticationHandlerFactory authFactory = sess.getServer().getAuthenticationHandlerFactory(); if (authFactory == null) { sess.sendResponse("502 Authentication not supported"); return; } AuthenticationHandler authHandler = authFactory.create(); String[] args = this.getArgs(commandString); // Let's check the command syntax if (args.length < 2) { sess.sendResponse("501 Syntax: " + VERB + " mechanism [initial-response]"); return; } // Let's check if we support the required authentication mechanism String mechanism = args[1]; if (!authFactory.getAuthenticationMechanisms().contains(mechanism.toUpperCase(Locale.ENGLISH))) { sess.sendResponse("504 The requested authentication mechanism is not supported"); return; } // OK, let's go trough the authentication process. try { // The authentication process may require a series of challenge-responses CRLFTerminatedReader reader = sess.getReader(); String response = authHandler.auth(commandString); if (response != null) { // challenge-response iteration sess.sendResponse(response); } while (response != null) { String clientInput = reader.readLine(); if (clientInput.trim().equals(AUTH_CANCEL_COMMAND)) { // RFC 2554 explicitly states this: sess.sendResponse("501 Authentication canceled by client."); return; } else { response = authHandler.auth(clientInput); if (response != null) { // challenge-response iteration sess.sendResponse(response); } } } sess.sendResponse("235 Authentication successful."); sess.setAuthenticationHandler(authHandler); } catch (RejectException authFailed) { sess.sendResponse("535 Authentication failure."); } }
public void execute(String commandString, Session sess) throws IOException { if (sess.isAuthenticated()) { sess.sendResponse("503 Refusing any other AUTH command."); return; } AuthenticationHandlerFactory authFactory = sess.getServer().getAuthenticationHandlerFactory(); if (authFactory == null) { sess.sendResponse("502 Authentication not supported"); return; } AuthenticationHandler authHandler = authFactory.create(); String[] args = this.getArgs(commandString); // Let's check the command syntax if (args.length < 2) { sess.sendResponse("501 Syntax: " + VERB + " mechanism [initial-response]"); return; } // Let's check if we support the required authentication mechanism String mechanism = args[1]; if (!authFactory.getAuthenticationMechanisms().contains(mechanism.toUpperCase(Locale.ENGLISH))) { sess.sendResponse("504 The requested authentication mechanism is not supported"); return; } // OK, let's go trough the authentication process. try { // The authentication process may require a series of challenge-responses CRLFTerminatedReader reader = sess.getReader(); String response = authHandler.auth(commandString); if (response != null) { // challenge-response iteration sess.sendResponse(response); } while (response != null) { String clientInput = reader.readLine(); if (clientInput.trim().equals(AUTH_CANCEL_COMMAND)) { // RFC 2554 explicitly states this: sess.sendResponse("501 Authentication canceled by client."); return; } else { response = authHandler.auth(clientInput); if (response != null) { // challenge-response iteration sess.sendResponse(response); } } } sess.sendResponse("235 Authentication successful."); sess.setAuthenticationHandler(authHandler); } catch (RejectException authFailed) { sess.sendResponse(authFailed.getErrorResponse()); } }
diff --git a/src/java-common/org/xins/common/text/SimplePatternParser.java b/src/java-common/org/xins/common/text/SimplePatternParser.java index 9038c21e9..6dba66ed7 100644 --- a/src/java-common/org/xins/common/text/SimplePatternParser.java +++ b/src/java-common/org/xins/common/text/SimplePatternParser.java @@ -1,187 +1,198 @@ /* * $Id$ * * Copyright 2003-2005 Wanadoo Nederland B.V. * See the COPYRIGHT file for redistribution and use restrictions. */ package org.xins.common.text; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Pattern; import org.xins.common.MandatoryArgumentChecker; /** * Simple pattern parser. * * <h3>Format</h3> * * <p>A simple pattern is a text string that may contain letters, digits, * underscores, hyphens, dots and the wildcard characters <code>'*'</code> * (asterisk) and <code>'?'</code> (question mark). * * <p>The location of an asterisk indicates any number of characters is * allowed. The location of a question mark indicates exactly one character is * expected. * * <p>To allow matching of simple patterns, a simple pattern is first compiled * into a Perl 5 regular expression. Every asterisk is converted to * <code>".*"</code>, while every question mark is converted to * <code>"."</code>. * * <h3>Examples</h3> * * <p>Examples of conversions from a simple pattern to a Perl 4 regular * expression: * * <table> * <tr><th>Simple pattern</th><th>Perl 5 regex equivalent</th></tr> * <tr><td></td> <td></td> </tr> * <tr><td>*</td> <td>.*</td> </tr> * <tr><td>?</td> <td>.</td> </tr> * <tr><td>_Get*</td> <td>_Get.*</td> </tr> * <tr><td>_Get*i?n</td> <td>_Get.*i.n</td> </tr> * <tr><td>*on</td> <td>.*on</td> </tr> * </table> * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * @author Peter Troon (<a href="mailto:peter.troon@nl.wanadoo.com">peter.troon@nl.wanadoo.com</a>) * * @since XINS 1.0.0 */ public class SimplePatternParser extends Object { //------------------------------------------------------------------------- // Class fields //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Class functions //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Constructors //------------------------------------------------------------------------- /** * Creates a new <code>SimplePatternParser</code> object. */ public SimplePatternParser() { // empty } //------------------------------------------------------------------------- // Fields //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Methods //------------------------------------------------------------------------- /** * Converts the specified simple pattern to a Perl 5 regular expression. * * @param simplePattern * the simple pattern, cannot be <code>null</code>. * * @return * the Perl 5 regular expression, never <code>null</code>. * * @throws IllegalArgumentException * if <code>simplePattern == null</code>. * * @throws ParseException * if provided simplePattern is invalid or could not be parsed. */ public Perl5Pattern parseSimplePattern(String simplePattern) throws IllegalArgumentException, ParseException { MandatoryArgumentChecker.check("simplePattern", simplePattern); simplePattern = convertToPerl5RegularExpression(simplePattern); Perl5Pattern perl5pattern = null; Perl5Compiler perl5compiler = new Perl5Compiler(); boolean parseError = false; try { Pattern pattern = perl5compiler.compile(simplePattern); if (pattern instanceof Perl5Pattern) { perl5pattern = (Perl5Pattern) pattern; } else { parseError = true; } } catch ( MalformedPatternException mpe) { parseError = true; } if (parseError) { throw new ParseException("An error occurred while parsing the pattern '" + simplePattern + "'."); } return perl5pattern; } /** * Converts the pattern to a Perl 5 Regular Expression. This means that * every asterisk is replaced by a dot and an asterisk, every question mark * is replaced by a dot, an accent circunflex is prepended to the pattern * and a dollar sign is appended to the pattern. * * @param pattern * the pattern to be converted, may not be <code>null</code>. * * @return * the converted pattern, not <code>null</code>. * * @throws NullPointerException * if <code>pattern == null</code>. * * @throws ParseException * if provided simplePattern is invalid or could not be parsed. */ private String convertToPerl5RegularExpression(String pattern) throws NullPointerException, ParseException { char[] contents = pattern.toCharArray(); int size = contents.length; FastStringBuffer buffer = new FastStringBuffer(size * 2); char prevChar = (char) 0; for (int i= 0; i < size; i++) { char currChar = contents[i]; if (currChar >= 'a' && currChar <= 'z') { buffer.append(currChar); } else if (currChar >= 'A' && currChar <= 'Z') { buffer.append(currChar); } else if (currChar >= '0' && currChar <= '9') { buffer.append(currChar); } else if (currChar == '_') { buffer.append(currChar); } else if (currChar == '-') { buffer.append(currChar); } else if (currChar == '.') { buffer.append("\\."); } else if ((currChar == '*' || currChar == '?') && (prevChar == '*' || prevChar == '?')) { - throw new ParseException("The pattern \"" + pattern + "\" is invalid. It is not allowed to have two wildcard characters next to each other."); + final String DETAIL = "The pattern \"" + + pattern + + "\" is invalid since it contains two subsequent wildcard characters ('" + + prevChar + + "' and '" + + currChar + + "') at positions " + + (i - 1) + + " and " + + i + + '.'; + throw new ParseException(DETAIL); } else if (currChar == '*') { buffer.append(".*"); } else if (currChar == '?') { buffer.append('.'); } else if (currChar == ',') { buffer.append('|'); } else { throw new ParseException("The pattern \"" + pattern + "\" is invalid. The character '" + currChar + "' is not allowed."); } prevChar = currChar; } return buffer.toString(); } }
true
true
private String convertToPerl5RegularExpression(String pattern) throws NullPointerException, ParseException { char[] contents = pattern.toCharArray(); int size = contents.length; FastStringBuffer buffer = new FastStringBuffer(size * 2); char prevChar = (char) 0; for (int i= 0; i < size; i++) { char currChar = contents[i]; if (currChar >= 'a' && currChar <= 'z') { buffer.append(currChar); } else if (currChar >= 'A' && currChar <= 'Z') { buffer.append(currChar); } else if (currChar >= '0' && currChar <= '9') { buffer.append(currChar); } else if (currChar == '_') { buffer.append(currChar); } else if (currChar == '-') { buffer.append(currChar); } else if (currChar == '.') { buffer.append("\\."); } else if ((currChar == '*' || currChar == '?') && (prevChar == '*' || prevChar == '?')) { throw new ParseException("The pattern \"" + pattern + "\" is invalid. It is not allowed to have two wildcard characters next to each other."); } else if (currChar == '*') { buffer.append(".*"); } else if (currChar == '?') { buffer.append('.'); } else if (currChar == ',') { buffer.append('|'); } else { throw new ParseException("The pattern \"" + pattern + "\" is invalid. The character '" + currChar + "' is not allowed."); } prevChar = currChar; } return buffer.toString(); }
private String convertToPerl5RegularExpression(String pattern) throws NullPointerException, ParseException { char[] contents = pattern.toCharArray(); int size = contents.length; FastStringBuffer buffer = new FastStringBuffer(size * 2); char prevChar = (char) 0; for (int i= 0; i < size; i++) { char currChar = contents[i]; if (currChar >= 'a' && currChar <= 'z') { buffer.append(currChar); } else if (currChar >= 'A' && currChar <= 'Z') { buffer.append(currChar); } else if (currChar >= '0' && currChar <= '9') { buffer.append(currChar); } else if (currChar == '_') { buffer.append(currChar); } else if (currChar == '-') { buffer.append(currChar); } else if (currChar == '.') { buffer.append("\\."); } else if ((currChar == '*' || currChar == '?') && (prevChar == '*' || prevChar == '?')) { final String DETAIL = "The pattern \"" + pattern + "\" is invalid since it contains two subsequent wildcard characters ('" + prevChar + "' and '" + currChar + "') at positions " + (i - 1) + " and " + i + '.'; throw new ParseException(DETAIL); } else if (currChar == '*') { buffer.append(".*"); } else if (currChar == '?') { buffer.append('.'); } else if (currChar == ',') { buffer.append('|'); } else { throw new ParseException("The pattern \"" + pattern + "\" is invalid. The character '" + currChar + "' is not allowed."); } prevChar = currChar; } return buffer.toString(); }
diff --git a/src/cl/votainteligente/inspector/client/presenters/HomePresenter.java b/src/cl/votainteligente/inspector/client/presenters/HomePresenter.java index c83514e..25a4a6c 100644 --- a/src/cl/votainteligente/inspector/client/presenters/HomePresenter.java +++ b/src/cl/votainteligente/inspector/client/presenters/HomePresenter.java @@ -1,578 +1,578 @@ package cl.votainteligente.inspector.client.presenters; import cl.votainteligente.inspector.client.i18n.ApplicationMessages; import cl.votainteligente.inspector.client.services.BillServiceAsync; import cl.votainteligente.inspector.client.services.CategoryServiceAsync; import cl.votainteligente.inspector.client.services.ParlamentarianServiceAsync; import cl.votainteligente.inspector.model.Bill; import cl.votainteligente.inspector.model.Category; import cl.votainteligente.inspector.model.Parlamentarian; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyStandard; import com.gwtplatform.mvp.client.proxy.*; import com.google.gwt.cell.client.ActionCell; import com.google.gwt.cell.client.Cell; import com.google.gwt.cell.client.ImageCell; import com.google.gwt.event.shared.EventBus; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.cellview.client.*; import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.view.client.*; import com.google.inject.Inject; import java.util.Comparator; import java.util.List; public class HomePresenter extends Presenter<HomePresenter.MyView, HomePresenter.MyProxy> implements HomePresenterIface { public static final String PLACE = "home"; public interface MyView extends View { void setPresenter(HomePresenterIface presenter); void getParlamentarianSearch(); void getCategorySearch(); CellTable<Parlamentarian> getParlamentarianTable(); CellTable<Category> getCategoryTable(); CellTable<Bill> getBillTable(); void setParlamentarianDisplay(String parlamentarianName); void setCategoryDisplay(String categoryName); void setParlamentarianImage(String parlamentarianImage); } @ProxyStandard @NameToken(PLACE) public interface MyProxy extends ProxyPlace<HomePresenter> { } @Inject private ApplicationMessages applicationMessages; @Inject private PlaceManager placeManager; @Inject private ParlamentarianServiceAsync parlamentarianService; @Inject private CategoryServiceAsync categoryService; @Inject private BillServiceAsync billService; private AbstractDataProvider<Parlamentarian> parlamentarianData; private AbstractDataProvider<Category> categoryData; private AbstractDataProvider<Bill> billData; private Parlamentarian selectedParlamentarian; private Category selectedCategory; @Inject public HomePresenter(EventBus eventBus, MyView view, MyProxy proxy) { super(eventBus, view, proxy); } @Override protected void onBind() { getView().setPresenter(this); } @Override protected void onReset() { parlamentarianData = new ListDataProvider<Parlamentarian>(); categoryData = new ListDataProvider<Category>(); billData = new ListDataProvider<Bill>(); selectedParlamentarian = null; selectedCategory = null; initParlamentarianTable(); initCategoryTable(); initBillTable(); initDataLoad(); getView().setParlamentarianDisplay(applicationMessages.getGeneralParlamentarian()); getView().setParlamentarianImage("images/parlamentarian/large/avatar.png"); getView().setCategoryDisplay(applicationMessages.getGeneralCategory()); } @Override protected void revealInParent() { fireEvent(new RevealContentEvent(MainPresenter.TYPE_MAIN_CONTENT, this)); } @Override public void initDataLoad() { parlamentarianService.getAllParlamentarians(new AsyncCallback<List<Parlamentarian>>() { @Override public void onFailure(Throwable caught) { Window.alert(applicationMessages.getErrorParlamentarianList()); } @Override public void onSuccess(List<Parlamentarian> result) { if (result != null) { ListDataProvider<Parlamentarian> data = new ListDataProvider<Parlamentarian>(result); setParlamentarianData(data); } } }); categoryService.getAllCategories(new AsyncCallback<List<Category>>() { @Override public void onFailure(Throwable caught) { Window.alert(applicationMessages.getErrorCategoryList()); } @Override public void onSuccess(List<Category> result) { if (result != null) { ListDataProvider<Category> data = new ListDataProvider<Category>(result); setCategoryData(data); } } }); setBillData(new ListDataProvider<Bill>()); } @Override public void searchParlamentarian(String keyWord) { getView().setParlamentarianDisplay(applicationMessages.getGeneralParlamentarian()); getView().setParlamentarianImage("images/parlamentarian/large/avatar.png"); getView().setCategoryDisplay(applicationMessages.getGeneralCategory()); parlamentarianService.searchParlamentarian(keyWord, new AsyncCallback<List<Parlamentarian>>() { @Override public void onFailure(Throwable caught) { Window.alert(applicationMessages.getErrorParlamentarianSearch()); } @Override public void onSuccess(List<Parlamentarian> result) { if (result != null) { ListDataProvider<Parlamentarian> data = new ListDataProvider<Parlamentarian>(result); setParlamentarianData(data); searchCategory(result); } } }); } @Override public void searchParlamentarian(List<Category> categories) { parlamentarianService.searchParlamentarian(categories, new AsyncCallback<List<Parlamentarian>>() { @Override public void onFailure(Throwable caught) { Window.alert(applicationMessages.getErrorParlamentarianCategorySearch()); } @Override public void onSuccess(List<Parlamentarian> result) { if (result != null) { ListDataProvider<Parlamentarian> data = new ListDataProvider<Parlamentarian>(result); setParlamentarianData(data); } } }); } @Override public void searchCategory(String keyWord) { getView().setParlamentarianDisplay(applicationMessages.getGeneralParlamentarian()); getView().setParlamentarianImage("images/parlamentarian/large/avatar.png"); getView().setCategoryDisplay(applicationMessages.getGeneralCategory()); categoryService.searchCategory(keyWord, new AsyncCallback<List<Category>>() { @Override public void onFailure(Throwable caught) { Window.alert(applicationMessages.getErrorCategorySearch()); } @Override public void onSuccess(List<Category> result) { if (result != null) { ListDataProvider<Category> data = new ListDataProvider<Category>(result); setCategoryData(data); searchParlamentarian(result); } } }); } @Override public void searchCategory(List<Parlamentarian> parlamentarians) { categoryService.searchCategory(parlamentarians, new AsyncCallback<List<Category>>() { @Override public void onFailure(Throwable caught) { Window.alert(applicationMessages.getErrorCategoryParlamentarianSearch()); } @Override public void onSuccess(List<Category> result) { if (result != null) { ListDataProvider<Category> data = new ListDataProvider<Category>(result); setCategoryData(data); } } }); } @Override public void searchBill(Parlamentarian parlamentarian, Category category) { billService.searchBills(parlamentarian, category, new AsyncCallback<List<Bill>>() { @Override public void onFailure(Throwable caught) { Window.alert(applicationMessages.getErrorBillList()); } @Override public void onSuccess(List<Bill> result) { if (result != null) { ListDataProvider<Bill> data = new ListDataProvider<Bill>(result); setBillData(data); } } }); } @Override public AbstractDataProvider<Parlamentarian> getParlamentarianData() { return parlamentarianData; } @Override public void setParlamentarianData(AbstractDataProvider<Parlamentarian> data) { parlamentarianData = data; parlamentarianData.addDataDisplay(getView().getParlamentarianTable()); } @Override public AbstractDataProvider<Category> getCategoryData() { return categoryData; } @Override public void setCategoryData(AbstractDataProvider<Category> data) { categoryData = data; categoryData.addDataDisplay(getView().getCategoryTable()); } @Override public AbstractDataProvider<Bill> getBillData() { return billData; } @Override public void setBillData(AbstractDataProvider<Bill> data) { billData = data; billData.addDataDisplay(getView().getBillTable()); } @Override public void initParlamentarianTable() { while (getView().getParlamentarianTable().getColumnCount() > 0) { getView().getParlamentarianTable().removeColumn(0); } // Creates image column Column<Parlamentarian, String> imageColumn = new Column<Parlamentarian, String>(new ImageCell()){ @Override public String getValue(Parlamentarian parlamentarian) { return "images/parlamentarian/small/" + parlamentarian.getImage(); } }; // Adds name column to table getView().getParlamentarianTable().addColumn(imageColumn, ""); // Creates name column TextColumn<Parlamentarian> nameColumn = new TextColumn<Parlamentarian>() { @Override public String getValue(Parlamentarian parlamentarian) { return parlamentarian.getFirstName() + " " + parlamentarian.getLastName(); } }; // Sets sortable name column nameColumn.setSortable(true); ListHandler<Parlamentarian> nameSortHandler = new ListHandler<Parlamentarian>(((ListDataProvider<Parlamentarian>) parlamentarianData).getList()); getView().getParlamentarianTable().addColumnSortHandler(nameSortHandler); nameSortHandler.setComparator(nameColumn, new Comparator<Parlamentarian>() { public int compare(Parlamentarian o1, Parlamentarian o2) { return o1.getLastName().compareTo(o2.getLastName()); } }); // Adds name column to table getView().getParlamentarianTable().addColumn(nameColumn, applicationMessages.getGeneralParlamentarian()); // Creates party column TextColumn<Parlamentarian> partyColumn = new TextColumn<Parlamentarian>() { @Override public String getValue(Parlamentarian parlamentarian) { return parlamentarian.getParty().getName(); } }; // Sets sortable party column partyColumn.setSortable(true); ListHandler<Parlamentarian> partySortHandler = new ListHandler<Parlamentarian>(((ListDataProvider<Parlamentarian>) parlamentarianData).getList()); getView().getParlamentarianTable().addColumnSortHandler(partySortHandler); partySortHandler.setComparator(nameColumn, new Comparator<Parlamentarian>() { public int compare(Parlamentarian o1, Parlamentarian o2) { return o1.getParty().getName().compareTo(o2.getParty().getName()); } }); // Adds party column to table getView().getParlamentarianTable().addColumn(partyColumn, applicationMessages.getGeneralParty()); // Creates action profile column Column<Parlamentarian, Parlamentarian> profileColumn = new Column<Parlamentarian, Parlamentarian>(new ActionCell<Parlamentarian>("", new ActionCell.Delegate<Parlamentarian>() { @Override public void execute(Parlamentarian parlamentarian) { PlaceRequest placeRequest = new PlaceRequest(ParlamentarianPresenter.PLACE); placeManager.revealPlace(placeRequest.with(ParlamentarianPresenter.PARAM_PARLAMENTARIAN_ID, parlamentarian.getId().toString())); } }) { @Override public void render(Cell.Context context, Parlamentarian value, SafeHtmlBuilder sb) { sb.append(new SafeHtml() { @Override public String asString() { return "<div class=\"profileButton\"></div>"; } }); } }) { @Override public Parlamentarian getValue(Parlamentarian parlamentarian) { return parlamentarian; } }; // Adds action profile column to table getView().getParlamentarianTable().addColumn(profileColumn, applicationMessages.getGeneralProfile()); // Sets selection model for each row final SingleSelectionModel<Parlamentarian> selectionModel = new SingleSelectionModel<Parlamentarian>(Parlamentarian.KEY_PROVIDER); getView().getParlamentarianTable().setSelectionModel(selectionModel); selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { public void onSelectionChange(SelectionChangeEvent event) { selectedParlamentarian = selectionModel.getSelectedObject(); getView().setParlamentarianDisplay(selectedParlamentarian.getFirstName() + " " + selectedParlamentarian.getLastName()); if (selectedParlamentarian.getImage() == null) { getView().setParlamentarianImage("images/parlamentarian/large/avatar.png"); } else { getView().setParlamentarianImage("images/parlamentarian/large/" + selectedParlamentarian.getImage()); } setBillTable(); } }); } @Override public void initCategoryTable() { while (getView().getCategoryTable().getColumnCount() > 0) { getView().getCategoryTable().removeColumn(0); } // Creates name column TextColumn<Category> nameColumn = new TextColumn<Category>() { @Override public String getValue(Category category) { return category.getName(); } }; // Sets sortable name column nameColumn.setSortable(true); ListHandler<Category> sortHandler = new ListHandler<Category>(((ListDataProvider<Category>) categoryData).getList()); getView().getCategoryTable().addColumnSortHandler(sortHandler); sortHandler.setComparator(nameColumn, new Comparator<Category>() { public int compare(Category o1, Category o2) { return o1.getName().compareTo(o2.getName()); } }); // Adds name column to table getView().getCategoryTable().addColumn(nameColumn, applicationMessages.getGeneralCategory()); // Creates action suscription column Column<Category, Category> suscriptionColumn = new Column<Category, Category>(new ActionCell<Category>("", new ActionCell.Delegate<Category>() { @Override public void execute(Category category) { // TODO: add category suscription servlet } }) { @Override public void render(Cell.Context context, Category value, SafeHtmlBuilder sb) { sb.append(new SafeHtml() { @Override public String asString() { return "<div class=\"suscribeButtonCategory\"></div>"; } }); } }) { @Override public Category getValue(Category category) { return category; } }; // Adds action suscription column to table getView().getCategoryTable().addColumn(suscriptionColumn, applicationMessages.getGeneralSusbcribe()); // Sets selection model for each row final SingleSelectionModel<Category> selectionModel = new SingleSelectionModel<Category>(Category.KEY_PROVIDER); getView().getCategoryTable().setSelectionModel(selectionModel); selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { public void onSelectionChange(SelectionChangeEvent event) { selectedCategory = selectionModel.getSelectedObject(); getView().setCategoryDisplay(selectedCategory.getName()); setBillTable(); } }); } @Override public void initBillTable() { while (getView().getBillTable().getColumnCount() > 0) { getView().getBillTable().removeColumn(0); } // Creates bulletin column TextColumn<Bill> bulletinColumn = new TextColumn<Bill>() { @Override public String getValue(Bill bill) { return bill.getBulletinNumber(); } }; // Sets sortable bulletin column bulletinColumn.setSortable(true); ListHandler<Bill> bulletinSortHandler = new ListHandler<Bill>(((ListDataProvider<Bill>) billData).getList()); getView().getBillTable().addColumnSortHandler(bulletinSortHandler); bulletinSortHandler.setComparator(bulletinColumn, new Comparator<Bill>() { public int compare(Bill o1, Bill o2) { return o1.getBulletinNumber().compareTo(o2.getBulletinNumber()); } }); // Adds bulletin column to table getView().getBillTable().addColumn(bulletinColumn, applicationMessages.getBillBulletin()); // Creates title column TextColumn<Bill> titleColumn = new TextColumn<Bill>() { @Override public String getValue(Bill bill) { return bill.getTitle(); } }; // Sets sortable title column titleColumn.setSortable(true); ListHandler<Bill> titleSortHandler = new ListHandler<Bill>(((ListDataProvider<Bill>) billData).getList()); getView().getBillTable().addColumnSortHandler(titleSortHandler); titleSortHandler.setComparator(titleColumn, new Comparator<Bill>() { public int compare(Bill o1, Bill o2) { return o1.getTitle().compareTo(o2.getTitle()); } }); // Adds title column to table getView().getBillTable().addColumn(titleColumn, applicationMessages.getBillConflictedBill()); // Creates isAuthor column Column<Bill, String> isAuthorColumn = new Column<Bill, String>(new ImageCell()){ @Override public String getValue(Bill bill) { if (selectedParlamentarian != null) { if (selectedParlamentarian.getAuthoredBills().contains(bill)) { return "images/footprints.png"; } } return "images/footprints_hidden.png"; } }; // Adds isAuthor column to table getView().getBillTable().addColumn(isAuthorColumn, applicationMessages.getBillIsAuthoredBill()); // Creates isVoted column Column<Bill, String> isVotedColumn = new Column<Bill, String>(new ImageCell()){ @Override public String getValue(Bill bill) { if (selectedParlamentarian != null) { if (selectedParlamentarian.getVotedBills().contains(bill)) { return "images/footprints.png"; } } return "images/footprints_hidden.png"; } }; // Adds isVoted column to table getView().getBillTable().addColumn(isVotedColumn, applicationMessages.getBillVotedInChamber()); // Creates action suscription column Column<Bill, Bill> suscriptionColumn = new Column<Bill, Bill>(new ActionCell<Bill>("", new ActionCell.Delegate<Bill>() { @Override public void execute(Bill bill) { // TODO: add bill suscription servlet } }) { @Override public void render(Cell.Context context, Bill value, SafeHtmlBuilder sb) { sb.append(new SafeHtml() { @Override public String asString() { return "<div class=\"suscribeButtonBill\"></div>"; } }); } }) { @Override public Bill getValue(Bill bill) { return bill; } }; // Adds action suscription column to table getView().getBillTable().addColumn(suscriptionColumn, applicationMessages.getGeneralSusbcribe()); // Sets selection model for each row final SingleSelectionModel<Bill> selectionModel = new SingleSelectionModel<Bill>(Bill.KEY_PROVIDER); getView().getBillTable().setSelectionModel(selectionModel); selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { public void onSelectionChange(SelectionChangeEvent event) { - // Add go to Bill Profile Action on selected row + // TODO: Add go to Bill Profile Action on selected row } }); } @Override public void setBillTable() { if (selectedParlamentarian != null && selectedCategory != null) { searchBill(selectedParlamentarian, selectedCategory); } } @Override public void showParlamentarianProfile(){ if (selectedParlamentarian != null) { PlaceRequest placeRequest = new PlaceRequest(ParlamentarianPresenter.PLACE); placeManager.revealPlace(placeRequest.with(ParlamentarianPresenter.PARAM_PARLAMENTARIAN_ID, selectedParlamentarian.getId().toString())); } } }
true
true
public void initBillTable() { while (getView().getBillTable().getColumnCount() > 0) { getView().getBillTable().removeColumn(0); } // Creates bulletin column TextColumn<Bill> bulletinColumn = new TextColumn<Bill>() { @Override public String getValue(Bill bill) { return bill.getBulletinNumber(); } }; // Sets sortable bulletin column bulletinColumn.setSortable(true); ListHandler<Bill> bulletinSortHandler = new ListHandler<Bill>(((ListDataProvider<Bill>) billData).getList()); getView().getBillTable().addColumnSortHandler(bulletinSortHandler); bulletinSortHandler.setComparator(bulletinColumn, new Comparator<Bill>() { public int compare(Bill o1, Bill o2) { return o1.getBulletinNumber().compareTo(o2.getBulletinNumber()); } }); // Adds bulletin column to table getView().getBillTable().addColumn(bulletinColumn, applicationMessages.getBillBulletin()); // Creates title column TextColumn<Bill> titleColumn = new TextColumn<Bill>() { @Override public String getValue(Bill bill) { return bill.getTitle(); } }; // Sets sortable title column titleColumn.setSortable(true); ListHandler<Bill> titleSortHandler = new ListHandler<Bill>(((ListDataProvider<Bill>) billData).getList()); getView().getBillTable().addColumnSortHandler(titleSortHandler); titleSortHandler.setComparator(titleColumn, new Comparator<Bill>() { public int compare(Bill o1, Bill o2) { return o1.getTitle().compareTo(o2.getTitle()); } }); // Adds title column to table getView().getBillTable().addColumn(titleColumn, applicationMessages.getBillConflictedBill()); // Creates isAuthor column Column<Bill, String> isAuthorColumn = new Column<Bill, String>(new ImageCell()){ @Override public String getValue(Bill bill) { if (selectedParlamentarian != null) { if (selectedParlamentarian.getAuthoredBills().contains(bill)) { return "images/footprints.png"; } } return "images/footprints_hidden.png"; } }; // Adds isAuthor column to table getView().getBillTable().addColumn(isAuthorColumn, applicationMessages.getBillIsAuthoredBill()); // Creates isVoted column Column<Bill, String> isVotedColumn = new Column<Bill, String>(new ImageCell()){ @Override public String getValue(Bill bill) { if (selectedParlamentarian != null) { if (selectedParlamentarian.getVotedBills().contains(bill)) { return "images/footprints.png"; } } return "images/footprints_hidden.png"; } }; // Adds isVoted column to table getView().getBillTable().addColumn(isVotedColumn, applicationMessages.getBillVotedInChamber()); // Creates action suscription column Column<Bill, Bill> suscriptionColumn = new Column<Bill, Bill>(new ActionCell<Bill>("", new ActionCell.Delegate<Bill>() { @Override public void execute(Bill bill) { // TODO: add bill suscription servlet } }) { @Override public void render(Cell.Context context, Bill value, SafeHtmlBuilder sb) { sb.append(new SafeHtml() { @Override public String asString() { return "<div class=\"suscribeButtonBill\"></div>"; } }); } }) { @Override public Bill getValue(Bill bill) { return bill; } }; // Adds action suscription column to table getView().getBillTable().addColumn(suscriptionColumn, applicationMessages.getGeneralSusbcribe()); // Sets selection model for each row final SingleSelectionModel<Bill> selectionModel = new SingleSelectionModel<Bill>(Bill.KEY_PROVIDER); getView().getBillTable().setSelectionModel(selectionModel); selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { public void onSelectionChange(SelectionChangeEvent event) { // Add go to Bill Profile Action on selected row } }); }
public void initBillTable() { while (getView().getBillTable().getColumnCount() > 0) { getView().getBillTable().removeColumn(0); } // Creates bulletin column TextColumn<Bill> bulletinColumn = new TextColumn<Bill>() { @Override public String getValue(Bill bill) { return bill.getBulletinNumber(); } }; // Sets sortable bulletin column bulletinColumn.setSortable(true); ListHandler<Bill> bulletinSortHandler = new ListHandler<Bill>(((ListDataProvider<Bill>) billData).getList()); getView().getBillTable().addColumnSortHandler(bulletinSortHandler); bulletinSortHandler.setComparator(bulletinColumn, new Comparator<Bill>() { public int compare(Bill o1, Bill o2) { return o1.getBulletinNumber().compareTo(o2.getBulletinNumber()); } }); // Adds bulletin column to table getView().getBillTable().addColumn(bulletinColumn, applicationMessages.getBillBulletin()); // Creates title column TextColumn<Bill> titleColumn = new TextColumn<Bill>() { @Override public String getValue(Bill bill) { return bill.getTitle(); } }; // Sets sortable title column titleColumn.setSortable(true); ListHandler<Bill> titleSortHandler = new ListHandler<Bill>(((ListDataProvider<Bill>) billData).getList()); getView().getBillTable().addColumnSortHandler(titleSortHandler); titleSortHandler.setComparator(titleColumn, new Comparator<Bill>() { public int compare(Bill o1, Bill o2) { return o1.getTitle().compareTo(o2.getTitle()); } }); // Adds title column to table getView().getBillTable().addColumn(titleColumn, applicationMessages.getBillConflictedBill()); // Creates isAuthor column Column<Bill, String> isAuthorColumn = new Column<Bill, String>(new ImageCell()){ @Override public String getValue(Bill bill) { if (selectedParlamentarian != null) { if (selectedParlamentarian.getAuthoredBills().contains(bill)) { return "images/footprints.png"; } } return "images/footprints_hidden.png"; } }; // Adds isAuthor column to table getView().getBillTable().addColumn(isAuthorColumn, applicationMessages.getBillIsAuthoredBill()); // Creates isVoted column Column<Bill, String> isVotedColumn = new Column<Bill, String>(new ImageCell()){ @Override public String getValue(Bill bill) { if (selectedParlamentarian != null) { if (selectedParlamentarian.getVotedBills().contains(bill)) { return "images/footprints.png"; } } return "images/footprints_hidden.png"; } }; // Adds isVoted column to table getView().getBillTable().addColumn(isVotedColumn, applicationMessages.getBillVotedInChamber()); // Creates action suscription column Column<Bill, Bill> suscriptionColumn = new Column<Bill, Bill>(new ActionCell<Bill>("", new ActionCell.Delegate<Bill>() { @Override public void execute(Bill bill) { // TODO: add bill suscription servlet } }) { @Override public void render(Cell.Context context, Bill value, SafeHtmlBuilder sb) { sb.append(new SafeHtml() { @Override public String asString() { return "<div class=\"suscribeButtonBill\"></div>"; } }); } }) { @Override public Bill getValue(Bill bill) { return bill; } }; // Adds action suscription column to table getView().getBillTable().addColumn(suscriptionColumn, applicationMessages.getGeneralSusbcribe()); // Sets selection model for each row final SingleSelectionModel<Bill> selectionModel = new SingleSelectionModel<Bill>(Bill.KEY_PROVIDER); getView().getBillTable().setSelectionModel(selectionModel); selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { public void onSelectionChange(SelectionChangeEvent event) { // TODO: Add go to Bill Profile Action on selected row } }); }
diff --git a/wingx/src/java/org/wingx/plaf/css/CalendarCG.java b/wingx/src/java/org/wingx/plaf/css/CalendarCG.java index d57094a..57da781 100644 --- a/wingx/src/java/org/wingx/plaf/css/CalendarCG.java +++ b/wingx/src/java/org/wingx/plaf/css/CalendarCG.java @@ -1,188 +1,188 @@ package org.wingx.plaf.css; import java.text.DateFormat; import java.text.Format; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import org.wings.SDimension; import org.wings.SFormattedTextField; import org.wings.SResourceIcon; import org.wings.header.Header; import org.wings.header.SessionHeaders; import org.wings.io.Device; import org.wings.plaf.Update; import org.wings.plaf.css.AbstractComponentCG; import org.wings.plaf.css.AbstractUpdate; import org.wings.plaf.css.UpdateHandler; import org.wings.plaf.css.Utils; import org.wings.plaf.css.script.OnHeadersLoadedScript; import org.wings.session.ScriptManager; import org.wings.util.SStringBuilder; import org.wingx.XCalendar; /** * @author <a href="mailto:e.habicht@thiesen.com">Erik Habicht</a> * @author Stephan Schuster */ public class CalendarCG extends AbstractComponentCG<XCalendar> implements org.wingx.plaf.CalendarCG<XCalendar> { private static final long serialVersionUID = 1L; protected final static List<Header> headers; static { String[] images = new String [] { "org/wingx/calendar/calcd.gif", "org/wingx/calendar/cally.gif", "org/wingx/calendar/calry.gif" }; for ( int x = 0, y = images.length ; x < y ; x++ ) { new SResourceIcon(images[x]).getId(); } List<Header> headerList = new ArrayList<Header>(); headerList.add(Utils.createExternalizedCSSHeaderFromProperty(Utils.CSS_YUI_ASSETS_CALENDAR)); headerList.add(Utils.createExternalizedJSHeaderFromProperty(Utils.JS_YUI_CALENDAR)); headerList.add(Utils.createExternalizedJSHeader("org/wingx/calendar/xcalendar.js")); headers = Collections.unmodifiableList(headerList); } public CalendarCG() { } public void installCG(XCalendar component) { super.installCG(component); SessionHeaders.getInstance().registerHeaders(headers); } public void uninstallCG(XCalendar component) { super.uninstallCG(component); SessionHeaders.getInstance().deregisterHeaders(headers); } public void writeInternal(Device device, XCalendar component) throws java.io.IOException { final String idComponent = component.getName(); final String idValue = idComponent + "val"; final String idButton = idComponent + "btn"; final String idContainer = idComponent + "con"; final String idCalendar = idComponent + "cal"; SFormattedTextField fTextField = component.getFormattedTextField(); SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); dateFormat.setTimeZone(component.getTimeZone()); device.print("<table"); Utils.writeAllAttributes(device, component); device.print("><tr><td class=\"tf\" width=\"*\""); int oversizePadding = Utils.calculateHorizontalOversize(fTextField, true); if (oversizePadding != 0) Utils.optAttribute(device, "oversize", oversizePadding); device.print('>'); SDimension preferredSize = component.getPreferredSize(); if (preferredSize != null && preferredSize.getWidth() != null && "auto".equals(preferredSize.getWidth())) fTextField.setPreferredSize(SDimension.FULLWIDTH); fTextField.setEnabled(component.isEnabled()); fTextField.write(device); device.print("\n</td><td class=\"bu\" width=\"1\">\n"); device.print("<input type=\"hidden\" id=\"").print(idValue) .print("\" name=\"").print(idValue) .print("\" value=\"").print(format(dateFormat, component.getDate())) .print("\">\n"); device.print("<img id=\"").print(idButton) .print("\" src=\"").print( component.getEditIcon().getURL() ) .print("\" />\n"); device.print("<div class=\"container\" id=\"").print(idContainer) .print("\"><div class=\"hd\"></div><div class=\"bd\"><div class=\"calendar\" id=\"") .print(idCalendar).print("\"></div></div></div></td>"); writeTableSuffix(device, component); if (component.isEnabled()) { SimpleDateFormat format_months_long = new SimpleDateFormat("MMMMM"); format_months_long.setTimeZone(component.getTimeZone()); SimpleDateFormat format_weekdays_short = new SimpleDateFormat("EE"); format_weekdays_short.setTimeZone(component.getTimeZone()); - SStringBuilder newXCalendar = new SStringBuilder("new wingS.xcalendar.XCalendar("); - newXCalendar.append('"').append(component.getName()).append("\","); - newXCalendar.append("{iframe:false,"); - newXCalendar.append("months_long:").append(createMonthsString( format_months_long)).append(','); - newXCalendar.append("weekdays_short:").append(createWeekdaysString( format_weekdays_short)).append(','); - newXCalendar.append("start_weekday:").append((Calendar.getInstance().getFirstDayOfWeek() - 1)).append("}"); - newXCalendar.append(");"); + SStringBuilder script = new SStringBuilder("new wingS.xcalendar.XCalendar(") + .append('"').append(component.getName()).append("\",\"") + .append(component.getParentFrame().getName()).append("\", {iframe:false,") + .append("months_long:").append(createMonthsString( format_months_long)).append(',') + .append("weekdays_short:").append(createWeekdaysString( format_weekdays_short)).append(',') + .append("start_weekday:").append((Calendar.getInstance().getFirstDayOfWeek() - 1)).append("}") + .append(");"); - ScriptManager.getInstance().addScriptListener(new OnHeadersLoadedScript(newXCalendar.toString(), true)); + ScriptManager.getInstance().addScriptListener(new OnHeadersLoadedScript(script.toString(), true)); } } private String createMonthsString(Format format) { SStringBuilder stringBuilder = new SStringBuilder(); stringBuilder.append('['); Calendar cal = new GregorianCalendar(); cal.set(Calendar.MONTH, Calendar.JANUARY); for (int x = 0, y = 12; x < y; x++) { stringBuilder.append('"'); stringBuilder.append(format.format(cal.getTime())); stringBuilder.append("\","); cal.add(Calendar.MONTH, 1); } stringBuilder.deleteCharAt(stringBuilder.length() - 1); stringBuilder.append(']'); return stringBuilder.toString(); } private String createWeekdaysString(Format format) { SStringBuilder stringBuilder = new SStringBuilder(); stringBuilder.append('['); Calendar cal = new GregorianCalendar(); cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); for (int x = 0, y = 7; x < y; x++) { stringBuilder.append('"'); stringBuilder.append(format.format(cal.getTime())); stringBuilder.append("\","); cal.add(Calendar.DAY_OF_WEEK, 1); } stringBuilder.deleteCharAt(stringBuilder.length() - 1); stringBuilder.append(']'); return stringBuilder.toString(); } private String format(DateFormat dateFormat, Date date) { return date != null ? dateFormat.format(date) : ""; } public Update getHiddenUpdate(XCalendar cal, Date date) { return new HiddenUpdate(cal, date); } protected static class HiddenUpdate extends AbstractUpdate<XCalendar> { private Date date; private SimpleDateFormat format; public HiddenUpdate(XCalendar cal, Date date) { super(cal); this.date = date; this.format = new SimpleDateFormat("MM/dd/yyyy"); } public Handler getHandler() { UpdateHandler handler = new UpdateHandler("value"); handler.addParameter(component.getName() + "val"); handler.addParameter(date == null ? "" : format.format(date)); return handler; } } }
false
true
public void writeInternal(Device device, XCalendar component) throws java.io.IOException { final String idComponent = component.getName(); final String idValue = idComponent + "val"; final String idButton = idComponent + "btn"; final String idContainer = idComponent + "con"; final String idCalendar = idComponent + "cal"; SFormattedTextField fTextField = component.getFormattedTextField(); SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); dateFormat.setTimeZone(component.getTimeZone()); device.print("<table"); Utils.writeAllAttributes(device, component); device.print("><tr><td class=\"tf\" width=\"*\""); int oversizePadding = Utils.calculateHorizontalOversize(fTextField, true); if (oversizePadding != 0) Utils.optAttribute(device, "oversize", oversizePadding); device.print('>'); SDimension preferredSize = component.getPreferredSize(); if (preferredSize != null && preferredSize.getWidth() != null && "auto".equals(preferredSize.getWidth())) fTextField.setPreferredSize(SDimension.FULLWIDTH); fTextField.setEnabled(component.isEnabled()); fTextField.write(device); device.print("\n</td><td class=\"bu\" width=\"1\">\n"); device.print("<input type=\"hidden\" id=\"").print(idValue) .print("\" name=\"").print(idValue) .print("\" value=\"").print(format(dateFormat, component.getDate())) .print("\">\n"); device.print("<img id=\"").print(idButton) .print("\" src=\"").print( component.getEditIcon().getURL() ) .print("\" />\n"); device.print("<div class=\"container\" id=\"").print(idContainer) .print("\"><div class=\"hd\"></div><div class=\"bd\"><div class=\"calendar\" id=\"") .print(idCalendar).print("\"></div></div></div></td>"); writeTableSuffix(device, component); if (component.isEnabled()) { SimpleDateFormat format_months_long = new SimpleDateFormat("MMMMM"); format_months_long.setTimeZone(component.getTimeZone()); SimpleDateFormat format_weekdays_short = new SimpleDateFormat("EE"); format_weekdays_short.setTimeZone(component.getTimeZone()); SStringBuilder newXCalendar = new SStringBuilder("new wingS.xcalendar.XCalendar("); newXCalendar.append('"').append(component.getName()).append("\","); newXCalendar.append("{iframe:false,"); newXCalendar.append("months_long:").append(createMonthsString( format_months_long)).append(','); newXCalendar.append("weekdays_short:").append(createWeekdaysString( format_weekdays_short)).append(','); newXCalendar.append("start_weekday:").append((Calendar.getInstance().getFirstDayOfWeek() - 1)).append("}"); newXCalendar.append(");"); ScriptManager.getInstance().addScriptListener(new OnHeadersLoadedScript(newXCalendar.toString(), true)); } }
public void writeInternal(Device device, XCalendar component) throws java.io.IOException { final String idComponent = component.getName(); final String idValue = idComponent + "val"; final String idButton = idComponent + "btn"; final String idContainer = idComponent + "con"; final String idCalendar = idComponent + "cal"; SFormattedTextField fTextField = component.getFormattedTextField(); SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); dateFormat.setTimeZone(component.getTimeZone()); device.print("<table"); Utils.writeAllAttributes(device, component); device.print("><tr><td class=\"tf\" width=\"*\""); int oversizePadding = Utils.calculateHorizontalOversize(fTextField, true); if (oversizePadding != 0) Utils.optAttribute(device, "oversize", oversizePadding); device.print('>'); SDimension preferredSize = component.getPreferredSize(); if (preferredSize != null && preferredSize.getWidth() != null && "auto".equals(preferredSize.getWidth())) fTextField.setPreferredSize(SDimension.FULLWIDTH); fTextField.setEnabled(component.isEnabled()); fTextField.write(device); device.print("\n</td><td class=\"bu\" width=\"1\">\n"); device.print("<input type=\"hidden\" id=\"").print(idValue) .print("\" name=\"").print(idValue) .print("\" value=\"").print(format(dateFormat, component.getDate())) .print("\">\n"); device.print("<img id=\"").print(idButton) .print("\" src=\"").print( component.getEditIcon().getURL() ) .print("\" />\n"); device.print("<div class=\"container\" id=\"").print(idContainer) .print("\"><div class=\"hd\"></div><div class=\"bd\"><div class=\"calendar\" id=\"") .print(idCalendar).print("\"></div></div></div></td>"); writeTableSuffix(device, component); if (component.isEnabled()) { SimpleDateFormat format_months_long = new SimpleDateFormat("MMMMM"); format_months_long.setTimeZone(component.getTimeZone()); SimpleDateFormat format_weekdays_short = new SimpleDateFormat("EE"); format_weekdays_short.setTimeZone(component.getTimeZone()); SStringBuilder script = new SStringBuilder("new wingS.xcalendar.XCalendar(") .append('"').append(component.getName()).append("\",\"") .append(component.getParentFrame().getName()).append("\", {iframe:false,") .append("months_long:").append(createMonthsString( format_months_long)).append(',') .append("weekdays_short:").append(createWeekdaysString( format_weekdays_short)).append(',') .append("start_weekday:").append((Calendar.getInstance().getFirstDayOfWeek() - 1)).append("}") .append(");"); ScriptManager.getInstance().addScriptListener(new OnHeadersLoadedScript(script.toString(), true)); } }
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceUse.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceUse.java index b67baf9b..db8b7a56 100755 --- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceUse.java +++ b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceUse.java @@ -1,269 +1,269 @@ /******************************************************************************* * Copyright (c) 2003, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.osgi.internal.serviceregistry; import java.security.AccessController; import java.security.PrivilegedAction; import org.eclipse.osgi.framework.debug.Debug; import org.eclipse.osgi.framework.internal.core.BundleContextImpl; import org.eclipse.osgi.framework.internal.core.Msg; import org.eclipse.osgi.util.NLS; import org.osgi.framework.*; /** * This class represents the use of a service by a bundle. One is created for each * service acquired by a bundle. This class manages the calls to ServiceFactory * and the bundle's use count. * * @ThreadSafe */ public class ServiceUse { /** ServiceFactory object if the service instance represents a factory, null otherwise */ final ServiceFactory factory; /** BundleContext associated with this service use */ final BundleContextImpl context; /** ServiceDescription of the registered service */ final ServiceRegistrationImpl registration; /** Service object either registered or that returned by ServiceFactory.getService() */ /* @GuardedBy("this") */ private Object cachedService; /** bundle's use count for this service */ /* @GuardedBy("this") */ private int useCount; /** Internal framework object. */ /** * Constructs a service use encapsulating the service object. * Objects of this class should be constructed while holding the * registrations lock. * * @param context bundle getting the service * @param registration ServiceRegistration of the service */ ServiceUse(BundleContextImpl context, ServiceRegistrationImpl registration) { this.useCount = 0; Object service = registration.getServiceObject(); if (service instanceof ServiceFactory) { this.factory = (ServiceFactory) service; this.cachedService = null; } else { this.factory = null; this.cachedService = service; } this.context = context; this.registration = registration; } /** * Get a service's service object. * Retrieves the service object for a service. * A bundle's use of a service is tracked by a * use count. Each time a service's service object is returned by * {@link #getService}, the context bundle's use count for the service * is incremented by one. Each time the service is release by * {@link #ungetService}, the context bundle's use count * for the service is decremented by one. * When a bundle's use count for a service * drops to zero, the bundle should no longer use the service. * * <p>The following steps are followed to get the service object: * <ol> * <li>The context bundle's use count for this service is incremented by one. * <li>If the context bundle's use count for the service is now one and * the service was registered with a {@link ServiceFactory}, * the {@link ServiceFactory#getService ServiceFactory.getService} method * is called to create a service object for the context bundle. * This service object is cached by the framework. * While the context bundle's use count for the service is greater than zero, * subsequent calls to get the services's service object for the context bundle * will return the cached service object. * <br>If the service object returned by the {@link ServiceFactory} * is not an <code>instanceof</code> * all the classes named when the service was registered or * the {@link ServiceFactory} throws an exception, * <code>null</code> is returned and a * {@link FrameworkEvent} of type {@link FrameworkEvent#ERROR} is broadcast. * <li>The service object for the service is returned. * </ol> * * @return A service object for the service associated with this * reference. */ /* @GuardedBy("this") */ Object getService() { if ((useCount > 0) || (factory == null)) { useCount++; return cachedService; } if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println("getService[factory=" + registration.getBundle() + "](" + context.getBundleImpl() + "," + registration + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } final Object service; try { service = AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return factory.getService(context.getBundleImpl(), registration); } }); } catch (Throwable t) { if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println(factory + ".getService() exception: " + t.getMessage()); //$NON-NLS-1$ Debug.printStackTrace(t); } // allow the adaptor to handle this unexpected error context.getFramework().getAdaptor().handleRuntimeError(t); ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_EXCEPTION, factory.getClass().getName(), "getService"), ServiceException.FACTORY_EXCEPTION, t); //$NON-NLS-1$ context.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se); return null; } if (service == null) { if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println(factory + ".getService() returned null."); //$NON-NLS-1$ } ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_OBJECT_NULL_EXCEPTION, factory.getClass().getName()), ServiceException.FACTORY_ERROR); - context.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se); + context.getFramework().publishFrameworkEvent(FrameworkEvent.WARNING, registration.getBundle(), se); return null; } String[] clazzes = registration.getClasses(); String invalidService = ServiceRegistry.checkServiceClass(clazzes, service); if (invalidService != null) { if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println("Service object is not an instanceof " + invalidService); //$NON-NLS-1$ } ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_NOT_INSTANCEOF_CLASS_EXCEPTION, factory.getClass().getName(), invalidService), ServiceException.FACTORY_ERROR); context.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se); return null; } this.cachedService = service; useCount++; return service; } /** * Unget a service's service object. * Releases the service object for a service. * If the context bundle's use count for the service is zero, this method * returns <code>false</code>. Otherwise, the context bundle's use count for the * service is decremented by one. * * <p>The service's service object * should no longer be used and all references to it should be destroyed * when a bundle's use count for the service * drops to zero. * * <p>The following steps are followed to unget the service object: * <ol> * <li>If the context bundle's use count for the service is zero or * the service has been unregistered, * <code>false</code> is returned. * <li>The context bundle's use count for this service is decremented by one. * <li>If the context bundle's use count for the service is now zero and * the service was registered with a {@link ServiceFactory}, * the {@link ServiceFactory#ungetService ServiceFactory.ungetService} method * is called to release the service object for the context bundle. * <li><code>true</code> is returned. * </ol> * * @return <code>true</code> if the context bundle's use count for the service * is zero otherwise <code>false</code>. */ /* @GuardedBy("this") */ boolean ungetService() { if (useCount == 0) { return true; } useCount--; if (useCount > 0) { return false; } if (factory == null) { return true; } final Object service = cachedService; cachedService = null; if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println("ungetService[factory=" + registration.getBundle() + "](" + context.getBundleImpl() + "," + registration + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } try { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { factory.ungetService(context.getBundleImpl(), registration, service); return null; } }); } catch (Throwable t) { if (Debug.DEBUG && Debug.DEBUG_GENERAL) { Debug.println(factory + ".ungetService() exception"); //$NON-NLS-1$ Debug.printStackTrace(t); } ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_EXCEPTION, factory.getClass().getName(), "ungetService"), ServiceException.FACTORY_EXCEPTION, t); //$NON-NLS-1$ context.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se); } return true; } /** * Release a service's service object. * <ol> * <li>The bundle's use count for this service is set to zero. * <li>If the service was registered with a {@link ServiceFactory}, * the {@link ServiceFactory#ungetService ServiceFactory.ungetService} method * is called to release the service object for the bundle. * </ol> */ /* @GuardedBy("this") */ void releaseService() { if ((useCount == 0) || (factory == null)) { return; } final Object service = cachedService; cachedService = null; useCount = 0; if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println("releaseService[factory=" + registration.getBundle() + "](" + context.getBundleImpl() + "," + registration + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } try { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { factory.ungetService(context.getBundleImpl(), registration, service); return null; } }); } catch (Throwable t) { if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println(factory + ".ungetService() exception"); //$NON-NLS-1$ Debug.printStackTrace(t); } ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_EXCEPTION, factory.getClass().getName(), "ungetService"), ServiceException.FACTORY_EXCEPTION, t); //$NON-NLS-1$ context.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se); } } }
true
true
Object getService() { if ((useCount > 0) || (factory == null)) { useCount++; return cachedService; } if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println("getService[factory=" + registration.getBundle() + "](" + context.getBundleImpl() + "," + registration + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } final Object service; try { service = AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return factory.getService(context.getBundleImpl(), registration); } }); } catch (Throwable t) { if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println(factory + ".getService() exception: " + t.getMessage()); //$NON-NLS-1$ Debug.printStackTrace(t); } // allow the adaptor to handle this unexpected error context.getFramework().getAdaptor().handleRuntimeError(t); ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_EXCEPTION, factory.getClass().getName(), "getService"), ServiceException.FACTORY_EXCEPTION, t); //$NON-NLS-1$ context.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se); return null; } if (service == null) { if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println(factory + ".getService() returned null."); //$NON-NLS-1$ } ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_OBJECT_NULL_EXCEPTION, factory.getClass().getName()), ServiceException.FACTORY_ERROR); context.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se); return null; } String[] clazzes = registration.getClasses(); String invalidService = ServiceRegistry.checkServiceClass(clazzes, service); if (invalidService != null) { if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println("Service object is not an instanceof " + invalidService); //$NON-NLS-1$ } ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_NOT_INSTANCEOF_CLASS_EXCEPTION, factory.getClass().getName(), invalidService), ServiceException.FACTORY_ERROR); context.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se); return null; } this.cachedService = service; useCount++; return service; }
Object getService() { if ((useCount > 0) || (factory == null)) { useCount++; return cachedService; } if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println("getService[factory=" + registration.getBundle() + "](" + context.getBundleImpl() + "," + registration + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } final Object service; try { service = AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return factory.getService(context.getBundleImpl(), registration); } }); } catch (Throwable t) { if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println(factory + ".getService() exception: " + t.getMessage()); //$NON-NLS-1$ Debug.printStackTrace(t); } // allow the adaptor to handle this unexpected error context.getFramework().getAdaptor().handleRuntimeError(t); ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_EXCEPTION, factory.getClass().getName(), "getService"), ServiceException.FACTORY_EXCEPTION, t); //$NON-NLS-1$ context.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se); return null; } if (service == null) { if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println(factory + ".getService() returned null."); //$NON-NLS-1$ } ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_OBJECT_NULL_EXCEPTION, factory.getClass().getName()), ServiceException.FACTORY_ERROR); context.getFramework().publishFrameworkEvent(FrameworkEvent.WARNING, registration.getBundle(), se); return null; } String[] clazzes = registration.getClasses(); String invalidService = ServiceRegistry.checkServiceClass(clazzes, service); if (invalidService != null) { if (Debug.DEBUG && Debug.DEBUG_SERVICES) { Debug.println("Service object is not an instanceof " + invalidService); //$NON-NLS-1$ } ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_NOT_INSTANCEOF_CLASS_EXCEPTION, factory.getClass().getName(), invalidService), ServiceException.FACTORY_ERROR); context.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se); return null; } this.cachedService = service; useCount++; return service; }
diff --git a/src/main/org/jboss/messaging/core/security/impl/SecurityStoreImpl.java b/src/main/org/jboss/messaging/core/security/impl/SecurityStoreImpl.java index a39fa53fa..e1c62ba22 100644 --- a/src/main/org/jboss/messaging/core/security/impl/SecurityStoreImpl.java +++ b/src/main/org/jboss/messaging/core/security/impl/SecurityStoreImpl.java @@ -1,273 +1,273 @@ /* * JBoss, Home of Professional Open Source * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.messaging.core.security.impl; import static org.jboss.messaging.core.config.impl.ConfigurationImpl.DEFAULT_MANAGEMENT_CLUSTER_PASSWORD; import static org.jboss.messaging.core.management.NotificationType.SECURITY_AUTHENTICATION_VIOLATION; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.jboss.messaging.core.client.management.impl.ManagementHelper; import org.jboss.messaging.core.exception.MessagingException; import org.jboss.messaging.core.logging.Logger; import org.jboss.messaging.core.management.Notification; import org.jboss.messaging.core.management.NotificationService; import org.jboss.messaging.core.management.NotificationType; import org.jboss.messaging.core.security.CheckType; import org.jboss.messaging.core.security.JBMSecurityManager; import org.jboss.messaging.core.security.Role; import org.jboss.messaging.core.security.SecurityStore; import org.jboss.messaging.core.server.ServerSession; import org.jboss.messaging.core.settings.HierarchicalRepository; import org.jboss.messaging.core.settings.HierarchicalRepositoryChangeListener; import org.jboss.messaging.utils.ConcurrentHashSet; import org.jboss.messaging.utils.SimpleString; import org.jboss.messaging.utils.TypedProperties; /** * The JBM SecurityStore implementation * * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a> * @author <a href="ataylor@redhat.com">Andy Taylor</a> * * Parts based on old version by: * * @author Peter Antman * @author <a href="mailto:Scott.Stark@jboss.org">Scott Stark</a> * @author <a href="mailto:ovidiu@feodorov.com">Ovidiu Feodorov</a> * * @version $Revision$ * * $Id$ */ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryChangeListener { // Constants ----------------------------------------------------- private static final Logger log = Logger.getLogger(SecurityStoreImpl.class); public static final String CLUSTER_ADMIN_USER = "JBM.MANAGEMENT.ADMIN.USER"; // Static -------------------------------------------------------- // Attributes ---------------------------------------------------- private boolean trace = log.isTraceEnabled(); private HierarchicalRepository<Set<Role>> securityRepository; private JBMSecurityManager securityManager; private final ConcurrentMap<CheckType, ConcurrentHashSet<SimpleString>> cache = new ConcurrentHashMap<CheckType, ConcurrentHashSet<SimpleString>>(); private final long invalidationInterval; private volatile long lastCheck; private final boolean securityEnabled; private String managementClusterPassword; private NotificationService notificationService; // Constructors -------------------------------------------------- public SecurityStoreImpl(final long invalidationInterval, final boolean securityEnabled) { this.invalidationInterval = invalidationInterval; this.securityEnabled = securityEnabled; } // SecurityManager implementation -------------------------------- public void authenticate(final String user, final String password) throws Exception { if (securityEnabled) { if (CLUSTER_ADMIN_USER.equals(user)) { if (trace) { log.trace("Authenticating cluster admin user"); } checkDefaultManagementClusterPassword(password); // The special user CLUSTER_ADMIN_USER is used for creating sessions that replicate management operation between nodes if (!managementClusterPassword.equals(password)) { throw new MessagingException(MessagingException.SECURITY_EXCEPTION, "Unable to validate user: " + user); } } else { if (!securityManager.validateUser(user, password)) { if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putStringProperty(ManagementHelper.HDR_USER, SimpleString.toSimpleString(user)); Notification notification = new Notification(SECURITY_AUTHENTICATION_VIOLATION, props); notificationService.sendNotification(notification); } throw new MessagingException(MessagingException.SECURITY_EXCEPTION, "Unable to validate user: " + user); } } } } public void check(final SimpleString address, final CheckType checkType, final ServerSession session) throws Exception { if (securityEnabled) { if (trace) { log.trace("checking access permissions to " + address); } if (checkCached(address, checkType)) { // OK return; } String saddress = address.toString(); Set<Role> roles = securityRepository.getMatch(saddress); String user = session.getUsername(); if (CLUSTER_ADMIN_USER.equals(user)) { // The special user CLUSTER_ADMIN_USER is used for creating sessions that replicate management operation between nodes //It has automatic read/write access to all destinations return; } else if (!securityManager.validateUserAndRole(user, session.getPassword(), roles, checkType)) { if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putStringProperty(ManagementHelper.HDR_ADDRESS, address); props.putStringProperty(ManagementHelper.HDR_CHECK_TYPE, new SimpleString(checkType.toString())); - props.putStringProperty(ManagementHelper.HDR_USER, new SimpleString(user)); + props.putStringProperty(ManagementHelper.HDR_USER, SimpleString.toSimpleString(user)); Notification notification = new Notification(NotificationType.SECURITY_PERMISSION_VIOLATION, props); notificationService.sendNotification(notification); } throw new MessagingException(MessagingException.SECURITY_EXCEPTION, "Unable to validate user: " + session.getUsername()); } // if we get here we're granted, add to the cache ConcurrentHashSet<SimpleString> set = new ConcurrentHashSet<SimpleString>(); ConcurrentHashSet<SimpleString> act = cache.putIfAbsent(checkType, set); if(act != null) { set = act; } set.add(address); } } public void onChange() { invalidateCache(); } // Public -------------------------------------------------------- public void setSecurityRepository(HierarchicalRepository<Set<Role>> securityRepository) { this.securityRepository = securityRepository; securityRepository.registerListener(this); } public void setNotificationService(NotificationService notificationService) { this.notificationService = notificationService; } public void setSecurityManager(JBMSecurityManager securityManager) { this.securityManager = securityManager; } public void setManagementClusterPassword(String password) { this.managementClusterPassword = password; checkDefaultManagementClusterPassword(password); } // Protected ----------------------------------------------------- // Package Private ----------------------------------------------- // Private ------------------------------------------------------- private void invalidateCache() { cache.clear(); } private boolean checkCached(final SimpleString dest, final CheckType checkType) { long now = System.currentTimeMillis(); boolean granted = false; if (now - lastCheck > invalidationInterval) { invalidateCache(); } else { ConcurrentHashSet<SimpleString> act = cache.get(checkType); if(act != null) { granted = act.contains(dest); } } lastCheck = now; return granted; } private void checkDefaultManagementClusterPassword(String password) { // Sanity check if (DEFAULT_MANAGEMENT_CLUSTER_PASSWORD.equals(password)) { log.warn("It has been detected that the cluster admin password which is used to " + "replicate management operation from one node to the other has not had its password changed from the installation default. " + "Please see the JBoss Messaging user guide for instructions on how to do this."); } } // Inner class --------------------------------------------------- }
true
true
public void check(final SimpleString address, final CheckType checkType, final ServerSession session) throws Exception { if (securityEnabled) { if (trace) { log.trace("checking access permissions to " + address); } if (checkCached(address, checkType)) { // OK return; } String saddress = address.toString(); Set<Role> roles = securityRepository.getMatch(saddress); String user = session.getUsername(); if (CLUSTER_ADMIN_USER.equals(user)) { // The special user CLUSTER_ADMIN_USER is used for creating sessions that replicate management operation between nodes //It has automatic read/write access to all destinations return; } else if (!securityManager.validateUserAndRole(user, session.getPassword(), roles, checkType)) { if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putStringProperty(ManagementHelper.HDR_ADDRESS, address); props.putStringProperty(ManagementHelper.HDR_CHECK_TYPE, new SimpleString(checkType.toString())); props.putStringProperty(ManagementHelper.HDR_USER, new SimpleString(user)); Notification notification = new Notification(NotificationType.SECURITY_PERMISSION_VIOLATION, props); notificationService.sendNotification(notification); } throw new MessagingException(MessagingException.SECURITY_EXCEPTION, "Unable to validate user: " + session.getUsername()); } // if we get here we're granted, add to the cache ConcurrentHashSet<SimpleString> set = new ConcurrentHashSet<SimpleString>(); ConcurrentHashSet<SimpleString> act = cache.putIfAbsent(checkType, set); if(act != null) { set = act; } set.add(address); } }
public void check(final SimpleString address, final CheckType checkType, final ServerSession session) throws Exception { if (securityEnabled) { if (trace) { log.trace("checking access permissions to " + address); } if (checkCached(address, checkType)) { // OK return; } String saddress = address.toString(); Set<Role> roles = securityRepository.getMatch(saddress); String user = session.getUsername(); if (CLUSTER_ADMIN_USER.equals(user)) { // The special user CLUSTER_ADMIN_USER is used for creating sessions that replicate management operation between nodes //It has automatic read/write access to all destinations return; } else if (!securityManager.validateUserAndRole(user, session.getPassword(), roles, checkType)) { if (notificationService != null) { TypedProperties props = new TypedProperties(); props.putStringProperty(ManagementHelper.HDR_ADDRESS, address); props.putStringProperty(ManagementHelper.HDR_CHECK_TYPE, new SimpleString(checkType.toString())); props.putStringProperty(ManagementHelper.HDR_USER, SimpleString.toSimpleString(user)); Notification notification = new Notification(NotificationType.SECURITY_PERMISSION_VIOLATION, props); notificationService.sendNotification(notification); } throw new MessagingException(MessagingException.SECURITY_EXCEPTION, "Unable to validate user: " + session.getUsername()); } // if we get here we're granted, add to the cache ConcurrentHashSet<SimpleString> set = new ConcurrentHashSet<SimpleString>(); ConcurrentHashSet<SimpleString> act = cache.putIfAbsent(checkType, set); if(act != null) { set = act; } set.add(address); } }
diff --git a/metamodel/kevoree/org.kevoree.modeling.sample.kevoree.test/src/test/java/org/kevoree/test/LoadJSonTest.java b/metamodel/kevoree/org.kevoree.modeling.sample.kevoree.test/src/test/java/org/kevoree/test/LoadJSonTest.java index c0aa1726..2dea1baf 100644 --- a/metamodel/kevoree/org.kevoree.modeling.sample.kevoree.test/src/test/java/org/kevoree/test/LoadJSonTest.java +++ b/metamodel/kevoree/org.kevoree.modeling.sample.kevoree.test/src/test/java/org/kevoree/test/LoadJSonTest.java @@ -1,43 +1,43 @@ package org.kevoree.test; import org.junit.Test; import org.kevoree.compare.DefaultModelCompare; import org.kevoree.loader.JSONModelLoader; import org.kevoree.modeling.api.KMFContainer; import org.kevoree.modeling.api.compare.ModelCompare; import org.kevoree.modeling.api.trace.TraceSequence; /** * Created with IntelliJ IDEA. * User: duke * Date: 07/11/2013 * Time: 09:20 */ public class LoadJSonTest { JSONModelLoader loader = new JSONModelLoader(); @Test public void bench() { ModelCompare compare = new DefaultModelCompare(); long before = System.currentTimeMillis(); KMFContainer root = loader.loadModelFromStream(this.getClass().getClassLoader().getResourceAsStream("jedModel.json")).get(0); KMFContainer root2 = loader.loadModelFromStream(this.getClass().getClassLoader().getResourceAsStream("jedModel2.json")).get(0); long after = System.currentTimeMillis(); System.out.println(after - before); before = System.currentTimeMillis(); - TraceSequence sequence = compare.merge(root,root2); + TraceSequence sequence = compare.diff(root,root2); after = System.currentTimeMillis(); System.out.println(after - before); System.out.println(sequence.exportToString()); } }
true
true
public void bench() { ModelCompare compare = new DefaultModelCompare(); long before = System.currentTimeMillis(); KMFContainer root = loader.loadModelFromStream(this.getClass().getClassLoader().getResourceAsStream("jedModel.json")).get(0); KMFContainer root2 = loader.loadModelFromStream(this.getClass().getClassLoader().getResourceAsStream("jedModel2.json")).get(0); long after = System.currentTimeMillis(); System.out.println(after - before); before = System.currentTimeMillis(); TraceSequence sequence = compare.merge(root,root2); after = System.currentTimeMillis(); System.out.println(after - before); System.out.println(sequence.exportToString()); }
public void bench() { ModelCompare compare = new DefaultModelCompare(); long before = System.currentTimeMillis(); KMFContainer root = loader.loadModelFromStream(this.getClass().getClassLoader().getResourceAsStream("jedModel.json")).get(0); KMFContainer root2 = loader.loadModelFromStream(this.getClass().getClassLoader().getResourceAsStream("jedModel2.json")).get(0); long after = System.currentTimeMillis(); System.out.println(after - before); before = System.currentTimeMillis(); TraceSequence sequence = compare.diff(root,root2); after = System.currentTimeMillis(); System.out.println(after - before); System.out.println(sequence.exportToString()); }
diff --git a/WifiSim/src/WifiGUI.java b/WifiSim/src/WifiGUI.java index 5e10d96..3fbb663 100644 --- a/WifiSim/src/WifiGUI.java +++ b/WifiSim/src/WifiGUI.java @@ -1,143 +1,143 @@ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import javax.swing.*; import javax.swing.border.LineBorder; /* Simulator: Jeremy Lozano */ public class WifiGUI { static JTextArea resultsBox; public static void main(String[] args) { //FRAME SETUP JFrame frame = new JFrame("Team 4 WIFI Simulator"); frame.setLayout(new BorderLayout()); //LEFT AND RIGHT PANEL DECLRATION AND SETUP final JPanel leftPanel = new JPanel(); leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS)); final JPanel rightPanel = new JPanel(); ////////////TOP PANEL //TOP PANEL bottom final NodePanel leftPanel2 = new NodePanel(new Node[0]); leftPanel2.setBorder(new LineBorder(Color.RED, 2)); //TOP PANEL top JPanel leftPanel1 = new JPanel(); //leftPanel1.setLayout(new BoxLayout(leftPanel1,BoxLayout.PAGE_AXIS)); JLabel maxPacketSizeLabel = new JLabel("MaxPacketSize (in Bytes)"); final JTextField maxPacketSize = new JTextField("", 5); maxPacketSize.setMaximumSize(maxPacketSize.getPreferredSize()); JLabel numOfPacketsLabel = new JLabel("Number of packets"); final JTextField numOfPackets = new JTextField("", 5); numOfPackets.setMaximumSize(numOfPackets.getPreferredSize()); JLabel numOfNodesLabel = new JLabel("Number of nodes"); final JTextField numOfNodes = new JTextField("", 5); numOfNodes.setMaximumSize(numOfNodes.getPreferredSize()); JButton submitButton = new JButton("Submit"); leftPanel1.add(maxPacketSizeLabel); leftPanel1.add(maxPacketSize); leftPanel1.add(numOfPacketsLabel); leftPanel1.add(numOfPackets); leftPanel1.add(numOfNodesLabel); leftPanel1.add(numOfNodes); leftPanel1.add(submitButton); ////////////BOTTOM PANEL resultsBox = new JTextArea(30,50); resultsBox.setLineWrap(true); final JScrollPane scrollPane = new JScrollPane(resultsBox); scrollPane.setSize(40, 30); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); resultsBox.setEditable(false); leftPanel.add(leftPanel1); leftPanel.add(leftPanel2); rightPanel.add(scrollPane); frame.add(leftPanel, BorderLayout.WEST); frame.add(rightPanel, BorderLayout.CENTER); redirectSystemStreams(); frame.setSize(1000, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); submitButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { int nNodes = 0; int packetSize = 0; int nPackets = 0; try { resultsBox.setText(""); packetSize = Integer.parseInt(maxPacketSize.getText().replace(" ", "")); nPackets = Integer.parseInt(numOfPackets.getText().replace(" ", "")); nNodes = Integer.parseInt(numOfNodes.getText().replace(" ", "")); resultsBox.append("Max Packet Size: " + packetSize + "\nNumber of packets: " + nPackets + "\nNumber of nodes: " + nNodes + '\n'); } catch (Exception E) { resultsBox.removeAll(); resultsBox.setText(""); resultsBox.append("Please enter appropriate entries into all fields!"); } - Simulator a = new Simulator(packetSize, nNodes, nPackets); + Simulator a = new Simulator(packetSize*8, nNodes, nPackets); leftPanel2.setNodes(a.getNodes()); a.run(); leftPanel.repaint(); } }); } private static void updateTextArea(final String text) { SwingUtilities.invokeLater(new Runnable() { public void run() { resultsBox.append(text); } }); } private static void redirectSystemStreams() { OutputStream out = new OutputStream() { @Override public void write(int b) throws IOException { updateTextArea(String.valueOf((char) b)); } @Override public void write(byte[] b, int off, int len) throws IOException { updateTextArea(new String(b, off, len)); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } }; System.setOut(new PrintStream(out, true)); System.setErr(new PrintStream(out, true)); } }
true
true
public static void main(String[] args) { //FRAME SETUP JFrame frame = new JFrame("Team 4 WIFI Simulator"); frame.setLayout(new BorderLayout()); //LEFT AND RIGHT PANEL DECLRATION AND SETUP final JPanel leftPanel = new JPanel(); leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS)); final JPanel rightPanel = new JPanel(); ////////////TOP PANEL //TOP PANEL bottom final NodePanel leftPanel2 = new NodePanel(new Node[0]); leftPanel2.setBorder(new LineBorder(Color.RED, 2)); //TOP PANEL top JPanel leftPanel1 = new JPanel(); //leftPanel1.setLayout(new BoxLayout(leftPanel1,BoxLayout.PAGE_AXIS)); JLabel maxPacketSizeLabel = new JLabel("MaxPacketSize (in Bytes)"); final JTextField maxPacketSize = new JTextField("", 5); maxPacketSize.setMaximumSize(maxPacketSize.getPreferredSize()); JLabel numOfPacketsLabel = new JLabel("Number of packets"); final JTextField numOfPackets = new JTextField("", 5); numOfPackets.setMaximumSize(numOfPackets.getPreferredSize()); JLabel numOfNodesLabel = new JLabel("Number of nodes"); final JTextField numOfNodes = new JTextField("", 5); numOfNodes.setMaximumSize(numOfNodes.getPreferredSize()); JButton submitButton = new JButton("Submit"); leftPanel1.add(maxPacketSizeLabel); leftPanel1.add(maxPacketSize); leftPanel1.add(numOfPacketsLabel); leftPanel1.add(numOfPackets); leftPanel1.add(numOfNodesLabel); leftPanel1.add(numOfNodes); leftPanel1.add(submitButton); ////////////BOTTOM PANEL resultsBox = new JTextArea(30,50); resultsBox.setLineWrap(true); final JScrollPane scrollPane = new JScrollPane(resultsBox); scrollPane.setSize(40, 30); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); resultsBox.setEditable(false); leftPanel.add(leftPanel1); leftPanel.add(leftPanel2); rightPanel.add(scrollPane); frame.add(leftPanel, BorderLayout.WEST); frame.add(rightPanel, BorderLayout.CENTER); redirectSystemStreams(); frame.setSize(1000, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); submitButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { int nNodes = 0; int packetSize = 0; int nPackets = 0; try { resultsBox.setText(""); packetSize = Integer.parseInt(maxPacketSize.getText().replace(" ", "")); nPackets = Integer.parseInt(numOfPackets.getText().replace(" ", "")); nNodes = Integer.parseInt(numOfNodes.getText().replace(" ", "")); resultsBox.append("Max Packet Size: " + packetSize + "\nNumber of packets: " + nPackets + "\nNumber of nodes: " + nNodes + '\n'); } catch (Exception E) { resultsBox.removeAll(); resultsBox.setText(""); resultsBox.append("Please enter appropriate entries into all fields!"); } Simulator a = new Simulator(packetSize, nNodes, nPackets); leftPanel2.setNodes(a.getNodes()); a.run(); leftPanel.repaint(); } }); }
public static void main(String[] args) { //FRAME SETUP JFrame frame = new JFrame("Team 4 WIFI Simulator"); frame.setLayout(new BorderLayout()); //LEFT AND RIGHT PANEL DECLRATION AND SETUP final JPanel leftPanel = new JPanel(); leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS)); final JPanel rightPanel = new JPanel(); ////////////TOP PANEL //TOP PANEL bottom final NodePanel leftPanel2 = new NodePanel(new Node[0]); leftPanel2.setBorder(new LineBorder(Color.RED, 2)); //TOP PANEL top JPanel leftPanel1 = new JPanel(); //leftPanel1.setLayout(new BoxLayout(leftPanel1,BoxLayout.PAGE_AXIS)); JLabel maxPacketSizeLabel = new JLabel("MaxPacketSize (in Bytes)"); final JTextField maxPacketSize = new JTextField("", 5); maxPacketSize.setMaximumSize(maxPacketSize.getPreferredSize()); JLabel numOfPacketsLabel = new JLabel("Number of packets"); final JTextField numOfPackets = new JTextField("", 5); numOfPackets.setMaximumSize(numOfPackets.getPreferredSize()); JLabel numOfNodesLabel = new JLabel("Number of nodes"); final JTextField numOfNodes = new JTextField("", 5); numOfNodes.setMaximumSize(numOfNodes.getPreferredSize()); JButton submitButton = new JButton("Submit"); leftPanel1.add(maxPacketSizeLabel); leftPanel1.add(maxPacketSize); leftPanel1.add(numOfPacketsLabel); leftPanel1.add(numOfPackets); leftPanel1.add(numOfNodesLabel); leftPanel1.add(numOfNodes); leftPanel1.add(submitButton); ////////////BOTTOM PANEL resultsBox = new JTextArea(30,50); resultsBox.setLineWrap(true); final JScrollPane scrollPane = new JScrollPane(resultsBox); scrollPane.setSize(40, 30); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); resultsBox.setEditable(false); leftPanel.add(leftPanel1); leftPanel.add(leftPanel2); rightPanel.add(scrollPane); frame.add(leftPanel, BorderLayout.WEST); frame.add(rightPanel, BorderLayout.CENTER); redirectSystemStreams(); frame.setSize(1000, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); submitButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { int nNodes = 0; int packetSize = 0; int nPackets = 0; try { resultsBox.setText(""); packetSize = Integer.parseInt(maxPacketSize.getText().replace(" ", "")); nPackets = Integer.parseInt(numOfPackets.getText().replace(" ", "")); nNodes = Integer.parseInt(numOfNodes.getText().replace(" ", "")); resultsBox.append("Max Packet Size: " + packetSize + "\nNumber of packets: " + nPackets + "\nNumber of nodes: " + nNodes + '\n'); } catch (Exception E) { resultsBox.removeAll(); resultsBox.setText(""); resultsBox.append("Please enter appropriate entries into all fields!"); } Simulator a = new Simulator(packetSize*8, nNodes, nPackets); leftPanel2.setNodes(a.getNodes()); a.run(); leftPanel.repaint(); } }); }
diff --git a/src/il/technion/ewolf/server/WebGuiHttpService.java b/src/il/technion/ewolf/server/WebGuiHttpService.java index 1fd7aca..e37eff1 100644 --- a/src/il/technion/ewolf/server/WebGuiHttpService.java +++ b/src/il/technion/ewolf/server/WebGuiHttpService.java @@ -1,73 +1,74 @@ package il.technion.ewolf.server; import java.io.IOException; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.HttpStatus; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpExpectationVerifier; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpRequestHandlerResolver; import org.apache.http.protocol.HttpService; import com.google.inject.Inject; public class WebGuiHttpService extends HttpService { HttpSessionStore sessionStore; @Inject public WebGuiHttpService(HttpProcessor processor, ConnectionReuseStrategy connStrategy, HttpResponseFactory responseFactory, HttpRequestHandlerResolver handlerResolver, HttpParams params, HttpSessionStore sessionStore) { super(processor, connStrategy, responseFactory, handlerResolver, params); this.sessionStore = sessionStore; } @Inject public WebGuiHttpService(HttpProcessor processor, ConnectionReuseStrategy connStrategy, HttpResponseFactory responseFactory, HttpRequestHandlerResolver handlerResolver, HttpExpectationVerifier expectationVerifier, HttpParams params, HttpSessionStore sessionStore) { super(processor, connStrategy, responseFactory, handlerResolver, expectationVerifier, params); this.sessionStore = sessionStore; } @Override protected void doService(HttpRequest req, HttpResponse res, HttpContext context) throws HttpException, IOException { boolean authorized = false; if (req.containsHeader("Cookie")) { Header[] headers = req.getHeaders("Cookie"); for (Header h : headers) { String cookie = h.getValue(); - if (sessionStore.isValid(cookie)) { + String key = cookie.substring("session=".length()); + if (sessionStore.isValid(key)) { authorized = true; context.setAttribute("authorized", true); break; } } } if (!authorized) { String uri = req.getRequestLine().getUri(); if (uri.equals("/sfs") || uri.equals("/sfsupload")) { res.setStatusCode(HttpStatus.SC_FORBIDDEN); return; } else { context.setAttribute("authorized", false); } } super.doService(req, res, context); } }
true
true
protected void doService(HttpRequest req, HttpResponse res, HttpContext context) throws HttpException, IOException { boolean authorized = false; if (req.containsHeader("Cookie")) { Header[] headers = req.getHeaders("Cookie"); for (Header h : headers) { String cookie = h.getValue(); if (sessionStore.isValid(cookie)) { authorized = true; context.setAttribute("authorized", true); break; } } } if (!authorized) { String uri = req.getRequestLine().getUri(); if (uri.equals("/sfs") || uri.equals("/sfsupload")) { res.setStatusCode(HttpStatus.SC_FORBIDDEN); return; } else { context.setAttribute("authorized", false); } } super.doService(req, res, context); }
protected void doService(HttpRequest req, HttpResponse res, HttpContext context) throws HttpException, IOException { boolean authorized = false; if (req.containsHeader("Cookie")) { Header[] headers = req.getHeaders("Cookie"); for (Header h : headers) { String cookie = h.getValue(); String key = cookie.substring("session=".length()); if (sessionStore.isValid(key)) { authorized = true; context.setAttribute("authorized", true); break; } } } if (!authorized) { String uri = req.getRequestLine().getUri(); if (uri.equals("/sfs") || uri.equals("/sfsupload")) { res.setStatusCode(HttpStatus.SC_FORBIDDEN); return; } else { context.setAttribute("authorized", false); } } super.doService(req, res, context); }
diff --git a/sandbox/rar/EightToCarRobustnessBatch.java b/sandbox/rar/EightToCarRobustnessBatch.java index e7ed5c16..eae1e703 100644 --- a/sandbox/rar/EightToCarRobustnessBatch.java +++ b/sandbox/rar/EightToCarRobustnessBatch.java @@ -1,190 +1,190 @@ package rar; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.rmi.RemoteException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import ussr.remote.AbstractSimulationBatch; import ussr.remote.facade.ParameterHolder; public class EightToCarRobustnessBatch extends AbstractSimulationBatch { public static class Parameters extends ParameterHolder { public int number; public float minR, maxR, completeR, maxTime, resetRisk,resetInterval; public Integer seedMaybe; public Parameters(Class<?> mainClass, int number, float minR, float maxR, float completeR, float maxTime, float resetRisk, float resetInterval) { this(mainClass,number,minR,maxR,completeR,maxTime,resetRisk,resetInterval,null); } public Parameters(Class<?> mainClass, int number, float minR, float maxR, float completeR, float maxTime, float resetRisk, float resetInterval, Integer seed) { super(mainClass); this.number = number; this.minR = minR; this.maxR = maxR; this.completeR = completeR; this.maxTime = maxTime; this.resetRisk = resetRisk; this.resetInterval = resetInterval; this.seedMaybe = seed; } public String toString() { NumberFormat formatter = new DecimalFormat("0000"); return (super.mainClass==null?"_":super.mainClass.getName())+"#"+formatter.format(number)+":minR="+minR+",maxR="+maxR+",comR="+completeR+",maxT="+maxTime+(seedMaybe==null?",noseed":",aseed")+",rR="+resetRisk+",rI="+resetInterval; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Float.floatToIntBits(completeR); result = prime * result + Float.floatToIntBits(maxR); result = prime * result + Float.floatToIntBits(maxTime); result = prime * result + Float.floatToIntBits(minR); result = prime * result + number; result = prime * result + Float.floatToIntBits(resetInterval); result = prime * result + Float.floatToIntBits(resetRisk); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; Parameters other = (Parameters) obj; if (Float.floatToIntBits(completeR) != Float .floatToIntBits(other.completeR)) return false; if (Float.floatToIntBits(maxR) != Float.floatToIntBits(other.maxR)) return false; if (Float.floatToIntBits(maxTime) != Float .floatToIntBits(other.maxTime)) return false; if (Float.floatToIntBits(minR) != Float.floatToIntBits(other.minR)) return false; if (number != other.number) return false; if (Float.floatToIntBits(resetInterval) != Float .floatToIntBits(other.resetInterval)) return false; if (Float.floatToIntBits(resetRisk) != Float .floatToIntBits(other.resetRisk)) return false; return true; } } private List<ParameterHolder> parameters = new LinkedList<ParameterHolder>(); private List<Class<? extends EightToCarRobustnessExperiment>> experiments = new ArrayList<Class<? extends EightToCarRobustnessExperiment>>(); private PrintWriter logfile; public static void main(String argv[]) { new EightToCarRobustnessBatch(EightToCarSettings.EXPERIMENTS).start(EightToCarSettings.N_PARALLEL_SIMS); } private int sequenceIndex = -1; private List<Integer> randomSequence = new ArrayList<Integer>(); private Random sequenceRandomizer = new Random(87); private void resetRandomSequence() { sequenceIndex = 0; } private int nextRandomFromSequence() { while(sequenceIndex>=randomSequence.size()) randomSequence.add(sequenceRandomizer.nextInt()); return randomSequence.get(sequenceIndex++); } public EightToCarRobustnessBatch(Class<?>[] mainClasses) { int counter = 0; for(int ci=0; ci<mainClasses.length; ci++) { // Efficiency experiments, 0% failure risk, varying packet loss if(!EightToCarSettings.SKIP_EFFICIENCY) for(float risk = EightToCarSettings.START_RISK; risk<=EightToCarSettings.END_RISK; risk+=EightToCarSettings.RISK_INC) { for(int i=0; i<EightToCarSettings.N_REPEAT; i++) { parameters.add(new EightToCarRobustnessBatch.Parameters(mainClasses[ci],counter,Math.max(0, risk-EightToCarSettings.RISK_DELTA),risk,0,EightToCarSettings.TIMEOUT,0,0)); } counter++; } // Robustness experiments, varying failure risk, no packet loss if(!EightToCarSettings.SKIP_ROBUSTNESS) for(float fail = EightToCarSettings.START_FAIL; fail<=EightToCarSettings.END_FAIL; fail+=EightToCarSettings.FAIL_INC) { resetRandomSequence(); for(int i=0; i<EightToCarSettings.N_REPEAT; i++) { parameters.add(new EightToCarRobustnessBatch.Parameters(mainClasses[ci],counter,0,0,fail,EightToCarSettings.TIMEOUT,0,0,nextRandomFromSequence())); } counter++; } if(!EightToCarSettings.SKIP_RESET) for(float interval = EightToCarSettings.RESET_RISK_TS_SIZE_MIN; interval<=EightToCarSettings.RESET_RISK_TS_SIZE_MAX; interval+=EightToCarSettings.RESET_RISK_TS_SIZE_DELTA) - for(float reset = EightToCarSettings.RESET_RISK_PER_TS_MIN; interval<=EightToCarSettings.RESET_RISK_PER_TS_MAX; interval+=EightToCarSettings.RESET_RISK_PER_TS_DELTA) { + for(float reset = EightToCarSettings.RESET_RISK_PER_TS_MIN; reset<=EightToCarSettings.RESET_RISK_PER_TS_MAX; reset+=EightToCarSettings.RESET_RISK_PER_TS_DELTA) { for(int i=0; i<EightToCarSettings.N_REPEAT; i++) parameters.add(new Parameters(mainClasses[ci],counter,0,0,0,EightToCarSettings.TIMEOUT,reset,interval)); counter++; } } try { logfile = new PrintWriter(new BufferedWriter(new FileWriter("eight-log.txt"))); } catch(IOException exn) { throw new Error("Unable to open log file"); } logfile.println("Starting "+parameters.size()+" experiments"); } @Override protected ParameterHolder getNextParameters() { logfile.println("experiment "+parameters.get(0)+" starting"); logfile.flush(); return parameters.remove(0); } @Override protected boolean runMoreSimulations() { return parameters.size()>0; } public void provideReturnValue(String experiment, String name, Object value) throws RemoteException { logfile.print("experiment "+experiment+" completed: "); if(name.equals("success")) { float time = (Float)value; logfile.println("Time taken:"+time); recordSuccess(experiment,time); } else if(name.equals("timeout")) { logfile.println("Timeout:X"); recordFailure(experiment); } else { logfile.println("Unknown value: "+name); recordFailure(experiment); } logfile.flush(); } @Override protected void reportHook(Set<String> experimentsNames, Map<String, List<Float>> successes, Map<String, Integer> failures, Map<String, ParameterHolder> experimentParameters) { } }
true
true
public EightToCarRobustnessBatch(Class<?>[] mainClasses) { int counter = 0; for(int ci=0; ci<mainClasses.length; ci++) { // Efficiency experiments, 0% failure risk, varying packet loss if(!EightToCarSettings.SKIP_EFFICIENCY) for(float risk = EightToCarSettings.START_RISK; risk<=EightToCarSettings.END_RISK; risk+=EightToCarSettings.RISK_INC) { for(int i=0; i<EightToCarSettings.N_REPEAT; i++) { parameters.add(new EightToCarRobustnessBatch.Parameters(mainClasses[ci],counter,Math.max(0, risk-EightToCarSettings.RISK_DELTA),risk,0,EightToCarSettings.TIMEOUT,0,0)); } counter++; } // Robustness experiments, varying failure risk, no packet loss if(!EightToCarSettings.SKIP_ROBUSTNESS) for(float fail = EightToCarSettings.START_FAIL; fail<=EightToCarSettings.END_FAIL; fail+=EightToCarSettings.FAIL_INC) { resetRandomSequence(); for(int i=0; i<EightToCarSettings.N_REPEAT; i++) { parameters.add(new EightToCarRobustnessBatch.Parameters(mainClasses[ci],counter,0,0,fail,EightToCarSettings.TIMEOUT,0,0,nextRandomFromSequence())); } counter++; } if(!EightToCarSettings.SKIP_RESET) for(float interval = EightToCarSettings.RESET_RISK_TS_SIZE_MIN; interval<=EightToCarSettings.RESET_RISK_TS_SIZE_MAX; interval+=EightToCarSettings.RESET_RISK_TS_SIZE_DELTA) for(float reset = EightToCarSettings.RESET_RISK_PER_TS_MIN; interval<=EightToCarSettings.RESET_RISK_PER_TS_MAX; interval+=EightToCarSettings.RESET_RISK_PER_TS_DELTA) { for(int i=0; i<EightToCarSettings.N_REPEAT; i++) parameters.add(new Parameters(mainClasses[ci],counter,0,0,0,EightToCarSettings.TIMEOUT,reset,interval)); counter++; } } try { logfile = new PrintWriter(new BufferedWriter(new FileWriter("eight-log.txt"))); } catch(IOException exn) { throw new Error("Unable to open log file"); } logfile.println("Starting "+parameters.size()+" experiments"); }
public EightToCarRobustnessBatch(Class<?>[] mainClasses) { int counter = 0; for(int ci=0; ci<mainClasses.length; ci++) { // Efficiency experiments, 0% failure risk, varying packet loss if(!EightToCarSettings.SKIP_EFFICIENCY) for(float risk = EightToCarSettings.START_RISK; risk<=EightToCarSettings.END_RISK; risk+=EightToCarSettings.RISK_INC) { for(int i=0; i<EightToCarSettings.N_REPEAT; i++) { parameters.add(new EightToCarRobustnessBatch.Parameters(mainClasses[ci],counter,Math.max(0, risk-EightToCarSettings.RISK_DELTA),risk,0,EightToCarSettings.TIMEOUT,0,0)); } counter++; } // Robustness experiments, varying failure risk, no packet loss if(!EightToCarSettings.SKIP_ROBUSTNESS) for(float fail = EightToCarSettings.START_FAIL; fail<=EightToCarSettings.END_FAIL; fail+=EightToCarSettings.FAIL_INC) { resetRandomSequence(); for(int i=0; i<EightToCarSettings.N_REPEAT; i++) { parameters.add(new EightToCarRobustnessBatch.Parameters(mainClasses[ci],counter,0,0,fail,EightToCarSettings.TIMEOUT,0,0,nextRandomFromSequence())); } counter++; } if(!EightToCarSettings.SKIP_RESET) for(float interval = EightToCarSettings.RESET_RISK_TS_SIZE_MIN; interval<=EightToCarSettings.RESET_RISK_TS_SIZE_MAX; interval+=EightToCarSettings.RESET_RISK_TS_SIZE_DELTA) for(float reset = EightToCarSettings.RESET_RISK_PER_TS_MIN; reset<=EightToCarSettings.RESET_RISK_PER_TS_MAX; reset+=EightToCarSettings.RESET_RISK_PER_TS_DELTA) { for(int i=0; i<EightToCarSettings.N_REPEAT; i++) parameters.add(new Parameters(mainClasses[ci],counter,0,0,0,EightToCarSettings.TIMEOUT,reset,interval)); counter++; } } try { logfile = new PrintWriter(new BufferedWriter(new FileWriter("eight-log.txt"))); } catch(IOException exn) { throw new Error("Unable to open log file"); } logfile.println("Starting "+parameters.size()+" experiments"); }
diff --git a/src/main/java/org/elasticsearch/index/query/TermsFilterParser.java b/src/main/java/org/elasticsearch/index/query/TermsFilterParser.java index 4917f64dfaa..520e1f2d470 100644 --- a/src/main/java/org/elasticsearch/index/query/TermsFilterParser.java +++ b/src/main/java/org/elasticsearch/index/query/TermsFilterParser.java @@ -1,307 +1,310 @@ /* * Licensed to ElasticSearch and Shay Banon 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.query; import com.google.common.collect.Lists; import org.apache.lucene.index.Term; import org.apache.lucene.queries.TermsFilter; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.Filter; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.BytesRefs; import org.elasticsearch.common.lucene.search.*; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.cache.filter.support.CacheKeyFilter; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.indices.cache.filter.terms.IndicesTermsFilterCache; import org.elasticsearch.indices.cache.filter.terms.TermsLookup; import java.io.IOException; import java.util.List; import static org.elasticsearch.index.query.support.QueryParsers.wrapSmartNameFilter; /** * */ public class TermsFilterParser implements FilterParser { public static final String NAME = "terms"; private IndicesTermsFilterCache termsFilterCache; @Inject public TermsFilterParser() { } @Override public String[] names() { return new String[]{NAME, "in"}; } @Inject(optional = true) public void setIndicesTermsFilterCache(IndicesTermsFilterCache termsFilterCache) { this.termsFilterCache = termsFilterCache; } @Override public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); MapperService.SmartNameFieldMappers smartNameFieldMappers; Boolean cache = null; String filterName = null; String currentFieldName = null; String lookupIndex = parseContext.index().name(); String lookupType = null; String lookupId = null; String lookupPath = null; CacheKeyFilter.Key cacheKey = null; XContentParser.Token token; String execution = "plain"; List<Object> terms = Lists.newArrayList(); String fieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { fieldName = currentFieldName; while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { Object value = parser.objectBytes(); if (value == null) { throw new QueryParsingException(parseContext.index(), "No value specified for terms filter"); } terms.add(value); } } else if (token == XContentParser.Token.START_OBJECT) { fieldName = currentFieldName; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token.isValue()) { if ("index".equals(currentFieldName)) { lookupIndex = parser.text(); } else if ("type".equals(currentFieldName)) { lookupType = parser.text(); } else if ("id".equals(currentFieldName)) { lookupId = parser.text(); } else if ("path".equals(currentFieldName)) { lookupPath = parser.text(); } else { throw new QueryParsingException(parseContext.index(), "[terms] filter does not support [" + currentFieldName + "] within lookup element"); } } } if (lookupType == null) { throw new QueryParsingException(parseContext.index(), "[terms] filter lookup element requires specifying the type"); } if (lookupId == null) { throw new QueryParsingException(parseContext.index(), "[terms] filter lookup element requires specifying the id"); } if (lookupPath == null) { throw new QueryParsingException(parseContext.index(), "[terms] filter lookup element requires specifying the path"); } } else if (token.isValue()) { if ("execution".equals(currentFieldName)) { execution = parser.text(); } else if ("_name".equals(currentFieldName)) { filterName = parser.text(); } else if ("_cache".equals(currentFieldName)) { cache = parser.booleanValue(); } else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) { cacheKey = new CacheKeyFilter.Key(parser.text()); } else { throw new QueryParsingException(parseContext.index(), "[terms] filter does not support [" + currentFieldName + "]"); } } } if (fieldName == null) { throw new QueryParsingException(parseContext.index(), "terms filter requires a field name, followed by array of terms"); } FieldMapper fieldMapper = null; smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); String[] previousTypes = null; if (smartNameFieldMappers != null) { if (smartNameFieldMappers.hasMapper()) { fieldMapper = smartNameFieldMappers.mapper(); fieldName = fieldMapper.names().indexName(); } // if we have a doc mapper, its explicit type, mark it if (smartNameFieldMappers.explicitTypeInNameWithDocMapper()) { previousTypes = QueryParseContext.setTypesWithPrevious(new String[]{smartNameFieldMappers.docMapper().type()}); } } if (lookupId != null) { // if there are no mappings, then nothing has been indexing yet against this shard, so we can return // no match (but not cached!), since the Terms Lookup relies on the fact that there are mappings... if (fieldMapper == null) { return Queries.MATCH_NO_FILTER; } // external lookup, use it TermsLookup termsLookup = new TermsLookup(fieldMapper, lookupIndex, lookupType, lookupId, lookupPath, parseContext); if (cacheKey == null) { cacheKey = new CacheKeyFilter.Key(termsLookup.toString()); } Filter filter = termsFilterCache.lookupTermsFilter(cacheKey, termsLookup); - filter = parseContext.cacheFilter(filter, null); // cacheKey is passed as null, so we don't double cache the key + // cache the whole filter by default, or if explicitly told to + if (cache == null || cache) { + filter = parseContext.cacheFilter(filter, null); // cacheKey is passed as null, so we don't double cache the key + } return filter; } if (terms.isEmpty()) { return Queries.MATCH_NO_FILTER; } try { Filter filter; if ("plain".equals(execution)) { if (fieldMapper != null) { filter = fieldMapper.termsFilter(terms, parseContext); } else { BytesRef[] filterValues = new BytesRef[terms.size()]; for (int i = 0; i < filterValues.length; i++) { filterValues[i] = BytesRefs.toBytesRef(terms.get(i)); } filter = new TermsFilter(fieldName, filterValues); } // cache the whole filter by default, or if explicitly told to if (cache == null || cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("bool".equals(execution)) { XBooleanFilter boolFiler = new XBooleanFilter(); if (fieldMapper != null) { for (Object term : terms) { boolFiler.add(parseContext.cacheFilter(fieldMapper.termFilter(term, parseContext), null), BooleanClause.Occur.SHOULD); } } else { for (Object term : terms) { boolFiler.add(parseContext.cacheFilter(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term))), null), BooleanClause.Occur.SHOULD); } } filter = boolFiler; // only cache if explicitly told to, since we cache inner filters if (cache != null && cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("bool_nocache".equals(execution)) { XBooleanFilter boolFiler = new XBooleanFilter(); if (fieldMapper != null) { for (Object term : terms) { boolFiler.add(fieldMapper.termFilter(term, parseContext), BooleanClause.Occur.SHOULD); } } else { for (Object term : terms) { boolFiler.add(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term))), BooleanClause.Occur.SHOULD); } } filter = boolFiler; // cache the whole filter by default, or if explicitly told to if (cache == null || cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("and".equals(execution)) { List<Filter> filters = Lists.newArrayList(); if (fieldMapper != null) { for (Object term : terms) { filters.add(parseContext.cacheFilter(fieldMapper.termFilter(term, parseContext), null)); } } else { for (Object term : terms) { filters.add(parseContext.cacheFilter(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term))), null)); } } filter = new AndFilter(filters); // only cache if explicitly told to, since we cache inner filters if (cache != null && cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("and_nocache".equals(execution)) { List<Filter> filters = Lists.newArrayList(); if (fieldMapper != null) { for (Object term : terms) { filters.add(fieldMapper.termFilter(term, parseContext)); } } else { for (Object term : terms) { filters.add(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term)))); } } filter = new AndFilter(filters); // cache the whole filter by default, or if explicitly told to if (cache == null || cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("or".equals(execution)) { List<Filter> filters = Lists.newArrayList(); if (fieldMapper != null) { for (Object term : terms) { filters.add(parseContext.cacheFilter(fieldMapper.termFilter(term, parseContext), null)); } } else { for (Object term : terms) { filters.add(parseContext.cacheFilter(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term))), null)); } } filter = new OrFilter(filters); // only cache if explicitly told to, since we cache inner filters if (cache != null && cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("or_nocache".equals(execution)) { List<Filter> filters = Lists.newArrayList(); if (fieldMapper != null) { for (Object term : terms) { filters.add(fieldMapper.termFilter(term, parseContext)); } } else { for (Object term : terms) { filters.add(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term)))); } } filter = new OrFilter(filters); // cache the whole filter by default, or if explicitly told to if (cache == null || cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else { throw new QueryParsingException(parseContext.index(), "bool filter execution value [" + execution + "] not supported"); } filter = wrapSmartNameFilter(filter, smartNameFieldMappers, parseContext); if (filterName != null) { parseContext.addNamedFilter(filterName, filter); } return filter; } finally { if (smartNameFieldMappers != null && smartNameFieldMappers.explicitTypeInNameWithDocMapper()) { QueryParseContext.setTypes(previousTypes); } } } }
true
true
public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); MapperService.SmartNameFieldMappers smartNameFieldMappers; Boolean cache = null; String filterName = null; String currentFieldName = null; String lookupIndex = parseContext.index().name(); String lookupType = null; String lookupId = null; String lookupPath = null; CacheKeyFilter.Key cacheKey = null; XContentParser.Token token; String execution = "plain"; List<Object> terms = Lists.newArrayList(); String fieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { fieldName = currentFieldName; while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { Object value = parser.objectBytes(); if (value == null) { throw new QueryParsingException(parseContext.index(), "No value specified for terms filter"); } terms.add(value); } } else if (token == XContentParser.Token.START_OBJECT) { fieldName = currentFieldName; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token.isValue()) { if ("index".equals(currentFieldName)) { lookupIndex = parser.text(); } else if ("type".equals(currentFieldName)) { lookupType = parser.text(); } else if ("id".equals(currentFieldName)) { lookupId = parser.text(); } else if ("path".equals(currentFieldName)) { lookupPath = parser.text(); } else { throw new QueryParsingException(parseContext.index(), "[terms] filter does not support [" + currentFieldName + "] within lookup element"); } } } if (lookupType == null) { throw new QueryParsingException(parseContext.index(), "[terms] filter lookup element requires specifying the type"); } if (lookupId == null) { throw new QueryParsingException(parseContext.index(), "[terms] filter lookup element requires specifying the id"); } if (lookupPath == null) { throw new QueryParsingException(parseContext.index(), "[terms] filter lookup element requires specifying the path"); } } else if (token.isValue()) { if ("execution".equals(currentFieldName)) { execution = parser.text(); } else if ("_name".equals(currentFieldName)) { filterName = parser.text(); } else if ("_cache".equals(currentFieldName)) { cache = parser.booleanValue(); } else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) { cacheKey = new CacheKeyFilter.Key(parser.text()); } else { throw new QueryParsingException(parseContext.index(), "[terms] filter does not support [" + currentFieldName + "]"); } } } if (fieldName == null) { throw new QueryParsingException(parseContext.index(), "terms filter requires a field name, followed by array of terms"); } FieldMapper fieldMapper = null; smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); String[] previousTypes = null; if (smartNameFieldMappers != null) { if (smartNameFieldMappers.hasMapper()) { fieldMapper = smartNameFieldMappers.mapper(); fieldName = fieldMapper.names().indexName(); } // if we have a doc mapper, its explicit type, mark it if (smartNameFieldMappers.explicitTypeInNameWithDocMapper()) { previousTypes = QueryParseContext.setTypesWithPrevious(new String[]{smartNameFieldMappers.docMapper().type()}); } } if (lookupId != null) { // if there are no mappings, then nothing has been indexing yet against this shard, so we can return // no match (but not cached!), since the Terms Lookup relies on the fact that there are mappings... if (fieldMapper == null) { return Queries.MATCH_NO_FILTER; } // external lookup, use it TermsLookup termsLookup = new TermsLookup(fieldMapper, lookupIndex, lookupType, lookupId, lookupPath, parseContext); if (cacheKey == null) { cacheKey = new CacheKeyFilter.Key(termsLookup.toString()); } Filter filter = termsFilterCache.lookupTermsFilter(cacheKey, termsLookup); filter = parseContext.cacheFilter(filter, null); // cacheKey is passed as null, so we don't double cache the key return filter; } if (terms.isEmpty()) { return Queries.MATCH_NO_FILTER; } try { Filter filter; if ("plain".equals(execution)) { if (fieldMapper != null) { filter = fieldMapper.termsFilter(terms, parseContext); } else { BytesRef[] filterValues = new BytesRef[terms.size()]; for (int i = 0; i < filterValues.length; i++) { filterValues[i] = BytesRefs.toBytesRef(terms.get(i)); } filter = new TermsFilter(fieldName, filterValues); } // cache the whole filter by default, or if explicitly told to if (cache == null || cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("bool".equals(execution)) { XBooleanFilter boolFiler = new XBooleanFilter(); if (fieldMapper != null) { for (Object term : terms) { boolFiler.add(parseContext.cacheFilter(fieldMapper.termFilter(term, parseContext), null), BooleanClause.Occur.SHOULD); } } else { for (Object term : terms) { boolFiler.add(parseContext.cacheFilter(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term))), null), BooleanClause.Occur.SHOULD); } } filter = boolFiler; // only cache if explicitly told to, since we cache inner filters if (cache != null && cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("bool_nocache".equals(execution)) { XBooleanFilter boolFiler = new XBooleanFilter(); if (fieldMapper != null) { for (Object term : terms) { boolFiler.add(fieldMapper.termFilter(term, parseContext), BooleanClause.Occur.SHOULD); } } else { for (Object term : terms) { boolFiler.add(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term))), BooleanClause.Occur.SHOULD); } } filter = boolFiler; // cache the whole filter by default, or if explicitly told to if (cache == null || cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("and".equals(execution)) { List<Filter> filters = Lists.newArrayList(); if (fieldMapper != null) { for (Object term : terms) { filters.add(parseContext.cacheFilter(fieldMapper.termFilter(term, parseContext), null)); } } else { for (Object term : terms) { filters.add(parseContext.cacheFilter(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term))), null)); } } filter = new AndFilter(filters); // only cache if explicitly told to, since we cache inner filters if (cache != null && cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("and_nocache".equals(execution)) { List<Filter> filters = Lists.newArrayList(); if (fieldMapper != null) { for (Object term : terms) { filters.add(fieldMapper.termFilter(term, parseContext)); } } else { for (Object term : terms) { filters.add(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term)))); } } filter = new AndFilter(filters); // cache the whole filter by default, or if explicitly told to if (cache == null || cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("or".equals(execution)) { List<Filter> filters = Lists.newArrayList(); if (fieldMapper != null) { for (Object term : terms) { filters.add(parseContext.cacheFilter(fieldMapper.termFilter(term, parseContext), null)); } } else { for (Object term : terms) { filters.add(parseContext.cacheFilter(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term))), null)); } } filter = new OrFilter(filters); // only cache if explicitly told to, since we cache inner filters if (cache != null && cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("or_nocache".equals(execution)) { List<Filter> filters = Lists.newArrayList(); if (fieldMapper != null) { for (Object term : terms) { filters.add(fieldMapper.termFilter(term, parseContext)); } } else { for (Object term : terms) { filters.add(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term)))); } } filter = new OrFilter(filters); // cache the whole filter by default, or if explicitly told to if (cache == null || cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else { throw new QueryParsingException(parseContext.index(), "bool filter execution value [" + execution + "] not supported"); } filter = wrapSmartNameFilter(filter, smartNameFieldMappers, parseContext); if (filterName != null) { parseContext.addNamedFilter(filterName, filter); } return filter; } finally { if (smartNameFieldMappers != null && smartNameFieldMappers.explicitTypeInNameWithDocMapper()) { QueryParseContext.setTypes(previousTypes); } } }
public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); MapperService.SmartNameFieldMappers smartNameFieldMappers; Boolean cache = null; String filterName = null; String currentFieldName = null; String lookupIndex = parseContext.index().name(); String lookupType = null; String lookupId = null; String lookupPath = null; CacheKeyFilter.Key cacheKey = null; XContentParser.Token token; String execution = "plain"; List<Object> terms = Lists.newArrayList(); String fieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { fieldName = currentFieldName; while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { Object value = parser.objectBytes(); if (value == null) { throw new QueryParsingException(parseContext.index(), "No value specified for terms filter"); } terms.add(value); } } else if (token == XContentParser.Token.START_OBJECT) { fieldName = currentFieldName; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token.isValue()) { if ("index".equals(currentFieldName)) { lookupIndex = parser.text(); } else if ("type".equals(currentFieldName)) { lookupType = parser.text(); } else if ("id".equals(currentFieldName)) { lookupId = parser.text(); } else if ("path".equals(currentFieldName)) { lookupPath = parser.text(); } else { throw new QueryParsingException(parseContext.index(), "[terms] filter does not support [" + currentFieldName + "] within lookup element"); } } } if (lookupType == null) { throw new QueryParsingException(parseContext.index(), "[terms] filter lookup element requires specifying the type"); } if (lookupId == null) { throw new QueryParsingException(parseContext.index(), "[terms] filter lookup element requires specifying the id"); } if (lookupPath == null) { throw new QueryParsingException(parseContext.index(), "[terms] filter lookup element requires specifying the path"); } } else if (token.isValue()) { if ("execution".equals(currentFieldName)) { execution = parser.text(); } else if ("_name".equals(currentFieldName)) { filterName = parser.text(); } else if ("_cache".equals(currentFieldName)) { cache = parser.booleanValue(); } else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) { cacheKey = new CacheKeyFilter.Key(parser.text()); } else { throw new QueryParsingException(parseContext.index(), "[terms] filter does not support [" + currentFieldName + "]"); } } } if (fieldName == null) { throw new QueryParsingException(parseContext.index(), "terms filter requires a field name, followed by array of terms"); } FieldMapper fieldMapper = null; smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); String[] previousTypes = null; if (smartNameFieldMappers != null) { if (smartNameFieldMappers.hasMapper()) { fieldMapper = smartNameFieldMappers.mapper(); fieldName = fieldMapper.names().indexName(); } // if we have a doc mapper, its explicit type, mark it if (smartNameFieldMappers.explicitTypeInNameWithDocMapper()) { previousTypes = QueryParseContext.setTypesWithPrevious(new String[]{smartNameFieldMappers.docMapper().type()}); } } if (lookupId != null) { // if there are no mappings, then nothing has been indexing yet against this shard, so we can return // no match (but not cached!), since the Terms Lookup relies on the fact that there are mappings... if (fieldMapper == null) { return Queries.MATCH_NO_FILTER; } // external lookup, use it TermsLookup termsLookup = new TermsLookup(fieldMapper, lookupIndex, lookupType, lookupId, lookupPath, parseContext); if (cacheKey == null) { cacheKey = new CacheKeyFilter.Key(termsLookup.toString()); } Filter filter = termsFilterCache.lookupTermsFilter(cacheKey, termsLookup); // cache the whole filter by default, or if explicitly told to if (cache == null || cache) { filter = parseContext.cacheFilter(filter, null); // cacheKey is passed as null, so we don't double cache the key } return filter; } if (terms.isEmpty()) { return Queries.MATCH_NO_FILTER; } try { Filter filter; if ("plain".equals(execution)) { if (fieldMapper != null) { filter = fieldMapper.termsFilter(terms, parseContext); } else { BytesRef[] filterValues = new BytesRef[terms.size()]; for (int i = 0; i < filterValues.length; i++) { filterValues[i] = BytesRefs.toBytesRef(terms.get(i)); } filter = new TermsFilter(fieldName, filterValues); } // cache the whole filter by default, or if explicitly told to if (cache == null || cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("bool".equals(execution)) { XBooleanFilter boolFiler = new XBooleanFilter(); if (fieldMapper != null) { for (Object term : terms) { boolFiler.add(parseContext.cacheFilter(fieldMapper.termFilter(term, parseContext), null), BooleanClause.Occur.SHOULD); } } else { for (Object term : terms) { boolFiler.add(parseContext.cacheFilter(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term))), null), BooleanClause.Occur.SHOULD); } } filter = boolFiler; // only cache if explicitly told to, since we cache inner filters if (cache != null && cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("bool_nocache".equals(execution)) { XBooleanFilter boolFiler = new XBooleanFilter(); if (fieldMapper != null) { for (Object term : terms) { boolFiler.add(fieldMapper.termFilter(term, parseContext), BooleanClause.Occur.SHOULD); } } else { for (Object term : terms) { boolFiler.add(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term))), BooleanClause.Occur.SHOULD); } } filter = boolFiler; // cache the whole filter by default, or if explicitly told to if (cache == null || cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("and".equals(execution)) { List<Filter> filters = Lists.newArrayList(); if (fieldMapper != null) { for (Object term : terms) { filters.add(parseContext.cacheFilter(fieldMapper.termFilter(term, parseContext), null)); } } else { for (Object term : terms) { filters.add(parseContext.cacheFilter(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term))), null)); } } filter = new AndFilter(filters); // only cache if explicitly told to, since we cache inner filters if (cache != null && cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("and_nocache".equals(execution)) { List<Filter> filters = Lists.newArrayList(); if (fieldMapper != null) { for (Object term : terms) { filters.add(fieldMapper.termFilter(term, parseContext)); } } else { for (Object term : terms) { filters.add(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term)))); } } filter = new AndFilter(filters); // cache the whole filter by default, or if explicitly told to if (cache == null || cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("or".equals(execution)) { List<Filter> filters = Lists.newArrayList(); if (fieldMapper != null) { for (Object term : terms) { filters.add(parseContext.cacheFilter(fieldMapper.termFilter(term, parseContext), null)); } } else { for (Object term : terms) { filters.add(parseContext.cacheFilter(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term))), null)); } } filter = new OrFilter(filters); // only cache if explicitly told to, since we cache inner filters if (cache != null && cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else if ("or_nocache".equals(execution)) { List<Filter> filters = Lists.newArrayList(); if (fieldMapper != null) { for (Object term : terms) { filters.add(fieldMapper.termFilter(term, parseContext)); } } else { for (Object term : terms) { filters.add(new TermFilter(new Term(fieldName, BytesRefs.toBytesRef(term)))); } } filter = new OrFilter(filters); // cache the whole filter by default, or if explicitly told to if (cache == null || cache) { filter = parseContext.cacheFilter(filter, cacheKey); } } else { throw new QueryParsingException(parseContext.index(), "bool filter execution value [" + execution + "] not supported"); } filter = wrapSmartNameFilter(filter, smartNameFieldMappers, parseContext); if (filterName != null) { parseContext.addNamedFilter(filterName, filter); } return filter; } finally { if (smartNameFieldMappers != null && smartNameFieldMappers.explicitTypeInNameWithDocMapper()) { QueryParseContext.setTypes(previousTypes); } } }
diff --git a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ConstructTaskOutstandingTableFromMasterTable.java b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ConstructTaskOutstandingTableFromMasterTable.java index 91c5d1e09..9bf3db85b 100644 --- a/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ConstructTaskOutstandingTableFromMasterTable.java +++ b/astrid/plugin-src/com/todoroo/astrid/actfm/sync/messages/ConstructTaskOutstandingTableFromMasterTable.java @@ -1,48 +1,50 @@ package com.todoroo.astrid.actfm.sync.messages; import com.todoroo.andlib.data.Property.LongProperty; import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.andlib.sql.Criterion; import com.todoroo.andlib.sql.Query; import com.todoroo.astrid.dao.MetadataDao; import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria; import com.todoroo.astrid.dao.OutstandingEntryDao; import com.todoroo.astrid.dao.RemoteModelDao; import com.todoroo.astrid.data.Metadata; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.data.TaskOutstanding; import com.todoroo.astrid.tags.TaskToTagMetadata; public class ConstructTaskOutstandingTableFromMasterTable extends ConstructOutstandingTableFromMasterTable<Task, TaskOutstanding> { private final MetadataDao metadataDao; public ConstructTaskOutstandingTableFromMasterTable(String table, RemoteModelDao<Task> dao, OutstandingEntryDao<TaskOutstanding> outstandingDao, MetadataDao metadataDao, LongProperty createdAtProperty) { super(table, dao, outstandingDao, createdAtProperty); this.metadataDao = metadataDao; } @Override protected void extras(long itemId, long createdAt) { super.extras(itemId, createdAt); TodorooCursor<Metadata> tagMetadata = metadataDao.query(Query.select(Metadata.PROPERTIES) .where(Criterion.and(MetadataCriteria.byTaskAndwithKey(itemId, TaskToTagMetadata.KEY), Metadata.DELETION_DATE.eq(0)))); Metadata m = new Metadata(); try { for (tagMetadata.moveToFirst(); !tagMetadata.isAfterLast(); tagMetadata.moveToNext()) { m.clear(); m.readFromCursor(tagMetadata); - TaskOutstanding oe = new TaskOutstanding(); - oe.setValue(TaskOutstanding.ENTITY_ID_PROPERTY, itemId); - oe.setValue(TaskOutstanding.COLUMN_STRING, NameMaps.TAG_ADDED_COLUMN); - oe.setValue(TaskOutstanding.VALUE_STRING, m.getValue(TaskToTagMetadata.TAG_UUID)); - oe.setValue(TaskOutstanding.CREATED_AT, createdAt); - outstandingDao.createNew(oe); + if (m.containsNonNullValue(TaskToTagMetadata.TAG_UUID)) { + TaskOutstanding oe = new TaskOutstanding(); + oe.setValue(TaskOutstanding.ENTITY_ID_PROPERTY, itemId); + oe.setValue(TaskOutstanding.COLUMN_STRING, NameMaps.TAG_ADDED_COLUMN); + oe.setValue(TaskOutstanding.VALUE_STRING, m.getValue(TaskToTagMetadata.TAG_UUID)); + oe.setValue(TaskOutstanding.CREATED_AT, createdAt); + outstandingDao.createNew(oe); + } } } finally { tagMetadata.close(); } } }
true
true
protected void extras(long itemId, long createdAt) { super.extras(itemId, createdAt); TodorooCursor<Metadata> tagMetadata = metadataDao.query(Query.select(Metadata.PROPERTIES) .where(Criterion.and(MetadataCriteria.byTaskAndwithKey(itemId, TaskToTagMetadata.KEY), Metadata.DELETION_DATE.eq(0)))); Metadata m = new Metadata(); try { for (tagMetadata.moveToFirst(); !tagMetadata.isAfterLast(); tagMetadata.moveToNext()) { m.clear(); m.readFromCursor(tagMetadata); TaskOutstanding oe = new TaskOutstanding(); oe.setValue(TaskOutstanding.ENTITY_ID_PROPERTY, itemId); oe.setValue(TaskOutstanding.COLUMN_STRING, NameMaps.TAG_ADDED_COLUMN); oe.setValue(TaskOutstanding.VALUE_STRING, m.getValue(TaskToTagMetadata.TAG_UUID)); oe.setValue(TaskOutstanding.CREATED_AT, createdAt); outstandingDao.createNew(oe); } } finally { tagMetadata.close(); } }
protected void extras(long itemId, long createdAt) { super.extras(itemId, createdAt); TodorooCursor<Metadata> tagMetadata = metadataDao.query(Query.select(Metadata.PROPERTIES) .where(Criterion.and(MetadataCriteria.byTaskAndwithKey(itemId, TaskToTagMetadata.KEY), Metadata.DELETION_DATE.eq(0)))); Metadata m = new Metadata(); try { for (tagMetadata.moveToFirst(); !tagMetadata.isAfterLast(); tagMetadata.moveToNext()) { m.clear(); m.readFromCursor(tagMetadata); if (m.containsNonNullValue(TaskToTagMetadata.TAG_UUID)) { TaskOutstanding oe = new TaskOutstanding(); oe.setValue(TaskOutstanding.ENTITY_ID_PROPERTY, itemId); oe.setValue(TaskOutstanding.COLUMN_STRING, NameMaps.TAG_ADDED_COLUMN); oe.setValue(TaskOutstanding.VALUE_STRING, m.getValue(TaskToTagMetadata.TAG_UUID)); oe.setValue(TaskOutstanding.CREATED_AT, createdAt); outstandingDao.createNew(oe); } } } finally { tagMetadata.close(); } }
diff --git a/src/mainpackage/mysql/Retrieve.java b/src/mainpackage/mysql/Retrieve.java index 094322e..aebb2bd 100644 --- a/src/mainpackage/mysql/Retrieve.java +++ b/src/mainpackage/mysql/Retrieve.java @@ -1,141 +1,140 @@ package mainpackage.mysql; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import mainpackage.AccountItem; public class Retrieve { /** * @param args */ private static List<RecurringItem> resultSetRA = new ArrayList<RecurringItem>(); private RecurringItem item; public List<RecurringItem> getResultSetRA() { return this.resultSetRA; } public void upcomingActivityRetrieveMySQL() { Connection connection = null; PreparedStatement pStatement = null; ResultSet resultSet = null; Properties props = new Properties(); FileInputStream inStream = null; try { inStream = new FileInputStream("/usr/local/mysql/database.properties"); props.load(inStream); } catch(FileNotFoundException fe) { Logger lgr = Logger.getLogger(Retrieve.class.getName()); lgr.log(Level.SEVERE, fe.getMessage(), fe); } catch (IOException ie) { Logger lgr = Logger.getLogger(Retrieve.class.getName()); lgr.log(Level.SEVERE, ie.getMessage(), ie); } finally { try { if(inStream != null) { inStream.close(); } } catch(IOException ie) { Logger lgr = Logger.getLogger(Retrieve.class.getName()); lgr.log(Level.SEVERE, ie.getMessage(), ie); } } String url = props.getProperty("db.url"); String user = props.getProperty("db.user"); String passwd = props.getProperty("db.passwd"); //Above block sets up MySQL connection //Following runs SQL commands try { connection = DriverManager.getConnection(url, user, passwd); pStatement = connection.prepareStatement("SELECT date, ActivityName, Amount, " + - "ActivityDate FROM calendar_table, Activities WHERE " + + "ActivityDate, Frequency, TypeInt FROM calendar_table, Activities WHERE " + "calendar_table.day=Activities.ActivityDate AND calendar_table.date " + "BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 2 WEEK);"); resultSet = pStatement.executeQuery(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); while(resultSet.next()) { - item = new RecurringItem(resultSet.getString(2), Double.parseDouble(resultSet.getString(3)), - (Date)df.parse(resultSet.getString(1)), "Bill", 0); + item = new RecurringItem(resultSet.getString(2), + Double.parseDouble(resultSet.getString(3)), + Integer.parseInt(resultSet.getString(1)), + Integer.parseInt(resultSet.getString(4)), + Integer.parseInt(resultSet.getString(5))); resultSetRA.add(item); } } catch(SQLException sqlEx) { Logger logger = Logger.getLogger(Retrieve.class.getName()); logger.log(Level.SEVERE, sqlEx.getMessage(), sqlEx); } catch (NumberFormatException e) { e.printStackTrace(); - } - catch (ParseException e) - { - e.printStackTrace(); } finally { try { if(resultSet != null) { resultSet.close(); } if(pStatement != null) { pStatement.close(); } if(connection != null) { connection.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Retrieve.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } } } }
false
true
public void upcomingActivityRetrieveMySQL() { Connection connection = null; PreparedStatement pStatement = null; ResultSet resultSet = null; Properties props = new Properties(); FileInputStream inStream = null; try { inStream = new FileInputStream("/usr/local/mysql/database.properties"); props.load(inStream); } catch(FileNotFoundException fe) { Logger lgr = Logger.getLogger(Retrieve.class.getName()); lgr.log(Level.SEVERE, fe.getMessage(), fe); } catch (IOException ie) { Logger lgr = Logger.getLogger(Retrieve.class.getName()); lgr.log(Level.SEVERE, ie.getMessage(), ie); } finally { try { if(inStream != null) { inStream.close(); } } catch(IOException ie) { Logger lgr = Logger.getLogger(Retrieve.class.getName()); lgr.log(Level.SEVERE, ie.getMessage(), ie); } } String url = props.getProperty("db.url"); String user = props.getProperty("db.user"); String passwd = props.getProperty("db.passwd"); //Above block sets up MySQL connection //Following runs SQL commands try { connection = DriverManager.getConnection(url, user, passwd); pStatement = connection.prepareStatement("SELECT date, ActivityName, Amount, " + "ActivityDate FROM calendar_table, Activities WHERE " + "calendar_table.day=Activities.ActivityDate AND calendar_table.date " + "BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 2 WEEK);"); resultSet = pStatement.executeQuery(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); while(resultSet.next()) { item = new RecurringItem(resultSet.getString(2), Double.parseDouble(resultSet.getString(3)), (Date)df.parse(resultSet.getString(1)), "Bill", 0); resultSetRA.add(item); } } catch(SQLException sqlEx) { Logger logger = Logger.getLogger(Retrieve.class.getName()); logger.log(Level.SEVERE, sqlEx.getMessage(), sqlEx); } catch (NumberFormatException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } finally { try { if(resultSet != null) { resultSet.close(); } if(pStatement != null) { pStatement.close(); } if(connection != null) { connection.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Retrieve.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } } }
public void upcomingActivityRetrieveMySQL() { Connection connection = null; PreparedStatement pStatement = null; ResultSet resultSet = null; Properties props = new Properties(); FileInputStream inStream = null; try { inStream = new FileInputStream("/usr/local/mysql/database.properties"); props.load(inStream); } catch(FileNotFoundException fe) { Logger lgr = Logger.getLogger(Retrieve.class.getName()); lgr.log(Level.SEVERE, fe.getMessage(), fe); } catch (IOException ie) { Logger lgr = Logger.getLogger(Retrieve.class.getName()); lgr.log(Level.SEVERE, ie.getMessage(), ie); } finally { try { if(inStream != null) { inStream.close(); } } catch(IOException ie) { Logger lgr = Logger.getLogger(Retrieve.class.getName()); lgr.log(Level.SEVERE, ie.getMessage(), ie); } } String url = props.getProperty("db.url"); String user = props.getProperty("db.user"); String passwd = props.getProperty("db.passwd"); //Above block sets up MySQL connection //Following runs SQL commands try { connection = DriverManager.getConnection(url, user, passwd); pStatement = connection.prepareStatement("SELECT date, ActivityName, Amount, " + "ActivityDate, Frequency, TypeInt FROM calendar_table, Activities WHERE " + "calendar_table.day=Activities.ActivityDate AND calendar_table.date " + "BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 2 WEEK);"); resultSet = pStatement.executeQuery(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); while(resultSet.next()) { item = new RecurringItem(resultSet.getString(2), Double.parseDouble(resultSet.getString(3)), Integer.parseInt(resultSet.getString(1)), Integer.parseInt(resultSet.getString(4)), Integer.parseInt(resultSet.getString(5))); resultSetRA.add(item); } } catch(SQLException sqlEx) { Logger logger = Logger.getLogger(Retrieve.class.getName()); logger.log(Level.SEVERE, sqlEx.getMessage(), sqlEx); } catch (NumberFormatException e) { e.printStackTrace(); } finally { try { if(resultSet != null) { resultSet.close(); } if(pStatement != null) { pStatement.close(); } if(connection != null) { connection.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Retrieve.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } } }
diff --git a/src-ai/hughai/ui/ConsoleJava.java b/src-ai/hughai/ui/ConsoleJava.java index b852bdb..c05d2f7 100644 --- a/src-ai/hughai/ui/ConsoleJava.java +++ b/src-ai/hughai/ui/ConsoleJava.java @@ -1,206 +1,224 @@ // Copyright Hugh Perkins 2009 // hughperkins@gmail.com http://manageddreams.com // // This program is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for // more details. // // You should have received a copy of the GNU General Public License along // with this program in the file licence.txt; if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111- // 1307 USA // You can find the licence also on the web at: // http://www.opensource.org/licenses/gpl-license.php // // ====================================================================================== // package hughai.ui; import java.util.*; import java.util.List; import java.util.jar.JarOutputStream; import java.util.zip.ZipEntry; import javax.activation.FileTypeMap; import javax.swing.*; import javax.script.*; import javax.xml.transform.stream.StreamResult; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.URL; import java.net.URLClassLoader; import hughai.*; import hughai.loader.utils.Loader; import hughai.utils.*; // provides a console tab to the gui that lets us execute code // on the fly! // is that wicked or wot! :-D public class ConsoleJava { final String classdir = "console-classes"; final String jarfilename = "Console.jar"; final String consoletemplatefilename = "JavaConsoleTemplate.txt"; // final String classpath="$aidir/SkirmishAI.jar:$aidir/UnderlyingAI.jar:$aidir/../../Interfaces/Java/0.1/AIInterface.jar"; // JFrame frame; JPanel textpanel; GridLayout gridLayout; JTextArea textarea; JButton gobutton; JButton quitbutton; JTextArea outputTextarea; PlayerObjects playerObjects; public ConsoleJava( PlayerObjects playerObjects ) { this.playerObjects = playerObjects; init(); } void init () { try { // frame = new JFrame("Console"); // frame.setSize( 400, 400 ); JPanel outerpanel = new JPanel(new BorderLayout()); gridLayout = new GridLayout( 2, 1 ); textpanel = new JPanel( gridLayout ); // frame.add( panel ); JPanel buttonpanel = new JPanel(new GridLayout(1,2)); outerpanel.add( "Center", textpanel ); outerpanel.add( "South", buttonpanel ); textarea = new JTextArea(); JScrollPane scrollPane = new JScrollPane( textarea ); outputTextarea = new JTextArea(); JScrollPane outputscrollpane = new JScrollPane( outputTextarea ); gobutton = new JButton( "Go" ); quitbutton = new JButton( "Quit" ); String templatepath = playerObjects.getCSAI().getAIDirectoryPath() + consoletemplatefilename; FileHelper fileHelper = new FileHelper( playerObjects ); String initialFile = fileHelper.readFile( templatepath ); if( initialFile != null ) { textarea.setText( initialFile ); } else { textarea.setText("<Missing file " + templatepath + ">" ); } gobutton.addActionListener( new GoButton() ); quitbutton.addActionListener( new QuitButton() ); textpanel.add( scrollPane ); textpanel.add( outputscrollpane ); buttonpanel.add( gobutton ); buttonpanel.add( quitbutton ); playerObjects.getMainUI().addPanelToTabbedPanel( "Java Console", outerpanel ); // frame.validate(); // frame.setVisible( true ); } catch( Exception e ) { playerObjects.getLogFile().WriteLine( Formatting.exceptionToStackTrace( e ) ); throw new RuntimeException( e ); } } // kind of hacky quick fix for linux vs Windows // there must be a better way of doing this... String localizeClassPath( String classpath ) { if( File.separator.equals("/") ) { // linux (and mac?) return classpath.replace( ";", ":" ).replace( "\\", "/" ); } else { // windows return classpath.replace( ":", ";" ).replace( "/", "\\" ); } } void debug( Object message ) { playerObjects.getLogFile().WriteLine( "" + message ); } class GoButton implements ActionListener { @Override public void actionPerformed( ActionEvent event ) { try { // String ourdir = "/home/user/persist/workspace/Test/"; String ourdir = playerObjects.getCSAI().getAIDirectoryPath(); System.out.println( textarea.getText() ); new File( ourdir + "src-console" + File.separator + "console").mkdirs(); PrintWriter printWriter = new PrintWriter( ourdir + "src-console" + File.separator + "console" + File.separator + "ConsoleText.java" ); printWriter.write( textarea.getText() ); printWriter.write( "\n" ); printWriter.close(); new File( ourdir + classdir ).mkdirs(); // Process process = // Runtime.getRuntime().exec( "bash -c pwd", null, // null ); String classpath = localizeClassPath( playerObjects.getConfig().getConsoleclasspath() ); classpath = classpath.replace( "$aidir/", ourdir ); Exec exec = new Exec( playerObjects ); - debug( exec.exec( "javac -classpath " + classpath + String result = ""; + try { + result = exec.exec( "javac -classpath " + classpath + " -d " + ourdir + classdir + " console" + File.separator + "ConsoleText.java", - ourdir + "src-console" ) ); + ourdir + "src-console" ); + debug( result ); + } catch( Exception e ) { + outputTextarea.setText( "Error during compilation: " + e.getMessage() ); + return; + } - debug( exec.exec( "jar -cf " + ourdir + jarfilename + try { + result = exec.exec( "jar -cf " + ourdir + jarfilename + " console", - ourdir + classdir ) ); + ourdir + classdir ); + debug( result ); + } catch( Exception e ) { + outputTextarea.setText( "Error during jar creation: " + e.getMessage() ); + return; + } // this should be moved to some generic class really URL[] locations = new URL[] { new File( ourdir + jarfilename ) .toURI().toURL()}; ClassLoader baseClassLoader = ConsoleJava.class.getClassLoader(); if( baseClassLoader == null ) { System.out.println("using system classloader as base"); baseClassLoader = ClassLoader.getSystemClassLoader(); } else { System.out.println("using our classloader as base"); } URLClassLoader classloader = new URLClassLoader( locations, baseClassLoader ); Class<?> cls = classloader.loadClass("console.ConsoleText"); if (!ConsoleEntryPoint.class.isAssignableFrom(cls)) { throw new RuntimeException("Invalid class"); } Object newInstance = cls.newInstance(); ConsoleEntryPoint subjar = (ConsoleEntryPoint)newInstance; - String result = subjar.go( playerObjects ); - outputTextarea.setText( result ); + try { + result = subjar.go( playerObjects ); + outputTextarea.setText( result ); + } catch( Exception e ) { + String exceptiontrace = Formatting.exceptionToStackTrace( e ); + outputTextarea.setText( exceptiontrace ); + } } catch( Exception e ) { playerObjects.getLogFile().WriteLine( Formatting.exceptionToStackTrace( e ) ); } } } class QuitButton implements ActionListener { @Override public void actionPerformed( ActionEvent event ) { System.exit(0); } } }
false
true
public void actionPerformed( ActionEvent event ) { try { // String ourdir = "/home/user/persist/workspace/Test/"; String ourdir = playerObjects.getCSAI().getAIDirectoryPath(); System.out.println( textarea.getText() ); new File( ourdir + "src-console" + File.separator + "console").mkdirs(); PrintWriter printWriter = new PrintWriter( ourdir + "src-console" + File.separator + "console" + File.separator + "ConsoleText.java" ); printWriter.write( textarea.getText() ); printWriter.write( "\n" ); printWriter.close(); new File( ourdir + classdir ).mkdirs(); // Process process = // Runtime.getRuntime().exec( "bash -c pwd", null, // null ); String classpath = localizeClassPath( playerObjects.getConfig().getConsoleclasspath() ); classpath = classpath.replace( "$aidir/", ourdir ); Exec exec = new Exec( playerObjects ); debug( exec.exec( "javac -classpath " + classpath + " -d " + ourdir + classdir + " console" + File.separator + "ConsoleText.java", ourdir + "src-console" ) ); debug( exec.exec( "jar -cf " + ourdir + jarfilename + " console", ourdir + classdir ) ); // this should be moved to some generic class really URL[] locations = new URL[] { new File( ourdir + jarfilename ) .toURI().toURL()}; ClassLoader baseClassLoader = ConsoleJava.class.getClassLoader(); if( baseClassLoader == null ) { System.out.println("using system classloader as base"); baseClassLoader = ClassLoader.getSystemClassLoader(); } else { System.out.println("using our classloader as base"); } URLClassLoader classloader = new URLClassLoader( locations, baseClassLoader ); Class<?> cls = classloader.loadClass("console.ConsoleText"); if (!ConsoleEntryPoint.class.isAssignableFrom(cls)) { throw new RuntimeException("Invalid class"); } Object newInstance = cls.newInstance(); ConsoleEntryPoint subjar = (ConsoleEntryPoint)newInstance; String result = subjar.go( playerObjects ); outputTextarea.setText( result ); } catch( Exception e ) { playerObjects.getLogFile().WriteLine( Formatting.exceptionToStackTrace( e ) ); } }
public void actionPerformed( ActionEvent event ) { try { // String ourdir = "/home/user/persist/workspace/Test/"; String ourdir = playerObjects.getCSAI().getAIDirectoryPath(); System.out.println( textarea.getText() ); new File( ourdir + "src-console" + File.separator + "console").mkdirs(); PrintWriter printWriter = new PrintWriter( ourdir + "src-console" + File.separator + "console" + File.separator + "ConsoleText.java" ); printWriter.write( textarea.getText() ); printWriter.write( "\n" ); printWriter.close(); new File( ourdir + classdir ).mkdirs(); // Process process = // Runtime.getRuntime().exec( "bash -c pwd", null, // null ); String classpath = localizeClassPath( playerObjects.getConfig().getConsoleclasspath() ); classpath = classpath.replace( "$aidir/", ourdir ); Exec exec = new Exec( playerObjects ); String result = ""; try { result = exec.exec( "javac -classpath " + classpath + " -d " + ourdir + classdir + " console" + File.separator + "ConsoleText.java", ourdir + "src-console" ); debug( result ); } catch( Exception e ) { outputTextarea.setText( "Error during compilation: " + e.getMessage() ); return; } try { result = exec.exec( "jar -cf " + ourdir + jarfilename + " console", ourdir + classdir ); debug( result ); } catch( Exception e ) { outputTextarea.setText( "Error during jar creation: " + e.getMessage() ); return; } // this should be moved to some generic class really URL[] locations = new URL[] { new File( ourdir + jarfilename ) .toURI().toURL()}; ClassLoader baseClassLoader = ConsoleJava.class.getClassLoader(); if( baseClassLoader == null ) { System.out.println("using system classloader as base"); baseClassLoader = ClassLoader.getSystemClassLoader(); } else { System.out.println("using our classloader as base"); } URLClassLoader classloader = new URLClassLoader( locations, baseClassLoader ); Class<?> cls = classloader.loadClass("console.ConsoleText"); if (!ConsoleEntryPoint.class.isAssignableFrom(cls)) { throw new RuntimeException("Invalid class"); } Object newInstance = cls.newInstance(); ConsoleEntryPoint subjar = (ConsoleEntryPoint)newInstance; try { result = subjar.go( playerObjects ); outputTextarea.setText( result ); } catch( Exception e ) { String exceptiontrace = Formatting.exceptionToStackTrace( e ); outputTextarea.setText( exceptiontrace ); } } catch( Exception e ) { playerObjects.getLogFile().WriteLine( Formatting.exceptionToStackTrace( e ) ); } }
diff --git a/src/com/example/Adapter/SolutionAdapter.java b/src/com/example/Adapter/SolutionAdapter.java index b57655c..2ef6673 100644 --- a/src/com/example/Adapter/SolutionAdapter.java +++ b/src/com/example/Adapter/SolutionAdapter.java @@ -1,85 +1,85 @@ package com.example.Adapter; import java.util.Arrays; import com.example.App.R; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class SolutionAdapter extends BaseAdapter { Context context; final static String SPACE = " "; String[] data; Integer[] tag; String sAnswer; int count = 0; public SolutionAdapter(Context c, int length) { this.context = c; this.data = new String[length]; this.tag = new Integer[length]; Arrays.fill(this.data, SPACE); } @Override public int getCount() { return data.length; } @Override public String getItem(int position) { return data[position]; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = LayoutInflater.from(context).inflate( R.layout.grid_solution, null); TextView tv = (TextView) convertView.findViewById(R.id.tvSolution); tv.setText(this.getItem(position)); tv.setTag(this.tag[position]); return convertView; } public String getAnswer() { String str = ""; for (String s : data) { str += s; } return str; } public boolean add(String w, int tagPosition) { for (int i = 0; i < data.length; i++) { + if (count == data.length) + return false; if (!w.equals("") && data[i].equals(SPACE)) { data[i] = w; count++; tag[i] = tagPosition; notifyDataSetChanged(); - if (count == data.length) - return false; return true; } } return false; } public void remove(int position) { tag[position] = null; data[position] = SPACE; count--; notifyDataSetChanged(); } }
false
true
public boolean add(String w, int tagPosition) { for (int i = 0; i < data.length; i++) { if (!w.equals("") && data[i].equals(SPACE)) { data[i] = w; count++; tag[i] = tagPosition; notifyDataSetChanged(); if (count == data.length) return false; return true; } } return false; }
public boolean add(String w, int tagPosition) { for (int i = 0; i < data.length; i++) { if (count == data.length) return false; if (!w.equals("") && data[i].equals(SPACE)) { data[i] = w; count++; tag[i] = tagPosition; notifyDataSetChanged(); return true; } } return false; }
diff --git a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JSF2ValidatorTest.java b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JSF2ValidatorTest.java index 71196d9b5..82bdde06c 100644 --- a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JSF2ValidatorTest.java +++ b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JSF2ValidatorTest.java @@ -1,57 +1,57 @@ /** * */ package org.jboss.tools.jsf.vpe.jsf.test.jbide; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.swt.custom.StyledText; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.part.FileEditorInput; import org.jboss.tools.jsf.vpe.jsf.test.JsfAllTests; import org.jboss.tools.jst.jsp.jspeditor.JSPMultiPageEditor; import org.jboss.tools.vpe.ui.test.TestUtil; import org.jboss.tools.vpe.ui.test.VpeTest; /** * JUnit test class for https://jira.jboss.org/browse/JBIDE-6965 * * @author mareshkau * */ public class JSF2ValidatorTest extends VpeTest{ private static final String MARKER_TYPE="org.jboss.tools.jsf.jsf2problemmarker"; //$NON-NLS-1$ public JSF2ValidatorTest(String name) { super(name); } public void testCAforIncludeTaglibInInenerNodes() throws Throwable { IFile file = (IFile) TestUtil.getComponentPath("JBIDE/6922/jbide6922.xhtml", //$NON-NLS-1$ JsfAllTests.IMPORT_JSF_20_PROJECT_NAME); IEditorInput input = new FileEditorInput(file); JSPMultiPageEditor multiPageEditor = openEditor(input); IMarker[] problemMarkers = file.findMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals("There shouldn't be any problems on page", 0,problemMarkers.length); //$NON-NLS-1$ StyledText styledText = multiPageEditor.getSourceEditor().getTextViewer() .getTextWidget(); int caretOffcet = TestUtil.getLinePositionOffcet(multiPageEditor.getSourceEditor().getTextViewer(), 4, 5); styledText.setCaretOffset(caretOffcet); styledText.insert("xmlns:test=\"http://java.sun.com/jsf/composite/test\""); //$NON-NLS-1$ TestUtil.delay(1200); TestUtil.waitForJobs(); problemMarkers = file.findMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals("res folder marker is expected", 1, problemMarkers.length); //$NON-NLS-1$ String message = (String) problemMarkers[0].getAttribute(IMarker.MESSAGE); - assertEquals("Error messages should be","JSF 2 Resources folder \"/resources/test\" is missing in a project root directory",message); //$NON-NLS-1$ //$NON-NLS-2$ + assertEquals("Error messages should be","JSF 2 Resources folder \"/resources/test\" is missing in a project web directory",message); //$NON-NLS-1$ //$NON-NLS-2$ caretOffcet = TestUtil.getLinePositionOffcet(multiPageEditor.getSourceEditor().getTextViewer(), 6, 1); styledText.setCaretOffset(caretOffcet); styledText.insert("<test:testElement />"); //$NON-NLS-1$ TestUtil.delay(1200); TestUtil.waitForJobs(); problemMarkers = file.findMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals("Number of markers should be",2, problemMarkers.length); //$NON-NLS-1$ } }
true
true
public void testCAforIncludeTaglibInInenerNodes() throws Throwable { IFile file = (IFile) TestUtil.getComponentPath("JBIDE/6922/jbide6922.xhtml", //$NON-NLS-1$ JsfAllTests.IMPORT_JSF_20_PROJECT_NAME); IEditorInput input = new FileEditorInput(file); JSPMultiPageEditor multiPageEditor = openEditor(input); IMarker[] problemMarkers = file.findMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals("There shouldn't be any problems on page", 0,problemMarkers.length); //$NON-NLS-1$ StyledText styledText = multiPageEditor.getSourceEditor().getTextViewer() .getTextWidget(); int caretOffcet = TestUtil.getLinePositionOffcet(multiPageEditor.getSourceEditor().getTextViewer(), 4, 5); styledText.setCaretOffset(caretOffcet); styledText.insert("xmlns:test=\"http://java.sun.com/jsf/composite/test\""); //$NON-NLS-1$ TestUtil.delay(1200); TestUtil.waitForJobs(); problemMarkers = file.findMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals("res folder marker is expected", 1, problemMarkers.length); //$NON-NLS-1$ String message = (String) problemMarkers[0].getAttribute(IMarker.MESSAGE); assertEquals("Error messages should be","JSF 2 Resources folder \"/resources/test\" is missing in a project root directory",message); //$NON-NLS-1$ //$NON-NLS-2$ caretOffcet = TestUtil.getLinePositionOffcet(multiPageEditor.getSourceEditor().getTextViewer(), 6, 1); styledText.setCaretOffset(caretOffcet); styledText.insert("<test:testElement />"); //$NON-NLS-1$ TestUtil.delay(1200); TestUtil.waitForJobs(); problemMarkers = file.findMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals("Number of markers should be",2, problemMarkers.length); //$NON-NLS-1$ }
public void testCAforIncludeTaglibInInenerNodes() throws Throwable { IFile file = (IFile) TestUtil.getComponentPath("JBIDE/6922/jbide6922.xhtml", //$NON-NLS-1$ JsfAllTests.IMPORT_JSF_20_PROJECT_NAME); IEditorInput input = new FileEditorInput(file); JSPMultiPageEditor multiPageEditor = openEditor(input); IMarker[] problemMarkers = file.findMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals("There shouldn't be any problems on page", 0,problemMarkers.length); //$NON-NLS-1$ StyledText styledText = multiPageEditor.getSourceEditor().getTextViewer() .getTextWidget(); int caretOffcet = TestUtil.getLinePositionOffcet(multiPageEditor.getSourceEditor().getTextViewer(), 4, 5); styledText.setCaretOffset(caretOffcet); styledText.insert("xmlns:test=\"http://java.sun.com/jsf/composite/test\""); //$NON-NLS-1$ TestUtil.delay(1200); TestUtil.waitForJobs(); problemMarkers = file.findMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals("res folder marker is expected", 1, problemMarkers.length); //$NON-NLS-1$ String message = (String) problemMarkers[0].getAttribute(IMarker.MESSAGE); assertEquals("Error messages should be","JSF 2 Resources folder \"/resources/test\" is missing in a project web directory",message); //$NON-NLS-1$ //$NON-NLS-2$ caretOffcet = TestUtil.getLinePositionOffcet(multiPageEditor.getSourceEditor().getTextViewer(), 6, 1); styledText.setCaretOffset(caretOffcet); styledText.insert("<test:testElement />"); //$NON-NLS-1$ TestUtil.delay(1200); TestUtil.waitForJobs(); problemMarkers = file.findMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals("Number of markers should be",2, problemMarkers.length); //$NON-NLS-1$ }
diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/Scene2dTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/Scene2dTest.java index 616443b7e..dd02234eb 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/Scene2dTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/Scene2dTest.java @@ -1,179 +1,179 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actions.FloatAction; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.VerticalGroup; import com.badlogic.gdx.scenes.scene2d.ui.Window; import com.badlogic.gdx.scenes.scene2d.utils.ActorGestureListener; import com.badlogic.gdx.scenes.scene2d.utils.TiledDrawable; import com.badlogic.gdx.tests.utils.GdxTest; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*; public class Scene2dTest extends GdxTest { Stage stage; private FloatAction meow = new FloatAction(10, 5); private TiledDrawable patch; public void create () { stage = new Stage(); Gdx.input.setInputProcessor(stage); final TextureRegion region = new TextureRegion(new Texture("data/badlogic.jpg")); final Actor actor = new Actor() { public void draw (SpriteBatch batch, float parentAlpha) { Color color = getColor(); batch.setColor(color.r, color.g, color.b, parentAlpha); batch.draw(region, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation()); } }; actor.setBounds(15, 15, 100, 100); actor.setOrigin(50, 50); stage.addActor(actor); actor.addListener(new InputListener() { public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { System.out.println("down"); return true; } public void touchUp (InputEvent event, float x, float y, int pointer, int button) { System.out.println("up " + event.getTarget()); } }); Skin skin = new Skin(Gdx.files.internal("data/uiskin.json")); VerticalGroup g = new VerticalGroup(); g.setPosition(100, 100); g.setReverse(true); stage.addActor(g); for (int i = 0; i < 10; i++) { g.addActor(new TextButton("button " + i, skin)); } g.pack(); final TextButton button = new TextButton("Fancy Background", skin); // button.addListener(new ClickListener() { // public void clicked (InputEvent event, float x, float y) { // System.out.println("click! " + x + " " + y); // } // }); button.addListener(new ActorGestureListener() { public boolean longPress (Actor actor, float x, float y) { System.out.println("long press " + x + ", " + y); return true; } - public void fling (InputEvent event, float velocityX, float velocityY, int pointer, int button) { + public void fling (InputEvent event, float velocityX, float velocityY, int button) { System.out.println("fling " + velocityX + ", " + velocityY); } public void zoom (InputEvent event, float initialDistance, float distance) { System.out.println("zoom " + initialDistance + ", " + distance); } public void pan (InputEvent event, float x, float y, float deltaX, float deltaY) { event.getListenerActor().translate(deltaX, deltaY); if (deltaX < 0) System.out.println("panning " + deltaX + ", " + deltaY + " " + event.getTarget()); } }); // button.addListener(new ChangeListener() { // public void changed (ChangeEvent event, Actor actor) { // // event.cancel(); // } // }); button.setPosition(50, 50); stage.addActor(button); // List select = new List(skin); // select.setBounds(200, 200, 100, 100); // select.setItems(new Object[] {1, 2, 3, 4, 5}); // stage.addActor(select); // stage.addListener(new ChangeListener() { // public void changed (ChangeEvent event, Actor actor) { // System.out.println(actor); // } // }); meow.setDuration(2); actor.addAction(forever(sequence(moveBy(50, 0, 2), moveBy(-50, 0, 2), run(new Runnable() { public void run () { actor.setZIndex(0); } })))); // actor.addAction(parallel(rotateBy(90, 2), rotateBy(90, 2))); // actor.addAction(parallel(moveTo(250, 250, 2, elasticOut), color(RED, 6), delay(0.5f), rotateTo(180, 5, swing))); // actor.addAction(forever(sequence(scaleTo(2, 2, 0.5f), scaleTo(1, 1, 0.5f), delay(0.5f)))); patch = new TiledDrawable(skin.getRegion("default-round")); Window window = new Window("Moo", skin); Label lbl = new Label("ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJ", skin); lbl.setWrap(true); window.row(); window.add(lbl).width(400); window.pack(); window.pack(); stage.addActor(window); } public void render () { // System.out.println(meow.getValue()); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); Table.drawDebug(stage); stage.getSpriteBatch().begin(); patch.draw(stage.getSpriteBatch(), 300, 100, 126, 126); stage.getSpriteBatch().end(); } public void resize (int width, int height) { stage.setViewport(width, height, true); } public boolean needsGL20 () { return true; } public void dispose () { stage.dispose(); } }
true
true
public void create () { stage = new Stage(); Gdx.input.setInputProcessor(stage); final TextureRegion region = new TextureRegion(new Texture("data/badlogic.jpg")); final Actor actor = new Actor() { public void draw (SpriteBatch batch, float parentAlpha) { Color color = getColor(); batch.setColor(color.r, color.g, color.b, parentAlpha); batch.draw(region, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation()); } }; actor.setBounds(15, 15, 100, 100); actor.setOrigin(50, 50); stage.addActor(actor); actor.addListener(new InputListener() { public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { System.out.println("down"); return true; } public void touchUp (InputEvent event, float x, float y, int pointer, int button) { System.out.println("up " + event.getTarget()); } }); Skin skin = new Skin(Gdx.files.internal("data/uiskin.json")); VerticalGroup g = new VerticalGroup(); g.setPosition(100, 100); g.setReverse(true); stage.addActor(g); for (int i = 0; i < 10; i++) { g.addActor(new TextButton("button " + i, skin)); } g.pack(); final TextButton button = new TextButton("Fancy Background", skin); // button.addListener(new ClickListener() { // public void clicked (InputEvent event, float x, float y) { // System.out.println("click! " + x + " " + y); // } // }); button.addListener(new ActorGestureListener() { public boolean longPress (Actor actor, float x, float y) { System.out.println("long press " + x + ", " + y); return true; } public void fling (InputEvent event, float velocityX, float velocityY, int pointer, int button) { System.out.println("fling " + velocityX + ", " + velocityY); } public void zoom (InputEvent event, float initialDistance, float distance) { System.out.println("zoom " + initialDistance + ", " + distance); } public void pan (InputEvent event, float x, float y, float deltaX, float deltaY) { event.getListenerActor().translate(deltaX, deltaY); if (deltaX < 0) System.out.println("panning " + deltaX + ", " + deltaY + " " + event.getTarget()); } }); // button.addListener(new ChangeListener() { // public void changed (ChangeEvent event, Actor actor) { // // event.cancel(); // } // }); button.setPosition(50, 50); stage.addActor(button); // List select = new List(skin); // select.setBounds(200, 200, 100, 100); // select.setItems(new Object[] {1, 2, 3, 4, 5}); // stage.addActor(select); // stage.addListener(new ChangeListener() { // public void changed (ChangeEvent event, Actor actor) { // System.out.println(actor); // } // }); meow.setDuration(2); actor.addAction(forever(sequence(moveBy(50, 0, 2), moveBy(-50, 0, 2), run(new Runnable() { public void run () { actor.setZIndex(0); } })))); // actor.addAction(parallel(rotateBy(90, 2), rotateBy(90, 2))); // actor.addAction(parallel(moveTo(250, 250, 2, elasticOut), color(RED, 6), delay(0.5f), rotateTo(180, 5, swing))); // actor.addAction(forever(sequence(scaleTo(2, 2, 0.5f), scaleTo(1, 1, 0.5f), delay(0.5f)))); patch = new TiledDrawable(skin.getRegion("default-round")); Window window = new Window("Moo", skin); Label lbl = new Label("ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJ", skin); lbl.setWrap(true); window.row(); window.add(lbl).width(400); window.pack(); window.pack(); stage.addActor(window); }
public void create () { stage = new Stage(); Gdx.input.setInputProcessor(stage); final TextureRegion region = new TextureRegion(new Texture("data/badlogic.jpg")); final Actor actor = new Actor() { public void draw (SpriteBatch batch, float parentAlpha) { Color color = getColor(); batch.setColor(color.r, color.g, color.b, parentAlpha); batch.draw(region, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation()); } }; actor.setBounds(15, 15, 100, 100); actor.setOrigin(50, 50); stage.addActor(actor); actor.addListener(new InputListener() { public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { System.out.println("down"); return true; } public void touchUp (InputEvent event, float x, float y, int pointer, int button) { System.out.println("up " + event.getTarget()); } }); Skin skin = new Skin(Gdx.files.internal("data/uiskin.json")); VerticalGroup g = new VerticalGroup(); g.setPosition(100, 100); g.setReverse(true); stage.addActor(g); for (int i = 0; i < 10; i++) { g.addActor(new TextButton("button " + i, skin)); } g.pack(); final TextButton button = new TextButton("Fancy Background", skin); // button.addListener(new ClickListener() { // public void clicked (InputEvent event, float x, float y) { // System.out.println("click! " + x + " " + y); // } // }); button.addListener(new ActorGestureListener() { public boolean longPress (Actor actor, float x, float y) { System.out.println("long press " + x + ", " + y); return true; } public void fling (InputEvent event, float velocityX, float velocityY, int button) { System.out.println("fling " + velocityX + ", " + velocityY); } public void zoom (InputEvent event, float initialDistance, float distance) { System.out.println("zoom " + initialDistance + ", " + distance); } public void pan (InputEvent event, float x, float y, float deltaX, float deltaY) { event.getListenerActor().translate(deltaX, deltaY); if (deltaX < 0) System.out.println("panning " + deltaX + ", " + deltaY + " " + event.getTarget()); } }); // button.addListener(new ChangeListener() { // public void changed (ChangeEvent event, Actor actor) { // // event.cancel(); // } // }); button.setPosition(50, 50); stage.addActor(button); // List select = new List(skin); // select.setBounds(200, 200, 100, 100); // select.setItems(new Object[] {1, 2, 3, 4, 5}); // stage.addActor(select); // stage.addListener(new ChangeListener() { // public void changed (ChangeEvent event, Actor actor) { // System.out.println(actor); // } // }); meow.setDuration(2); actor.addAction(forever(sequence(moveBy(50, 0, 2), moveBy(-50, 0, 2), run(new Runnable() { public void run () { actor.setZIndex(0); } })))); // actor.addAction(parallel(rotateBy(90, 2), rotateBy(90, 2))); // actor.addAction(parallel(moveTo(250, 250, 2, elasticOut), color(RED, 6), delay(0.5f), rotateTo(180, 5, swing))); // actor.addAction(forever(sequence(scaleTo(2, 2, 0.5f), scaleTo(1, 1, 0.5f), delay(0.5f)))); patch = new TiledDrawable(skin.getRegion("default-round")); Window window = new Window("Moo", skin); Label lbl = new Label("ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJ", skin); lbl.setWrap(true); window.row(); window.add(lbl).width(400); window.pack(); window.pack(); stage.addActor(window); }
diff --git a/src/test/java/org/mxupdate/test/util/TestParameterCache.java b/src/test/java/org/mxupdate/test/util/TestParameterCache.java index 15b67b33..c912a39a 100644 --- a/src/test/java/org/mxupdate/test/util/TestParameterCache.java +++ b/src/test/java/org/mxupdate/test/util/TestParameterCache.java @@ -1,100 +1,100 @@ /* * Copyright 2008-2009 The MxUpdate Team * * 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. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.mxupdate.test.util; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import matrix.db.Context; import org.mxupdate.mapping.Mapping_mxJPO; import org.mxupdate.update.util.ParameterCache_mxJPO; /** * @author The MxUpdate Team * @version $Id$ */ public class TestParameterCache extends ParameterCache_mxJPO { /** * Default constructor. * * @throws Exception if the parmater cache could not be initialized */ public TestParameterCache() throws Exception { super(null, false); } /** * Initialize the test mapping class (instance of {@link TestMapping}). * * @param _context MX context for this request (not used) * @return initialized mapping instance * @throws Exception if the mapping class could not be initialized */ @Override protected Mapping_mxJPO initMapping(final Context _context) throws Exception { return new TestMapping(); } /** * Test mapping class to overwrite the read of the properties from a file * (instead from an existing program in MX). */ private class TestMapping extends Mapping_mxJPO { /** * Default constructor. * * @throws Exception if the mapping could not be read */ public TestMapping() throws Exception { super(null); } /** * Read the properties directly from the file system at * &quot;src/org/mxupdate/mapping.properties&quot;. * * @param _context MX context for this request (not used) * @return read properties * @throws IOException if the properties from the file could not be * read */ @Override protected Properties readProperties(final Context _context) throws IOException { final Properties props = new Properties(); - props.load(new FileInputStream("src/org/mxupdate/mapping.properties")); + props.load(new FileInputStream("src/main/resources/org/mxupdate/mapping.properties")); return props; } } }
true
true
protected Properties readProperties(final Context _context) throws IOException { final Properties props = new Properties(); props.load(new FileInputStream("src/org/mxupdate/mapping.properties")); return props; }
protected Properties readProperties(final Context _context) throws IOException { final Properties props = new Properties(); props.load(new FileInputStream("src/main/resources/org/mxupdate/mapping.properties")); return props; }
diff --git a/src/factory/server/managers/kitAssemblyManager/UpdateServer.java b/src/factory/server/managers/kitAssemblyManager/UpdateServer.java index 6debd4e..22b55ec 100755 --- a/src/factory/server/managers/kitAssemblyManager/UpdateServer.java +++ b/src/factory/server/managers/kitAssemblyManager/UpdateServer.java @@ -1,663 +1,666 @@ package factory.server.managers.kitAssemblyManager; import factory.global.data.*; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.*; import factory.server.managers.GuiManager; import java.io.*; import factory.server.managers.laneManager.*; public class UpdateServer implements GuiManager { ArrayList<FactoryObject> CurrentObjects = new ArrayList<FactoryObject>(); TreeMap<Integer, Boolean> ChangeMap = new TreeMap<Integer, Boolean>(); TreeMap<Integer, FactoryObject> ChangeData = new TreeMap<Integer, FactoryObject>(); InspectionCamera cam; LaneManager lm; Conveyor conv; KitRobot robot; PartRobot probot; ArrayList<FactoryObject> LineObjects = new ArrayList<FactoryObject>(); ArrayList<FactoryObject> lastObjects = null; ArrayList<KitStand> stands; ArrayList<Kit> kits; ArrayList<Part> parts; ArrayList<Nest> nests; ArrayList<Integer> nestsIndex; FactoryObject flash = new FactoryObject(100, 430, 14); int count = 0; int countconv = 0; int partscount = 0; int k; int a[] = new int[4]; int b[] = new int[4]; boolean isBringKit = false; boolean isMoveToStand = false; boolean isMovePartstoStand = false; boolean isMoveToInspection = false; boolean isTakePic = false; boolean isTakeToConveyor = false; boolean isTakeKit = false; boolean isFinished = true; boolean isFlashed = false; boolean flag = false; boolean isBadKit = false; ArrayList<Boolean> isFull; @SuppressWarnings("unchecked") public UpdateServer() { cam = new InspectionCamera(100,500,13, this); conv = new Conveyor(0,20,-1, this); robot = new KitRobot(23,280,-1, this); probot = new PartRobot(253,280,-1, this); stands = new ArrayList<KitStand>(); kits = new ArrayList<Kit>(); parts = new ArrayList<Part>(); nests = new ArrayList<Nest>(); isFull = new ArrayList<Boolean>(); for (int i = 0; i < 8; i++) isFull.add(false); nestsIndex = new ArrayList<Integer>(); for (int i = 0; i < 8; i++) for (int j = 0; j < 9; j++) parts.add(new Part(0, 0, -1)); for (int i = 0; i < 3; i++) { KitStand ks = new KitStand(100,130 + i * 150,-1); stands.add(ks); } for (int i = 0; i < 4; i++){ Nest n1 = new Nest(355,72+i*124,-1); n1.setIndex(i * 2); Nest n2 = new Nest(355,72+i*124+35,-1); n2.setIndex(i * 2 + 1); nests.add(n1); nests.add(n2); } flash.setImage(14); LineObjects.add(new FactoryObject((int)robot.getX1(),(int)robot.getY1(),(int)robot.getX2(),(int)robot.getY2())); LineObjects.add(new FactoryObject((int)probot.getX1(),(int)probot.getY1(),(int)probot.getX2(),(int)probot.getY2())); setCurrentObjects(); } public void setFlash(boolean f) { isFlashed = f; } public void bindManager(GuiManager bindManager) { lm = (LaneManager) bindManager; for (int i = 0; i < 8; i++) { for (int j = 0; j < lm.getNest(i).size(); j++) { factory.global.data.Part p = lm.getNest(i).get(j); parts.add(new Part(p.x, p.y, p.imageIndex)); } for (int j = lm.getNest(i).size(); j < 9; j++) parts.add(new Part(0, 0, -1)); } } public ArrayList<FactoryObject> getCurrentObjects() { return CurrentObjects; } public void sync(TreeMap<Integer, FactoryObject> changeData) // frame sync { for (int i = 0; i < CurrentObjects.size(); i++) { FactoryObject t = null; if (CurrentObjects.get(i).isLine) t = new FactoryObject(CurrentObjects.get(i).x, CurrentObjects.get(i).y, CurrentObjects.get(i).xf, CurrentObjects.get(i).yf); else t = new FactoryObject(CurrentObjects.get(i).x, CurrentObjects.get(i).y, CurrentObjects.get(i).imageIndex); changeData.put(i, t); } } public void setCurrentObjects() { //add all the stuff to the arraylist CurrentObjects.clear(); try { for (int i = 0; i < 8; i++) { if (!isFull.get(i)) { for (int j = 0; j < lm.getNest(i).size(); j++) { { factory.global.data.Part p = lm.getNest(i).get(j); parts.set(j + 9 * i, new Part(355 + p.x, p.y, p.imageIndex)); } } for (int j = lm.getNest(i).size(); j < 9; j++) parts.set(j + 9 * i, new Part(0, 0, -1)); } if (lm.getNest(i).size() == 9) { factory.global.data.Part p = lm.getNest(i).get(8); //p.print(); //36, 98 if (p.x == 36 && p.y == 98 + i * 36) isFull.set(i, true); else isFull.set(i, false); } else isFull.set(i, false); } }catch(Exception e) {} for (int i = 0; i < kits.size(); i++) CurrentObjects.add(kits.get(i)); for (int i = 0; i < LineObjects.size(); i++) CurrentObjects.add(LineObjects.get(i)); CurrentObjects.add(probot.getGripper()); for (int i = 0; i < parts.size(); i++) { //if (parts.get(i).imageIndex != -1) // parts.get(i).print(); CurrentObjects.add(parts.get(i)); } CurrentObjects.add(cam); if (isFlashed) { CurrentObjects.add(flash); } } public boolean emptyStand() { //return whether stands are all empty for (int i = 0; i < 2; i++) { if (stands.get(i).getKit() == null) return true; } return false; } public ArrayList<Kit> getKits() { return kits; } public ArrayList<KitStand> getStands() { return stands; } public boolean isFinished() { return isFinished; } public int getCount() { return count; } public TreeMap<Integer, Boolean> getChangeMap() { return ChangeMap; } public TreeMap<Integer, FactoryObject> getChangeData() { return ChangeData; } public void bringKit() { if (isBringKit) //the control signal { flag = true; boolean f = true; if (conv.getInKit() == null && count < 26) { conv.bringKit(); countconv++; isFinished = false; flag = false; f = false; } if (!conv.kitArrived() && count < 26) { conv.moveKit(); f = false; if (flag) countconv++; isFinished = false; } if (f) isBringKit = false; //kits.get(0).print(); } else isBringKit = true; if (countconv == 26) { countconv = 0; isBringKit = false; isFinished = true; //isMoveToStand = true; } } public void moveToStand(int k) { if (isMoveToStand) { flag = true; boolean f = true; if (!robot.getIsMoving() && emptyStand() && conv.kitArrived()) { robot.moveFromConveyorToStand(conv, stands.get(k), conv.getInKit(), 0); //call the robot to do the animation count++; isFinished = false; flag = false; f = false; } if (robot.getIsMoving()) { robot.move(); f = false; if (flag) { count++; isFinished = false; } } if (f) isMoveToStand = false; } else { isMoveToStand = true; this.k = k; } if (count == 100) { count = 0; isMoveToStand = false; isFinished = true; //isBringKit = true; //isMovePartstoStand = true; } } public void movePartstoStand(int nest, int stand, int[] pos, int[] indexes) { if (isMovePartstoStand) { flag = true; boolean f = true; if (!probot.isMoving()) { if (stands.get(stand).getKit() != null){ Part[] p = new Part[4]; Nest[] n = new Nest[4]; nestsIndex.removeAll(nestsIndex); if (isBadKit) for (int i = pos.length - 1;i >= 0; i--) if (pos[i] != - 1) { parts.set(8 + 9 * pos[i], new Part(0, 0, -1)); lm.removePart(pos[i]); pos[i] = -1; indexes[i] = -1; break; } for (int j = 0; j < p.length; j++){ if (pos[j] != -1 && indexes[j] != -1) { - Part p1 = parts.get(8 + 9 * pos[j]); + Part p1 = null; + for (int i = 8; i >= 0; i--) + if (parts.get(i + 9 * pos[j]).imageIndex != -1) + p1 = parts.get(i + 9 * pos[j]); //System.out.println(p1.imageIndex); //Part p1 = new Part(nests.get(j).getPosition()X, //nests.get(j).getPositionY(), 1); //lm.removePart(pos[j]); parts.add(p1); p[j] = parts.get(parts.size() - 1); n[j] = nests.get(pos[j]); nestsIndex.add(pos[j]); } else p[j] = null; } probot.moveFromNest(stands.get(stand),p,n,indexes,0); //call the robot to do the animation isFinished = false; flag = false; f = false; count++; } } if (probot.isMoving()) { probot.move(); f = false; if (flag) { count++; isFinished = false; } } if (f) isMovePartstoStand = false; } else { isMovePartstoStand = true; this.k = stand; this.a = pos; this.b = indexes; } if (count == 141) { count = 0; isFinished = true; isMovePartstoStand = false; //if (stands.get(stand).getKit().getIsComplete()) //isMoveToInspection = true; } } public void moveToInspection(int stand) { if(isMoveToInspection) { flag = true; boolean f = true; if (!robot.getIsMoving() && stands.get(2).getKit() == null && stands.get(stand).getKit() != null) { robot.moveFromStandToStand(stands.get(stand),stands.get(2), stands.get(stand).getKit(), 0); //call the robot to do the animation count++; isFinished = false; flag = false; f = false; } if (robot.getIsMoving()) { robot.move(); if (flag) { count++; isFinished = false; f = false; } } if (f) isMoveToInspection = false; } else /*if (stands.get(stand).getKit().getIsComplete())*/ { isMoveToInspection = true; this.k = stand; } if (count == 100) { count = 0; isMoveToInspection = false; isFinished = true; //isTakePic = true; } } public void takePic() { if (isTakePic) { flag = true; boolean f = true; if (!robot.getIsMoving() && stands.get(2).getKit() != null && !stands.get(2).getKit().getPicTaken() && !cam.isMoving()) { cam.takePicture(stands.get(2), 0); //call the robot to do the animation count++; isFinished = false; flag = false; f = false; } if (cam.isMoving) { cam.move(); if (flag) { count++; isFinished = false; } f = false; } if (f) isTakePic = false; } else isTakePic = true; if (count == 57) { count = 0; isTakePic = false; isFinished = true; //isTakeToConveyor = true; } } public void takeToConveyor() { if (isTakeToConveyor) { flag = true; boolean f = true; if (!robot.getIsMoving() && stands.get(2).getKit() != null && stands.get(2).getKit().getPicTaken()) { if(!isBadKit) robot.moveFromStandToConveyor(stands.get(2), conv, stands.get(2).getKit(), 0); //call the robot to do the animation else robot.trashKit(stands.get(2), stands.get(2).getKit(), 0); count++; isFinished = false; flag = false; f = false; } if (robot.getIsMoving()) { robot.move(); f = false; if (flag) { count++; isFinished = false; } } if (f) isTakeToConveyor = false; } else isTakeToConveyor = true; if (count == 100) { count = 0; isTakeToConveyor = false; isFinished = true; //isTakeKit = true; } } public void takeKit() { if (isTakeKit) { if (conv.getOutKit() != null) { conv.takeKit(); //call the robot to do the animation count++; isFinished = false; } else isTakeKit = false; } else isTakeKit = true; if (count == 26) { count = 0; isTakeKit = false; isFinished = true; conv.getOutKit().setIsMoving(false); conv.setOutKit(null); } } public void removeExtraKits() //remove the unused kits { for (int i = 0; i < kits.size(); i++){ if (kits.get(i).getPositionX() < 0 && !kits.get(i).getIsMoving()){ removeExtraParts(); kits.remove(i); i--; } } } public void removeExtraParts()//remove the unused parts { for (int i = 0; i < parts.size(); i++){ if (parts.get(i).getPositionX() < 0){ parts.remove(i); i--; } } } public void update(TreeMap<Integer, Boolean> inputChangeMap, TreeMap<Integer, FactoryObject> inputChangeData) // ------------> update complete { //ChangeMap = inputChangeMap; //ChangeData = inputChangeData; move(); //update the coornidates /*System.out.print("1st: "); lastObjects.get(0).print(); System.out.print("2nd: "); CurrentObjects.get(0).print();*/ inputChangeData.clear(); inputChangeMap.clear(); if (lastObjects.size() <= CurrentObjects.size()) { for (int i = 0; i < lastObjects.size(); i++) { if (!lastObjects.get(i).isEquals(CurrentObjects.get(i))) //if the objects are the same then update the network stuff { //System.out.print(i + " :"); //CurrentObjects.get(i).print(); inputChangeMap.put(i, true); FactoryObject t = null; if (CurrentObjects.get(i).isLine) t = new FactoryObject(CurrentObjects.get(i).x, CurrentObjects.get(i).y, CurrentObjects.get(i).xf, CurrentObjects.get(i).yf); else t = new FactoryObject(CurrentObjects.get(i).x, CurrentObjects.get(i).y, CurrentObjects.get(i).imageIndex); inputChangeData.put(i, t); } } for (int i = lastObjects.size(); i < CurrentObjects.size(); i++) { inputChangeMap.put(i, true); FactoryObject t = null; if (CurrentObjects.get(i).isLine) t = new FactoryObject(CurrentObjects.get(i).x, CurrentObjects.get(i).y, CurrentObjects.get(i).xf, CurrentObjects.get(i).yf); else t = new FactoryObject(CurrentObjects.get(i).x, CurrentObjects.get(i).y, CurrentObjects.get(i).imageIndex); inputChangeData.put(i, t); } } else { for (int i = 0; i < CurrentObjects.size(); i++) { if (!lastObjects.get(i).isEquals(CurrentObjects.get(i))) { //System.out.print(i + " :"); inputChangeMap.put(i, true); FactoryObject t = null; if (CurrentObjects.get(i).isLine) t = new FactoryObject(CurrentObjects.get(i).x, CurrentObjects.get(i).y, CurrentObjects.get(i).xf, CurrentObjects.get(i).yf); else t = new FactoryObject(CurrentObjects.get(i).x, CurrentObjects.get(i).y, CurrentObjects.get(i).imageIndex); inputChangeData.put(i, t); } } for (int i = CurrentObjects.size(); i < lastObjects.size(); i++) //if the original list is shorter, delete all the extra objects { inputChangeMap.put(i, false); } } //lastObjects = (ArrayList<FactoryObject>) CurrentObjects.clone(); } public void move() { //call the interfaces to do the animation lastObjects = new ArrayList<FactoryObject>(); for (int i = 0; i < CurrentObjects.size(); i++) { lastObjects.add((FactoryObject)CurrentObjects.get(i).clone()); } if (isBringKit) bringKit(); if (isMoveToStand) moveToStand(k); if (isMovePartstoStand) { //int a[] = {0, 1, 2, 5}; //int b[] = {0,4,6,8}; movePartstoStand(200, k, a, b); } if (isMoveToInspection) { moveToInspection(k); } if (isTakePic) takePic(); if (isTakeToConveyor) takeToConveyor(); if (isTakeKit) { takeKit(); } removeExtraKits(); LineObjects.set(0, new FactoryObject((int)robot.getX1(),(int)robot.getY1(),(int)robot.getX2(),(int)robot.getY2())); LineObjects.set(1, new FactoryObject((int)probot.getX1(),(int)probot.getY1(),(int)probot.getX2(),(int)probot.getY2())); setCurrentObjects(); } public boolean isBadKit() { return isBadKit; } public void breakPart(String b, int x) { if (b.equals("BRKSM")) isBadKit = !isBadKit; } public void setSync(){} public boolean getSync() { return false; } }
true
true
public void movePartstoStand(int nest, int stand, int[] pos, int[] indexes) { if (isMovePartstoStand) { flag = true; boolean f = true; if (!probot.isMoving()) { if (stands.get(stand).getKit() != null){ Part[] p = new Part[4]; Nest[] n = new Nest[4]; nestsIndex.removeAll(nestsIndex); if (isBadKit) for (int i = pos.length - 1;i >= 0; i--) if (pos[i] != - 1) { parts.set(8 + 9 * pos[i], new Part(0, 0, -1)); lm.removePart(pos[i]); pos[i] = -1; indexes[i] = -1; break; } for (int j = 0; j < p.length; j++){ if (pos[j] != -1 && indexes[j] != -1) { Part p1 = parts.get(8 + 9 * pos[j]); //System.out.println(p1.imageIndex); //Part p1 = new Part(nests.get(j).getPosition()X, //nests.get(j).getPositionY(), 1); //lm.removePart(pos[j]); parts.add(p1); p[j] = parts.get(parts.size() - 1); n[j] = nests.get(pos[j]); nestsIndex.add(pos[j]); } else p[j] = null; } probot.moveFromNest(stands.get(stand),p,n,indexes,0); //call the robot to do the animation isFinished = false; flag = false; f = false; count++; } } if (probot.isMoving()) { probot.move(); f = false; if (flag) { count++; isFinished = false; } } if (f) isMovePartstoStand = false; } else { isMovePartstoStand = true; this.k = stand; this.a = pos; this.b = indexes; } if (count == 141) { count = 0; isFinished = true; isMovePartstoStand = false; //if (stands.get(stand).getKit().getIsComplete()) //isMoveToInspection = true; } }
public void movePartstoStand(int nest, int stand, int[] pos, int[] indexes) { if (isMovePartstoStand) { flag = true; boolean f = true; if (!probot.isMoving()) { if (stands.get(stand).getKit() != null){ Part[] p = new Part[4]; Nest[] n = new Nest[4]; nestsIndex.removeAll(nestsIndex); if (isBadKit) for (int i = pos.length - 1;i >= 0; i--) if (pos[i] != - 1) { parts.set(8 + 9 * pos[i], new Part(0, 0, -1)); lm.removePart(pos[i]); pos[i] = -1; indexes[i] = -1; break; } for (int j = 0; j < p.length; j++){ if (pos[j] != -1 && indexes[j] != -1) { Part p1 = null; for (int i = 8; i >= 0; i--) if (parts.get(i + 9 * pos[j]).imageIndex != -1) p1 = parts.get(i + 9 * pos[j]); //System.out.println(p1.imageIndex); //Part p1 = new Part(nests.get(j).getPosition()X, //nests.get(j).getPositionY(), 1); //lm.removePart(pos[j]); parts.add(p1); p[j] = parts.get(parts.size() - 1); n[j] = nests.get(pos[j]); nestsIndex.add(pos[j]); } else p[j] = null; } probot.moveFromNest(stands.get(stand),p,n,indexes,0); //call the robot to do the animation isFinished = false; flag = false; f = false; count++; } } if (probot.isMoving()) { probot.move(); f = false; if (flag) { count++; isFinished = false; } } if (f) isMovePartstoStand = false; } else { isMovePartstoStand = true; this.k = stand; this.a = pos; this.b = indexes; } if (count == 141) { count = 0; isFinished = true; isMovePartstoStand = false; //if (stands.get(stand).getKit().getIsComplete()) //isMoveToInspection = true; } }
diff --git a/src/main/java/tconstruct/client/tabs/AbstractTab.java b/src/main/java/tconstruct/client/tabs/AbstractTab.java index 97da51632..3fa1604d1 100644 --- a/src/main/java/tconstruct/client/tabs/AbstractTab.java +++ b/src/main/java/tconstruct/client/tabs/AbstractTab.java @@ -1,67 +1,68 @@ package tconstruct.client.tabs; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.*; public abstract class AbstractTab extends GuiButton { ResourceLocation texture = new ResourceLocation("textures/gui/container/creative_inventory/tabs.png"); ItemStack renderStack; RenderItem itemRenderer = new RenderItem(); public AbstractTab(int id, int posX, int posY, ItemStack renderStack) { super(id, posX, posY, 28, 32, ""); this.renderStack = renderStack; } @Override public void drawButton (Minecraft mc, int mouseX, int mouseY) { if (this.visible) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); int yTexPos = this.enabled ? 3 : 32; int ySize = this.enabled ? 28 : 32; int xOffset = this.id == 2 ? 0 : 1; mc.renderEngine.bindTexture(this.texture); this.drawTexturedModalRect(this.xPosition, this.yPosition, xOffset * 28, yTexPos, 28, ySize); RenderHelper.enableGUIStandardItemLighting(); this.zLevel = 100.0F; this.itemRenderer.zLevel = 100.0F; GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL12.GL_RESCALE_NORMAL); this.itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.renderEngine, renderStack, xPosition + 6, yPosition + 8); this.itemRenderer.renderItemOverlayIntoGUI(mc.fontRenderer, mc.renderEngine, renderStack, xPosition + 6, yPosition + 8); GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); this.itemRenderer.zLevel = 0.0F; this.zLevel = 0.0F; RenderHelper.disableStandardItemLighting(); } } @Override public boolean mousePressed (Minecraft mc, int mouseX, int mouseY) { boolean inWindow = this.enabled && this.visible && mouseX >= this.xPosition && mouseY >= this.yPosition && mouseX < this.xPosition + this.width && mouseY < this.yPosition + this.height; if (inWindow) { this.onTabClicked(); } return inWindow; } public abstract void onTabClicked (); public abstract boolean shouldAddToList (); }
true
true
public void drawButton (Minecraft mc, int mouseX, int mouseY) { if (this.visible) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); int yTexPos = this.enabled ? 3 : 32; int ySize = this.enabled ? 28 : 32; int xOffset = this.id == 2 ? 0 : 1; mc.renderEngine.bindTexture(this.texture); this.drawTexturedModalRect(this.xPosition, this.yPosition, xOffset * 28, yTexPos, 28, ySize); RenderHelper.enableGUIStandardItemLighting(); this.zLevel = 100.0F; this.itemRenderer.zLevel = 100.0F; GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL12.GL_RESCALE_NORMAL); this.itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.renderEngine, renderStack, xPosition + 6, yPosition + 8); this.itemRenderer.renderItemOverlayIntoGUI(mc.fontRenderer, mc.renderEngine, renderStack, xPosition + 6, yPosition + 8); GL11.glDisable(GL11.GL_LIGHTING); this.itemRenderer.zLevel = 0.0F; this.zLevel = 0.0F; RenderHelper.disableStandardItemLighting(); } }
public void drawButton (Minecraft mc, int mouseX, int mouseY) { if (this.visible) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); int yTexPos = this.enabled ? 3 : 32; int ySize = this.enabled ? 28 : 32; int xOffset = this.id == 2 ? 0 : 1; mc.renderEngine.bindTexture(this.texture); this.drawTexturedModalRect(this.xPosition, this.yPosition, xOffset * 28, yTexPos, 28, ySize); RenderHelper.enableGUIStandardItemLighting(); this.zLevel = 100.0F; this.itemRenderer.zLevel = 100.0F; GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL12.GL_RESCALE_NORMAL); this.itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.renderEngine, renderStack, xPosition + 6, yPosition + 8); this.itemRenderer.renderItemOverlayIntoGUI(mc.fontRenderer, mc.renderEngine, renderStack, xPosition + 6, yPosition + 8); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_BLEND); this.itemRenderer.zLevel = 0.0F; this.zLevel = 0.0F; RenderHelper.disableStandardItemLighting(); } }
diff --git a/treeview/src/main/uk/ac/starlink/treeview/NdxDataNode.java b/treeview/src/main/uk/ac/starlink/treeview/NdxDataNode.java index 95c4d9a30..9ed9c3481 100644 --- a/treeview/src/main/uk/ac/starlink/treeview/NdxDataNode.java +++ b/treeview/src/main/uk/ac/starlink/treeview/NdxDataNode.java @@ -1,436 +1,444 @@ package uk.ac.starlink.treeview; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.swing.Action; import javax.swing.AbstractAction; import javax.swing.Icon; import javax.swing.JComponent; import javax.xml.rpc.ServiceException; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import uk.ac.starlink.array.AccessMode; import uk.ac.starlink.array.NDArray; import uk.ac.starlink.array.NDArrays; import uk.ac.starlink.array.NDShape; import uk.ac.starlink.array.Requirements; import uk.ac.starlink.ast.FrameSet; import uk.ac.starlink.hds.HDSException; import uk.ac.starlink.hds.HDSObject; import uk.ac.starlink.hds.NDFNdxHandler; import uk.ac.starlink.hds.HDSReference; import uk.ac.starlink.ndx.Ndx; import uk.ac.starlink.ndx.Ndxs; import uk.ac.starlink.ndx.NdxIO; import uk.ac.starlink.ndx.XMLNdxHandler; import uk.ac.starlink.splat.util.SplatException; import uk.ac.starlink.util.URLUtils; /** * An implementation of the <tt>DataNode</tt> interface for representing * {@link uk.ac.starlink.ndx.Ndx} objects. * * @author Mark Taylor (Starlink) */ public class NdxDataNode extends DefaultDataNode { private Ndx ndx; private String name; private String desc; private Icon icon; private JComponent fullView; private URL url; /** * Initialises an NdxDataNode from a string giving a URL or filename. * * @param loc the location of a readable Ndx */ public NdxDataNode( String loc ) throws NoSuchDataException { try { this.url = new URL( new URL( "file:." ), loc ); } catch ( MalformedURLException e ) { this.url = null; } try { this.ndx = new NdxIO().makeNdx( loc, AccessMode.READ ); } catch ( IOException e ) { throw new NoSuchDataException( "Can't make NDX", e ); } catch ( IllegalArgumentException e ) { throw new NoSuchDataException( "Can't make NDX", e ); } if ( ndx == null ) { throw new NoSuchDataException( "URL " + loc + " doesn't look like an NDX" ); } name = loc.replaceFirst( "#.*$", "" ); name = name.replaceFirst( "^.*/", "" ); setLabel( name ); } public NdxDataNode( File file ) throws NoSuchDataException { this( file.toString() ); setPath( file.getAbsolutePath() ); } /** * Initialises an NdxDataNode from an NDF structure. * * @param hobj an HDSObject, which should reference an NDF structure */ public NdxDataNode( HDSObject hobj ) throws NoSuchDataException { try { url = new HDSReference( hobj ).getURL(); } catch ( HDSException e ) { url = null; } try { ndx = NDFNdxHandler.getInstance() .makeNdx( hobj, url, AccessMode.READ ); name = hobj.datName(); } catch ( HDSException e ) { throw new NoSuchDataException( e ); } if ( ndx == null ) { throw new NoSuchDataException( "Not an NDF structure" ); } setLabel( name ); } /** * Initialises an NdxDataNode from an XML source. It is passed as * a Source rather than a simple Node so that it can contain the * SystemID as well, which may be necessary to resolve relative URL * references to data arrays etc. * * @param xsrc a Source containing the XML representation of the Ndx */ public NdxDataNode( Source xsrc ) throws NoSuchDataException { try { ndx = XMLNdxHandler.getInstance().makeNdx( xsrc, AccessMode.READ ); } catch ( IOException e ) { throw new NoSuchDataException( e ); } catch ( IllegalArgumentException e ) { throw new NoSuchDataException( e ); } if ( ndx == null ) { throw new NoSuchDataException( "Not an NDX" ); } if ( ndx.hasTitle() ) { name = ndx.getTitle(); } else { name = "ndx"; } this.url = URLUtils.makeURL( xsrc.getSystemId() ); setLabel( name ); } public String getDescription() { if ( desc == null ) { desc = new NDShape( ndx.getImage().getShape() ).toString(); } return desc; } public boolean allowsChildren() { return true; } protected DataNode[] getChildren() { DataNodeFactory childMaker = getChildMaker(); List children = new ArrayList(); if ( ndx.hasTitle() ) { DataNode tit; tit = new ScalarDataNode( "Title", "string", ndx.getTitle() ); tit.setCreator( new CreationState( this ) ); children.add( tit ); } DataNode im; try { im = childMaker.makeDataNode( this, ndx.getImage() ); } catch ( NoSuchDataException e ) { im = childMaker.makeErrorDataNode( this, e ); } im.setLabel( "image" ); children.add( im ); if ( ndx.hasVariance() ) { DataNode var; try { var = childMaker.makeDataNode( this, ndx.getVariance() ); } catch ( NoSuchDataException e ) { var = childMaker.makeErrorDataNode( this, e ); } var.setLabel( "variance" ); children.add( var ); } if ( ndx.hasQuality() ) { DataNode qual; try { qual = childMaker.makeDataNode( this, ndx.getQuality() ); } catch ( NoSuchDataException e ) { qual = childMaker.makeErrorDataNode( this, e ); } qual.setLabel( "quality" ); children.add( qual ); } int badbits = ndx.getBadBits(); if ( badbits != 0 ) { DataNode bb = new ScalarDataNode( "BadBits", "int", "0x" + Integer.toHexString( badbits ) ); bb.setCreator( new CreationState( this ) ); children.add( bb ); } if ( Driver.hasAST && ndx.hasWCS() ) { DataNode wnode; try { wnode = childMaker.makeDataNode( this, ndx.getAst() ); } catch ( NoSuchDataException e ) { wnode = childMaker.makeErrorDataNode( this, e ); } children.add( wnode ); } if ( ndx.hasEtc() ) { DataNode etcNode; try { etcNode = childMaker.makeDataNode( this, ndx.getEtc() ); } catch ( NoSuchDataException e ) { etcNode = childMaker.makeErrorDataNode( this, e ); } children.add( etcNode ); } return (DataNode[]) children.toArray( new DataNode[ 0 ] ); } public String getName() { return name; } public String getNodeTLA() { return "NDX"; } public String getNodeType() { return "NDX structure"; } public Icon getIcon() { if ( icon == null ) { icon = IconFactory.getInstance().getIcon( IconFactory.NDX ); } return icon; } public String getPathElement() { return getLabel(); } public String getPathSeparator() { return "."; } public boolean hasFullView() { return true; } public JComponent getFullView() { if ( fullView == null ) { DetailViewer dv = new DetailViewer( this ); fullView = dv.getComponent(); dv.addSeparator(); if ( ndx.hasTitle() ) { dv.addKeyedItem( "Title", ndx.getTitle() ); } dv.addPane( "XML representation", new ComponentMaker() { public JComponent getComponent() throws TransformerException { return new TextViewer( ndx.toXML( url ) ); } } ); try { addDataViews( dv, ndx ); } catch ( IOException e ) { dv.logError( e ); } } return fullView; } /** * Adds visual elements to a DetailViewer suitable for a general * NDX-type structure. This method is used by the NdxDataNode class * to add things like an image view pane, but is provided as a * public static method so that other DataNodes which represent * NDX-type data can use it too. * * @param dv the DetailViewer into which the new visual elements are * to be placed * @param ndx the NDX which is to be described * @throws IOException if anything goes wrong with the data access */ public static void addDataViews( DetailViewer dv, final Ndx ndx ) throws IOException{ Requirements req = new Requirements( AccessMode.READ ) .setRandom( true ); final NDArray image = NDArrays.toRequiredArray( Ndxs.getMaskedImage( ndx ), req ); final FrameSet ast = Driver.hasAST ? Ndxs.getAst( ndx ) : null; final NDShape shape = image.getShape(); final int ndim = shape.getNumDims(); /* Get a version with degenerate dimensions collapsed. Should really * also get a corresponding WCS and use that, but I haven't worked * out how to do that properly yet, so the views below either use * the original array with its WCS or the effective array with * a blank WCS. */ - final NDArray eimage = NDArrayDataNode.effectiveArray( image ); - final int endim = eimage.getShape().getNumDims(); + final NDArray eimage; + final int endim; + if ( shape.getNumPixels() > 1 ) { + eimage = NDArrayDataNode.effectiveArray( image ); + endim = eimage.getShape().getNumDims(); + } + else { + eimage = image; + endim = ndim; + } /* Add data views as appropriate. */ if ( Driver.hasAST && ndx.hasWCS() && ndim == 2 && endim == 2 ) { dv.addScalingPane( "WCS grids", new ComponentMaker() { public JComponent getComponent() throws IOException { return new GridPlotter( shape, ast ); } } ); } dv.addPane( "Pixel values", new ComponentMaker() { public JComponent getComponent() throws IOException { if ( endim == 2 && ndim != 2 ) { return new ArrayBrowser( eimage ); } else { return new ArrayBrowser( image ); } } } ); dv.addPane( "Statistics", new ComponentMaker() { public JComponent getComponent() { return new StatsViewer( image ); } } ); if ( endim == 1 && Driver.hasAST ) { dv.addScalingPane( "Graph view", new ComponentMaker() { public JComponent getComponent() throws IOException, SplatException { return new GraphViewer( ndx ); } } ); } if ( ( ndim == 2 || endim == 2 ) && Driver.hasJAI ) { dv.addPane( "Image display", new ComponentMaker() { public JComponent getComponent() throws IOException { if ( endim == 2 && ndim != 2 ) { return new ImageViewer( eimage, null ); } else { return new ImageViewer( image, ast ); } } } ); } if ( endim > 2 && Driver.hasJAI ) { dv.addPane( "Slices", new ComponentMaker() { public JComponent getComponent() { if ( endim != ndim ) { return new SliceViewer( image, null ); } else { return new SliceViewer( image, ast ); } } } ); } if ( endim == 3 && Driver.hasJAI ) { dv.addPane( "Collapsed", new ComponentMaker() { public JComponent getComponent() throws IOException { if ( endim != ndim ) { return new CollapseViewer( eimage, null ); } else { return new CollapseViewer( image, ast ); } } } ); } /* Add actions as appropriate. */ List actlist = new ArrayList(); if ( ndim == 1 && endim == 1 ) { final ApplicationInvoker displayer = ApplicationInvoker.SPLAT; if ( displayer.canDisplayNDX() ) { Icon splatic = IconFactory.getInstance() .getIcon( IconFactory.SPLAT ); Action splatAct = new AbstractAction( "Splat", splatic ) { public void actionPerformed( ActionEvent evt ) { try { displayer.displayNDX( ndx ); } catch ( ServiceException e ) { beep(); e.printStackTrace(); } } }; actlist.add( splatAct ); } } if ( ndim == 2 && endim == 2 ) { final ApplicationInvoker displayer = ApplicationInvoker.SOG; if ( displayer.canDisplayNDX() ) { Icon sogic = IconFactory.getInstance() .getIcon( IconFactory.SOG ); Action sogAct = new AbstractAction( "SoG", sogic ) { public void actionPerformed( ActionEvent evt ) { try { displayer.displayNDX( ndx ); } catch ( ServiceException e ) { beep(); e.printStackTrace(); } } }; actlist.add( sogAct ); } } dv.addActions( (Action[]) actlist.toArray( new Action[ 0 ] ) ); } }
true
true
public static void addDataViews( DetailViewer dv, final Ndx ndx ) throws IOException{ Requirements req = new Requirements( AccessMode.READ ) .setRandom( true ); final NDArray image = NDArrays.toRequiredArray( Ndxs.getMaskedImage( ndx ), req ); final FrameSet ast = Driver.hasAST ? Ndxs.getAst( ndx ) : null; final NDShape shape = image.getShape(); final int ndim = shape.getNumDims(); /* Get a version with degenerate dimensions collapsed. Should really * also get a corresponding WCS and use that, but I haven't worked * out how to do that properly yet, so the views below either use * the original array with its WCS or the effective array with * a blank WCS. */ final NDArray eimage = NDArrayDataNode.effectiveArray( image ); final int endim = eimage.getShape().getNumDims(); /* Add data views as appropriate. */ if ( Driver.hasAST && ndx.hasWCS() && ndim == 2 && endim == 2 ) { dv.addScalingPane( "WCS grids", new ComponentMaker() { public JComponent getComponent() throws IOException { return new GridPlotter( shape, ast ); } } ); } dv.addPane( "Pixel values", new ComponentMaker() { public JComponent getComponent() throws IOException { if ( endim == 2 && ndim != 2 ) { return new ArrayBrowser( eimage ); } else { return new ArrayBrowser( image ); } } } ); dv.addPane( "Statistics", new ComponentMaker() { public JComponent getComponent() { return new StatsViewer( image ); } } ); if ( endim == 1 && Driver.hasAST ) { dv.addScalingPane( "Graph view", new ComponentMaker() { public JComponent getComponent() throws IOException, SplatException { return new GraphViewer( ndx ); } } ); } if ( ( ndim == 2 || endim == 2 ) && Driver.hasJAI ) { dv.addPane( "Image display", new ComponentMaker() { public JComponent getComponent() throws IOException { if ( endim == 2 && ndim != 2 ) { return new ImageViewer( eimage, null ); } else { return new ImageViewer( image, ast ); } } } ); } if ( endim > 2 && Driver.hasJAI ) { dv.addPane( "Slices", new ComponentMaker() { public JComponent getComponent() { if ( endim != ndim ) { return new SliceViewer( image, null ); } else { return new SliceViewer( image, ast ); } } } ); } if ( endim == 3 && Driver.hasJAI ) { dv.addPane( "Collapsed", new ComponentMaker() { public JComponent getComponent() throws IOException { if ( endim != ndim ) { return new CollapseViewer( eimage, null ); } else { return new CollapseViewer( image, ast ); } } } ); } /* Add actions as appropriate. */ List actlist = new ArrayList(); if ( ndim == 1 && endim == 1 ) { final ApplicationInvoker displayer = ApplicationInvoker.SPLAT; if ( displayer.canDisplayNDX() ) { Icon splatic = IconFactory.getInstance() .getIcon( IconFactory.SPLAT ); Action splatAct = new AbstractAction( "Splat", splatic ) { public void actionPerformed( ActionEvent evt ) { try { displayer.displayNDX( ndx ); } catch ( ServiceException e ) { beep(); e.printStackTrace(); } } }; actlist.add( splatAct ); } } if ( ndim == 2 && endim == 2 ) { final ApplicationInvoker displayer = ApplicationInvoker.SOG; if ( displayer.canDisplayNDX() ) { Icon sogic = IconFactory.getInstance() .getIcon( IconFactory.SOG ); Action sogAct = new AbstractAction( "SoG", sogic ) { public void actionPerformed( ActionEvent evt ) { try { displayer.displayNDX( ndx ); } catch ( ServiceException e ) { beep(); e.printStackTrace(); } } }; actlist.add( sogAct ); } } dv.addActions( (Action[]) actlist.toArray( new Action[ 0 ] ) ); }
public static void addDataViews( DetailViewer dv, final Ndx ndx ) throws IOException{ Requirements req = new Requirements( AccessMode.READ ) .setRandom( true ); final NDArray image = NDArrays.toRequiredArray( Ndxs.getMaskedImage( ndx ), req ); final FrameSet ast = Driver.hasAST ? Ndxs.getAst( ndx ) : null; final NDShape shape = image.getShape(); final int ndim = shape.getNumDims(); /* Get a version with degenerate dimensions collapsed. Should really * also get a corresponding WCS and use that, but I haven't worked * out how to do that properly yet, so the views below either use * the original array with its WCS or the effective array with * a blank WCS. */ final NDArray eimage; final int endim; if ( shape.getNumPixels() > 1 ) { eimage = NDArrayDataNode.effectiveArray( image ); endim = eimage.getShape().getNumDims(); } else { eimage = image; endim = ndim; } /* Add data views as appropriate. */ if ( Driver.hasAST && ndx.hasWCS() && ndim == 2 && endim == 2 ) { dv.addScalingPane( "WCS grids", new ComponentMaker() { public JComponent getComponent() throws IOException { return new GridPlotter( shape, ast ); } } ); } dv.addPane( "Pixel values", new ComponentMaker() { public JComponent getComponent() throws IOException { if ( endim == 2 && ndim != 2 ) { return new ArrayBrowser( eimage ); } else { return new ArrayBrowser( image ); } } } ); dv.addPane( "Statistics", new ComponentMaker() { public JComponent getComponent() { return new StatsViewer( image ); } } ); if ( endim == 1 && Driver.hasAST ) { dv.addScalingPane( "Graph view", new ComponentMaker() { public JComponent getComponent() throws IOException, SplatException { return new GraphViewer( ndx ); } } ); } if ( ( ndim == 2 || endim == 2 ) && Driver.hasJAI ) { dv.addPane( "Image display", new ComponentMaker() { public JComponent getComponent() throws IOException { if ( endim == 2 && ndim != 2 ) { return new ImageViewer( eimage, null ); } else { return new ImageViewer( image, ast ); } } } ); } if ( endim > 2 && Driver.hasJAI ) { dv.addPane( "Slices", new ComponentMaker() { public JComponent getComponent() { if ( endim != ndim ) { return new SliceViewer( image, null ); } else { return new SliceViewer( image, ast ); } } } ); } if ( endim == 3 && Driver.hasJAI ) { dv.addPane( "Collapsed", new ComponentMaker() { public JComponent getComponent() throws IOException { if ( endim != ndim ) { return new CollapseViewer( eimage, null ); } else { return new CollapseViewer( image, ast ); } } } ); } /* Add actions as appropriate. */ List actlist = new ArrayList(); if ( ndim == 1 && endim == 1 ) { final ApplicationInvoker displayer = ApplicationInvoker.SPLAT; if ( displayer.canDisplayNDX() ) { Icon splatic = IconFactory.getInstance() .getIcon( IconFactory.SPLAT ); Action splatAct = new AbstractAction( "Splat", splatic ) { public void actionPerformed( ActionEvent evt ) { try { displayer.displayNDX( ndx ); } catch ( ServiceException e ) { beep(); e.printStackTrace(); } } }; actlist.add( splatAct ); } } if ( ndim == 2 && endim == 2 ) { final ApplicationInvoker displayer = ApplicationInvoker.SOG; if ( displayer.canDisplayNDX() ) { Icon sogic = IconFactory.getInstance() .getIcon( IconFactory.SOG ); Action sogAct = new AbstractAction( "SoG", sogic ) { public void actionPerformed( ActionEvent evt ) { try { displayer.displayNDX( ndx ); } catch ( ServiceException e ) { beep(); e.printStackTrace(); } } }; actlist.add( sogAct ); } } dv.addActions( (Action[]) actlist.toArray( new Action[ 0 ] ) ); }
diff --git a/src/paulscode/android/mupen64plusae/input/TouchController.java b/src/paulscode/android/mupen64plusae/input/TouchController.java index 27cf7163..968d1dcf 100644 --- a/src/paulscode/android/mupen64plusae/input/TouchController.java +++ b/src/paulscode/android/mupen64plusae/input/TouchController.java @@ -1,461 +1,466 @@ /** * Mupen64PlusAE, an N64 emulator for the Android platform * * Copyright (C) 2013 Paul Lamb * * This file is part of Mupen64PlusAE. * * Mupen64PlusAE is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Mupen64PlusAE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with Mupen64PlusAE. If * not, see <http://www.gnu.org/licenses/>. * * Authors: Paul Lamb, Gillou68310, littleguy77 */ package paulscode.android.mupen64plusae.input; import paulscode.android.mupen64plusae.input.map.TouchMap; import paulscode.android.mupen64plusae.persistent.AppData; import android.annotation.TargetApi; import android.graphics.Point; import android.os.Vibrator; import android.util.FloatMath; import android.util.SparseIntArray; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; /** * A class for generating N64 controller commands from a touchscreen. */ public class TouchController extends AbstractController implements OnTouchListener { public interface OnStateChangedListener { /** * Called after the analog stick values have changed. * * @param axisFractionX The x-axis fraction, between -1 and 1, inclusive. * @param axisFractionY The y-axis fraction, between -1 and 1, inclusive. */ public void onAnalogChanged( float axisFractionX, float axisFractionY ); /** * Called after auto-hold button state changed. * * @param pressed The auto-hold state. * @param index The index of the auto-hold mask. */ public void onAutoHold( boolean pressed, int index ); } public static final int AUTOHOLD_METHOD_LONGPRESS = 0; public static final int AUTOHOLD_METHOD_SLIDEOUT = 1; /** The number of milliseconds to wait before auto-holding (long-press method). */ private static final int AUTOHOLD_LONGPRESS_TIME = 1000; /** The number of milliseconds of vibration when auto-hold is engaged. */ private static final int AUTOHOLD_VIBRATE_TIME = 100; /** The maximum number of pointers to query. */ private static final int MAX_POINTER_IDS = 256; /** The state change listener. */ private final OnStateChangedListener mListener; /** The map from screen coordinates to N64 controls. */ private final TouchMap mTouchMap; /** The map from pointer ids to N64 controls. */ private final SparseIntArray mPointerMap = new SparseIntArray(); /** Whether the analog stick should be constrained to an octagon. */ private final boolean mIsOctagonal; /** The method used for auto-holding buttons. */ private final int mAutoHoldMethod; /** The touch state of each pointer. True indicates down, false indicates up. */ private final boolean[] mTouchState = new boolean[MAX_POINTER_IDS]; /** The x-coordinate of each pointer, between 0 and (screenwidth-1), inclusive. */ private final int[] mPointerX = new int[MAX_POINTER_IDS]; /** The y-coordinate of each pointer, between 0 and (screenheight-1), inclusive. */ private final int[] mPointerY = new int[MAX_POINTER_IDS]; /** The pressed start time of each pointer. */ private final long[] mStartTime = new long[MAX_POINTER_IDS]; /** The time between press and release of each pointer. */ private final long[] mElapsedTime = new long[MAX_POINTER_IDS]; /** * The identifier of the pointer associated with the analog stick. -1 indicates the stick has * been released. */ private int mAnalogPid = -1; /** The touch event source to listen to, or 0 to listen to all sources. */ private int mSourceFilter = 0; private Vibrator mVibrator = null; /** * Instantiates a new touch controller. * * @param touchMap The map from touch coordinates to N64 controls. * @param view The view receiving touch event data. * @param listener The listener for controller state changes. * @param isOctagonal True if the analog stick should be constrained to an octagon. */ public TouchController( TouchMap touchMap, View view, OnStateChangedListener listener, boolean isOctagonal, Vibrator vibrator, int autoHoldMethod ) { mListener = listener; mTouchMap = touchMap; mIsOctagonal = isOctagonal; view.setOnTouchListener( this ); mVibrator = vibrator; mAutoHoldMethod = autoHoldMethod; } /** * Sets the touch event source filter. * * @param source The source to listen to, or 0 to listen to all sources. */ public void setSourceFilter( int source ) { mSourceFilter = source; } /* * (non-Javadoc) * * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent) */ @Override @TargetApi( 9 ) public boolean onTouch( View view, MotionEvent event ) { // Eclair is needed for multi-touch tracking (getPointerId, getPointerCount) if( !AppData.IS_ECLAIR ) return false; // Filter by source, if applicable int source = AppData.IS_GINGERBREAD ? event.getSource() : 0; if( mSourceFilter != 0 && mSourceFilter != source ) return false; int action = event.getAction(); int actionCode = action & MotionEvent.ACTION_MASK; int pid = -1; switch( actionCode ) { case MotionEvent.ACTION_POINTER_DOWN: // A non-primary touch has been made pid = event.getPointerId( action >> MotionEvent.ACTION_POINTER_INDEX_SHIFT ); mStartTime[pid] = System.currentTimeMillis(); mTouchState[pid] = true; break; case MotionEvent.ACTION_POINTER_UP: // A non-primary touch has been released pid = event.getPointerId( action >> MotionEvent.ACTION_POINTER_INDEX_SHIFT ); mElapsedTime[pid] = System.currentTimeMillis() - mStartTime[pid]; mTouchState[pid] = false; break; case MotionEvent.ACTION_DOWN: // A touch gesture has started (e.g. analog stick movement) for( int i = 0; i < event.getPointerCount(); i++ ) { pid = event.getPointerId( i ); mStartTime[pid] = System.currentTimeMillis(); mTouchState[pid] = true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: // A touch gesture has ended or canceled (e.g. analog stick movement) for( int i = 0; i < event.getPointerCount(); i++ ) { pid = event.getPointerId( i ); mElapsedTime[pid] = System.currentTimeMillis() - mStartTime[pid]; mTouchState[pid] = false; } break; default: break; } // Update the coordinates of down pointers and record max PID for speed int maxPid = -1; for( int i = 0; i < event.getPointerCount(); i++ ) { pid = event.getPointerId( i ); if( pid > maxPid ) maxPid = pid; if( mTouchState[pid] ) { mPointerX[pid] = (int) event.getX( i ); mPointerY[pid] = (int) event.getY( i ); } } // Process each touch processTouches( mTouchState, mPointerX, mPointerY, mElapsedTime, maxPid ); return true; } /** * Sets the N64 controller state based on where the screen is (multi-) touched. Values outside * the ranges listed below are safe. * * @param touchstate The touch state of each pointer. True indicates down, false indicates up. * @param pointerX The x-coordinate of each pointer, between 0 and (screenwidth-1), inclusive. * @param pointerY The y-coordinate of each pointer, between 0 and (screenheight-1), inclusive. * @param maxPid Maximum ID of the pointers that have changed (speed optimization). */ private void processTouches( boolean[] touchstate, int[] pointerX, int[] pointerY, long[] elapsedTime, int maxPid ) { boolean analogMoved = false; // Process each pointer in sequence for( int pid = 0; pid <= maxPid; pid++ ) { // Release analog if its pointer is not touching the screen if( pid == mAnalogPid && !touchstate[pid] ) { analogMoved = true; mAnalogPid = -1; mState.axisFractionX = 0; mState.axisFractionY = 0; } // Process button inputs if( pid != mAnalogPid ) processButtonTouch( touchstate[pid], pointerX[pid], pointerY[pid], elapsedTime[pid], pid ); // Process analog inputs if( touchstate[pid] && processAnalogTouch( pid, pointerX[pid], pointerY[pid] ) ) analogMoved = true; } // Call the super method to send the input to the core notifyChanged(); // Update the skin if the virtual analog stick moved if( analogMoved && mListener != null ) mListener.onAnalogChanged( mState.axisFractionX, mState.axisFractionY ); } /** * Process a touch as if intended for a button. Values outside the ranges listed below are safe. * * @param touched Whether the button is pressed. * @param xLocation The x-coordinate of the touch, between 0 and (screenwidth-1), inclusive. * @param yLocation The y-coordinate of the touch, between 0 and (screenheight-1), inclusive. * @param pid The identifier of the touch pointer. */ private void processButtonTouch( boolean touched, int xLocation, int yLocation, long timeElapsed, int pid ) { // Determine the index of the button that was pressed int index = touched ? mTouchMap.getButtonPress( xLocation, yLocation ) : mPointerMap.get( pid, TouchMap.UNMAPPED ); // Update the pointer map if( !touched ) { mPointerMap.delete( pid ); } else { // Check if this pointer was already mapped to a button int prevIndex = mPointerMap.get( pid ); // Record the new button index in the map mPointerMap.put( pid, index ); // If mapped to a different button previously, take various actions if( prevIndex != index ) { // Reset auto-hold start time mStartTime[pid] = System.currentTimeMillis(); if( prevIndex != TouchMap.UNMAPPED ) { if( mTouchMap.autoHoldImages[prevIndex] == null ) { // Release previous (non-auto-hold) button setTouchState( prevIndex, false ); } else { switch( mAutoHoldMethod ) { case AUTOHOLD_METHOD_LONGPRESS: // Release previous auto-hold button (long-press method) - mListener.onAutoHold( false, prevIndex ); + if( mListener != null ) + mListener.onAutoHold( false, prevIndex ); break; case AUTOHOLD_METHOD_SLIDEOUT: if( index == TouchMap.UNMAPPED ) { // Auto-hold previous button (slide-out method) mVibrator.vibrate( AUTOHOLD_VIBRATE_TIME ); - mListener.onAutoHold( true, prevIndex ); + if( mListener != null ) + mListener.onAutoHold( true, prevIndex ); setTouchState( prevIndex, true ); } break; } } } } } if( index != TouchMap.UNMAPPED ) { if( mTouchMap.autoHoldImages[index] == null ) { // Press and release (non-auto-hold) button setTouchState( index, touched ); } else { if( touched ) setTouchState( index, true ); else { switch( mAutoHoldMethod ) { case AUTOHOLD_METHOD_LONGPRESS: if( timeElapsed < AUTOHOLD_LONGPRESS_TIME ) { // Release auto-hold button if < 1 second (long-press method) - mListener.onAutoHold( false, index ); + if( mListener != null ) + mListener.onAutoHold( false, index ); setTouchState( index, false ); } else { // Auto-hold button if > 1 second (long-press method) mVibrator.vibrate( AUTOHOLD_VIBRATE_TIME ); - mListener.onAutoHold( true, index ); + if( mListener != null ) + mListener.onAutoHold( true, index ); setTouchState( index, true ); } break; case AUTOHOLD_METHOD_SLIDEOUT: // Release autoHold button (slide-out method) - mListener.onAutoHold( false, index ); + if( mListener != null ) + mListener.onAutoHold( false, index ); setTouchState( index, false ); break; } } } } } /** * Sets the state of a button, and handles the D-Pad diagonals. * * @param index Which button is affected. * @param touched Whether the button is pressed. */ private void setTouchState( int index, boolean touched ) { // Set the button state if( index < AbstractController.NUM_N64_BUTTONS ) { // A single button was pressed mState.buttons[index] = touched; } else { // Two d-pad buttons pressed simultaneously switch( index ) { case TouchMap.DPD_RU: mState.buttons[DPD_R] = touched; mState.buttons[DPD_U] = touched; break; case TouchMap.DPD_RD: mState.buttons[DPD_R] = touched; mState.buttons[DPD_D] = touched; break; case TouchMap.DPD_LD: mState.buttons[DPD_L] = touched; mState.buttons[DPD_D] = touched; break; case TouchMap.DPD_LU: mState.buttons[DPD_L] = touched; mState.buttons[DPD_U] = touched; break; default: break; } } } /** * Process a touch as if intended for the analog stick. Values outside the ranges listed below * are safe. * * @param pointerId The pointer identifier. * @param xLocation The x-coordinate of the touch, between 0 and (screenwidth-1), inclusive. * @param yLocation The y-coordinate of the touch, between 0 and (screenheight-1), inclusive. * @return True, if the analog state changed. */ private boolean processAnalogTouch( int pointerId, int xLocation, int yLocation ) { // Get the cartesian displacement of the analog stick Point point = mTouchMap.getAnalogDisplacement( xLocation, yLocation ); // Compute the pythagorean displacement of the stick int dX = point.x; int dY = point.y; float displacement = FloatMath.sqrt( ( dX * dX ) + ( dY * dY ) ); // "Capture" the analog control if( mTouchMap.isInCaptureRange( displacement ) ) mAnalogPid = pointerId; if( pointerId == mAnalogPid ) { // User is controlling the analog stick if( mIsOctagonal ) { // Limit range of motion to an octagon (like the real N64 controller) point = mTouchMap.getConstrainedDisplacement( dX, dY ); dX = point.x; dY = point.y; displacement = FloatMath.sqrt( ( dX * dX ) + ( dY * dY ) ); } // Fraction of full-throttle, between 0 and 1, inclusive float p = mTouchMap.getAnalogStrength( displacement ); // Store the axis values in the super fields (screen y is inverted) mState.axisFractionX = p * dX / displacement; mState.axisFractionY = -p * dY / displacement; // Analog state changed return true; } // Analog state did not change return false; } }
false
true
private void processButtonTouch( boolean touched, int xLocation, int yLocation, long timeElapsed, int pid ) { // Determine the index of the button that was pressed int index = touched ? mTouchMap.getButtonPress( xLocation, yLocation ) : mPointerMap.get( pid, TouchMap.UNMAPPED ); // Update the pointer map if( !touched ) { mPointerMap.delete( pid ); } else { // Check if this pointer was already mapped to a button int prevIndex = mPointerMap.get( pid ); // Record the new button index in the map mPointerMap.put( pid, index ); // If mapped to a different button previously, take various actions if( prevIndex != index ) { // Reset auto-hold start time mStartTime[pid] = System.currentTimeMillis(); if( prevIndex != TouchMap.UNMAPPED ) { if( mTouchMap.autoHoldImages[prevIndex] == null ) { // Release previous (non-auto-hold) button setTouchState( prevIndex, false ); } else { switch( mAutoHoldMethod ) { case AUTOHOLD_METHOD_LONGPRESS: // Release previous auto-hold button (long-press method) mListener.onAutoHold( false, prevIndex ); break; case AUTOHOLD_METHOD_SLIDEOUT: if( index == TouchMap.UNMAPPED ) { // Auto-hold previous button (slide-out method) mVibrator.vibrate( AUTOHOLD_VIBRATE_TIME ); mListener.onAutoHold( true, prevIndex ); setTouchState( prevIndex, true ); } break; } } } } } if( index != TouchMap.UNMAPPED ) { if( mTouchMap.autoHoldImages[index] == null ) { // Press and release (non-auto-hold) button setTouchState( index, touched ); } else { if( touched ) setTouchState( index, true ); else { switch( mAutoHoldMethod ) { case AUTOHOLD_METHOD_LONGPRESS: if( timeElapsed < AUTOHOLD_LONGPRESS_TIME ) { // Release auto-hold button if < 1 second (long-press method) mListener.onAutoHold( false, index ); setTouchState( index, false ); } else { // Auto-hold button if > 1 second (long-press method) mVibrator.vibrate( AUTOHOLD_VIBRATE_TIME ); mListener.onAutoHold( true, index ); setTouchState( index, true ); } break; case AUTOHOLD_METHOD_SLIDEOUT: // Release autoHold button (slide-out method) mListener.onAutoHold( false, index ); setTouchState( index, false ); break; } } } } }
private void processButtonTouch( boolean touched, int xLocation, int yLocation, long timeElapsed, int pid ) { // Determine the index of the button that was pressed int index = touched ? mTouchMap.getButtonPress( xLocation, yLocation ) : mPointerMap.get( pid, TouchMap.UNMAPPED ); // Update the pointer map if( !touched ) { mPointerMap.delete( pid ); } else { // Check if this pointer was already mapped to a button int prevIndex = mPointerMap.get( pid ); // Record the new button index in the map mPointerMap.put( pid, index ); // If mapped to a different button previously, take various actions if( prevIndex != index ) { // Reset auto-hold start time mStartTime[pid] = System.currentTimeMillis(); if( prevIndex != TouchMap.UNMAPPED ) { if( mTouchMap.autoHoldImages[prevIndex] == null ) { // Release previous (non-auto-hold) button setTouchState( prevIndex, false ); } else { switch( mAutoHoldMethod ) { case AUTOHOLD_METHOD_LONGPRESS: // Release previous auto-hold button (long-press method) if( mListener != null ) mListener.onAutoHold( false, prevIndex ); break; case AUTOHOLD_METHOD_SLIDEOUT: if( index == TouchMap.UNMAPPED ) { // Auto-hold previous button (slide-out method) mVibrator.vibrate( AUTOHOLD_VIBRATE_TIME ); if( mListener != null ) mListener.onAutoHold( true, prevIndex ); setTouchState( prevIndex, true ); } break; } } } } } if( index != TouchMap.UNMAPPED ) { if( mTouchMap.autoHoldImages[index] == null ) { // Press and release (non-auto-hold) button setTouchState( index, touched ); } else { if( touched ) setTouchState( index, true ); else { switch( mAutoHoldMethod ) { case AUTOHOLD_METHOD_LONGPRESS: if( timeElapsed < AUTOHOLD_LONGPRESS_TIME ) { // Release auto-hold button if < 1 second (long-press method) if( mListener != null ) mListener.onAutoHold( false, index ); setTouchState( index, false ); } else { // Auto-hold button if > 1 second (long-press method) mVibrator.vibrate( AUTOHOLD_VIBRATE_TIME ); if( mListener != null ) mListener.onAutoHold( true, index ); setTouchState( index, true ); } break; case AUTOHOLD_METHOD_SLIDEOUT: // Release autoHold button (slide-out method) if( mListener != null ) mListener.onAutoHold( false, index ); setTouchState( index, false ); break; } } } } }
diff --git a/2012/11/13/src/StaticBitSet.java b/2012/11/13/src/StaticBitSet.java index 459c0d6..66603b7 100644 --- a/2012/11/13/src/StaticBitSet.java +++ b/2012/11/13/src/StaticBitSet.java @@ -1,61 +1,62 @@ import java.util.Arrays; public class StaticBitSet { long[] data; public StaticBitSet(int sizeinbits) { data = new long[(sizeinbits + 63) / 64]; } void clear() { Arrays.fill(data, 0); } public void resize(int sizeinbits) { data = Arrays.copyOf(data, (sizeinbits + 63) / 64); } public int cardinality() { int sum = 0; for(long l : data) sum += Long.bitCount(l); return sum; } public boolean get(int i) { return (data[i / 64] & (1l << (i % 64))) !=0; } public void set(int i) { data[i / 64] |= (1l << (i % 64)); } public void unset(int i) { data[i / 64] &= ~(1l << (i % 64)); } public void set(int i, boolean b) { if(b) set(i); else unset(i); } // for(int i=bs.nextSetBit(0); i>=0; i=bs.nextSetBit(i+1)) { // operate on // index i here } public int nextSetBit(int i) { int x = i / 64; + if(x>=data.length) return -1; long w = data[x]; w >>>= (i % 64); if (w != 0) { return i + Long.numberOfTrailingZeros(w); } ++x; for (; x < data.length; ++x) { if (data[x] != 0) { return x * 64 + Long.numberOfTrailingZeros(data[x]); } } return -1; } }
true
true
public int nextSetBit(int i) { int x = i / 64; long w = data[x]; w >>>= (i % 64); if (w != 0) { return i + Long.numberOfTrailingZeros(w); } ++x; for (; x < data.length; ++x) { if (data[x] != 0) { return x * 64 + Long.numberOfTrailingZeros(data[x]); } } return -1; }
public int nextSetBit(int i) { int x = i / 64; if(x>=data.length) return -1; long w = data[x]; w >>>= (i % 64); if (w != 0) { return i + Long.numberOfTrailingZeros(w); } ++x; for (; x < data.length; ++x) { if (data[x] != 0) { return x * 64 + Long.numberOfTrailingZeros(data[x]); } } return -1; }
diff --git a/src/main/java/de/cinovo/q/query/type/impl/TypeSymbol.java b/src/main/java/de/cinovo/q/query/type/impl/TypeSymbol.java index 2c17d14..3641f9c 100644 --- a/src/main/java/de/cinovo/q/query/type/impl/TypeSymbol.java +++ b/src/main/java/de/cinovo/q/query/type/impl/TypeSymbol.java @@ -1,60 +1,60 @@ // ------------------------------------------------------------------------------- // Copyright (c) 2011-2012 Cinovo AG // All rights reserved. This program and the accompanying materials // are made available under the terms of the Apache License, Version 2.0 // which accompanies this distribution, and is available at // http://www.apache.org/licenses/LICENSE-2.0.html // ------------------------------------------------------------------------------- package de.cinovo.q.query.type.impl; import de.cinovo.q.query.type.NominalType; import de.cinovo.q.query.type.Type; import de.cinovo.q.query.type.ValueFactory; import de.cinovo.q.query.value.Value; import de.cinovo.q.query.value.impl.SymbolValue; /** * Symbol. * * @author mwittig * */ public final class TypeSymbol implements NominalType<String> { /** Instance. */ private static final TypeSymbol INSTANCE = new TypeSymbol(); /** * @return Instance */ public static TypeSymbol get() { return TypeSymbol.INSTANCE; } @Override public ValueFactory<String, Type<String>> geValueFactory() { return new ValueFactory<String, Type<String>>() { @Override public Value<String, ? extends Type<String>> create(final String value) { return SymbolValue.from(value); } @Override public Value<String, ? extends Type<String>> fromQ(final Object value) { if (value instanceof String) { return this.create((String) value); - } // TODO what to do woth Lists String[] ??? + } throw new IllegalArgumentException("Type is " + value.getClass().getSimpleName()); } }; } /** */ private TypeSymbol() { super(); } }
true
true
public ValueFactory<String, Type<String>> geValueFactory() { return new ValueFactory<String, Type<String>>() { @Override public Value<String, ? extends Type<String>> create(final String value) { return SymbolValue.from(value); } @Override public Value<String, ? extends Type<String>> fromQ(final Object value) { if (value instanceof String) { return this.create((String) value); } // TODO what to do woth Lists String[] ??? throw new IllegalArgumentException("Type is " + value.getClass().getSimpleName()); } }; }
public ValueFactory<String, Type<String>> geValueFactory() { return new ValueFactory<String, Type<String>>() { @Override public Value<String, ? extends Type<String>> create(final String value) { return SymbolValue.from(value); } @Override public Value<String, ? extends Type<String>> fromQ(final Object value) { if (value instanceof String) { return this.create((String) value); } throw new IllegalArgumentException("Type is " + value.getClass().getSimpleName()); } }; }
diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/CommonViewerAdvisor.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/CommonViewerAdvisor.java index df9131b36..97c1f4a96 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/CommonViewerAdvisor.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/mapping/CommonViewerAdvisor.java @@ -1,507 +1,508 @@ /******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.team.internal.ui.mapping; import java.util.*; import org.eclipse.core.resources.mapping.*; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.action.*; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.*; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.*; import org.eclipse.team.core.TeamException; import org.eclipse.team.core.mapping.*; import org.eclipse.team.internal.ui.TeamUIPlugin; import org.eclipse.team.internal.ui.Utils; import org.eclipse.team.internal.ui.synchronize.AbstractTreeViewerAdvisor; import org.eclipse.team.internal.ui.synchronize.SynchronizePageConfiguration; import org.eclipse.team.ui.TeamUI; import org.eclipse.team.ui.mapping.*; import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration; import org.eclipse.team.ui.synchronize.ModelSynchronizeParticipant; import org.eclipse.ui.*; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.navigator.*; import org.eclipse.ui.navigator.resources.ResourceDragAdapterAssistant; import org.eclipse.ui.part.IPageSite; /** * Provides a Common Navigator based viewer for use by a {@link ModelSynchronizePage}. */ public class CommonViewerAdvisor extends AbstractTreeViewerAdvisor implements INavigatorContentServiceListener, IEmptyTreeListener, IPropertyChangeListener { public static final class NavigableCommonViewer extends CommonViewer implements ITreeViewerAccessor { private final IEmptyTreeListener listener; private boolean empty; private NavigableCommonViewer(String id, Composite parent, int style, IEmptyTreeListener listener) { super(id, parent, style); this.listener = listener; } public void createChildren(TreeItem item) { super.createChildren(item); } public void openSelection() { fireOpen(new OpenEvent(this, getSelection())); } protected void internalRefresh(Object element, boolean updateLabels) { TreePath[] expanded = getVisibleExpandedPaths(); super.internalRefresh(element, updateLabels); setExpandedTreePaths(expanded); checkForEmptyViewer(); } protected void internalRemove(Object parent, Object[] elements) { super.internalRemove(parent, elements); if (parent == getInput()) checkForEmptyViewer(); } protected void internalRemove(Object[] elements) { super.internalRemove(elements); checkForEmptyViewer(); } protected void internalAdd(Widget widget, Object parentElement, Object[] childElements) { super.internalAdd(widget, parentElement, childElements); if (empty) { empty = false; listener.notEmpty(this); } } protected void inputChanged(Object input, Object oldInput) { super.inputChanged(input, oldInput); checkForEmptyViewer(); } private void checkForEmptyViewer() { Object input = getInput(); if (input != null) { Widget w = findItem(input); Item[] children = getChildren(w); if (children.length == 0) { if (!empty) { empty = true; listener.treeEmpty(this); } return; } } empty = false; if (listener != null) listener.notEmpty(this); } public boolean isEmpty() { return empty; } protected void initDragAndDrop() { getNavigatorContentService().getDnDService().bindDragAssistant(new ResourceDragAdapterAssistant()); super.initDragAndDrop(); } /** * Gets the expanded elements that are visible to the user. An expanded * element is only visible if the parent is expanded. * * @return the visible expanded elements * @since 2.0 */ public TreePath[] getVisibleExpandedPaths() { ArrayList v = new ArrayList(); internalCollectVisibleExpanded(v, getControl()); return (TreePath[]) v.toArray(new TreePath[v.size()]); } private void internalCollectVisibleExpanded(ArrayList result, Widget widget) { Item[] items = getChildren(widget); for (int i = 0; i < items.length; i++) { Item item = items[i]; if (getExpanded(item)) { TreePath path = getTreePathFromItem(item); if (path != null) { result.add(path); } //Only recurse if it is expanded - if //not then the children aren't visible internalCollectVisibleExpanded(result, item); } } } } /** * Subclass of SubActionBars that manages the contributions from the common action service */ private class CommonSubActionBars extends SubActionBars { public CommonSubActionBars(IActionBars parent) { super(parent); } public void setGlobalActionHandler(String actionID, IAction handler) { if (handler == null) { // Only remove the handler if it was set if (getGlobalActionHandler(actionID) != null) { getParent().setGlobalActionHandler(actionID, null); super.setGlobalActionHandler(actionID, null); } } else { // Only set the action handler if the parent doesn't if (getParent().getGlobalActionHandler(actionID) != null) { TeamUIPlugin.log(new TeamException(NLS.bind("Conflicting attempt to set action id {0} detected", actionID))); //$NON-NLS-1$ return; } super.setGlobalActionHandler(actionID, handler); } } public void clearGlobalActionHandlers() { // When cleared, also remove the ids from the parent Map handlers = getGlobalActionHandlers(); if (handlers != null) { Set keys = handlers.keySet(); Iterator iter = keys.iterator(); while (iter.hasNext()) { String actionId = (String) iter.next(); getParent().setGlobalActionHandler(actionId, null); } } super.clearGlobalActionHandlers(); } public void updateActionBars() { // On update, push all or action handlers into our parent Map newActionHandlers = getGlobalActionHandlers(); if (newActionHandlers != null) { Set keys = newActionHandlers.entrySet(); Iterator iter = keys.iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); getParent().setGlobalActionHandler((String) entry.getKey(), (IAction) entry.getValue()); } } super.updateActionBars(); } } public static final String TEAM_NAVIGATOR_CONTENT = "org.eclipse.team.ui.navigatorViewer"; //$NON-NLS-1$ private static final String PROP_ACTION_SERVICE_ACTION_BARS = "org.eclipse.team.ui.actionServiceActionBars"; //$NON-NLS-1$ private Set extensions = new HashSet(); private NavigatorActionService actionService; private IEmptyTreeListener emptyTreeListener; /** * Create a common viewer * @param parent the parent composite of the common viewer * @param configuration the configuration for the viewer * @return a newly created common viewer */ private static CommonViewer createViewer(Composite parent, final ISynchronizePageConfiguration configuration, IEmptyTreeListener listener) { final CommonViewer v = new NavigableCommonViewer(configuration.getViewerId(), parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL, listener); v.setSorter(new CommonViewerSorter()); v.setSorter(new TeamViewerSorter((CommonViewerSorter)v.getSorter())); ISynchronizationScope scope = getScope(configuration); bindTeamContentProviders(v); scope.addScopeChangeListener(new ISynchronizationScopeChangeListener() { public void scopeChanged(final ISynchronizationScope scope, ResourceMapping[] newMappings, ResourceTraversal[] newTraversals) { enableContentProviders(v, configuration); Utils.asyncExec(new Runnable() { public void run() { v.refresh(); } }, v); } }); enableContentProviders(v, configuration); configuration.getSite().setSelectionProvider(v); return v; } private static void enableContentProviders(CommonViewer v, ISynchronizePageConfiguration configuration) { v.getNavigatorContentService().getActivationService().activateExtensions(getEnabledContentProviders(configuration), true); } private static String[] getEnabledContentProviders(ISynchronizePageConfiguration configuration) { String visibleModel = (String)configuration.getProperty(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER); if (visibleModel != null && !visibleModel.equals(ModelSynchronizeParticipant.ALL_MODEL_PROVIDERS_VISIBLE)) { ITeamContentProviderDescriptor desc = TeamUI.getTeamContentProviderManager().getDescriptor(visibleModel); if (desc != null && desc.isEnabled()) return new String[] { desc.getContentExtensionId() }; } configuration.setProperty(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER, ModelSynchronizeParticipant.ALL_MODEL_PROVIDERS_VISIBLE); ModelSynchronizeParticipant participant = (ModelSynchronizeParticipant)configuration.getParticipant(); ModelProvider[] providers = participant.getEnabledModelProviders(); Set result = new HashSet(); Object property = configuration.getProperty(ITeamContentProviderManager.PROP_PAGE_LAYOUT); boolean isFlatLayout = property != null && property.equals(ITeamContentProviderManager.FLAT_LAYOUT); for (int i = 0; i < providers.length; i++) { ModelProvider provider = providers[i]; ITeamContentProviderDescriptor desc = TeamUI.getTeamContentProviderManager().getDescriptor(provider.getId()); if (desc != null && desc.isEnabled() && (!isFlatLayout || desc.isFlatLayoutSupported())) result.add(desc.getContentExtensionId()); } return (String[]) result.toArray(new String[result.size()]); } private static void bindTeamContentProviders(CommonViewer v) { ITeamContentProviderManager teamContentProviderManager = TeamUI.getTeamContentProviderManager(); ITeamContentProviderDescriptor[] descriptors = teamContentProviderManager.getDescriptors(); Set toBind = new HashSet(); for (int i = 0; i < descriptors.length; i++) { ITeamContentProviderDescriptor descriptor = descriptors[i]; toBind.add(descriptor.getContentExtensionId()); } v.getNavigatorContentService().bindExtensions((String[]) toBind.toArray(new String[toBind.size()]), true); } private static ISynchronizationScope getScope(ISynchronizePageConfiguration configuration) { return (ISynchronizationScope)configuration.getProperty(ITeamContentProviderManager.P_SYNCHRONIZATION_SCOPE); } /** * Create the advisor using the given configuration * @param parent the parent * @param configuration the configuration */ public CommonViewerAdvisor(Composite parent, ISynchronizePageConfiguration configuration) { super(configuration); final CommonViewer viewer = CommonViewerAdvisor.createViewer(parent, configuration, this); TeamUI.getTeamContentProviderManager().addPropertyChangeListener(this); configuration.addPropertyChangeListener(this); GridData data = new GridData(GridData.FILL_BOTH); viewer.getControl().setLayoutData(data); viewer.getNavigatorContentService().addListener(this); initializeViewer(viewer); IBaseLabelProvider provider = viewer.getLabelProvider(); if (provider instanceof DecoratingLabelProvider) { DecoratingLabelProvider dlp = (DecoratingLabelProvider) provider; ILabelDecorator decorator = ((SynchronizePageConfiguration)configuration).getLabelDecorator(); if (decorator != null) { ILabelProvider lp = dlp.getLabelProvider(); dlp = new DecoratingLabelProvider( new DecoratingLabelProvider(lp, decorator), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()); viewer.setLabelProvider(dlp); } DecorationContext decorationContext = new DecorationContext(); decorationContext.putProperty(SynchronizationStateTester.PROP_TESTER, new SynchronizationStateTester() { public boolean isStateDecorationEnabled() { return false; } }); + decorationContext.putProperty(IDecoration.DISABLE_REPLACE, Boolean.TRUE); dlp.setDecorationContext(decorationContext); } } public void setInitialInput() { CommonViewer viewer = (CommonViewer)getViewer(); viewer.setInput(getInitialInput()); viewer.expandToLevel(2); } /* (non-Javadoc) * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#initializeViewer(org.eclipse.jface.viewers.StructuredViewer) */ public void initializeViewer(StructuredViewer viewer) { createActionService((CommonViewer)viewer, getConfiguration()); super.initializeViewer(viewer); } private void createActionService(CommonViewer viewer, ISynchronizePageConfiguration configuration) { ICommonViewerSite commonSite = createCommonViewerSite(viewer, configuration); actionService = new NavigatorActionService(commonSite, viewer, viewer.getNavigatorContentService()); } private ICommonViewerSite createCommonViewerSite(CommonViewer viewer, ISynchronizePageConfiguration configuration) { IWorkbenchSite site = configuration.getSite().getWorkbenchSite(); if (site instanceof IEditorSite) { IEditorSite es = (IEditorSite) site; return CommonViewerSiteFactory.createCommonViewerSite(es); } if (site instanceof IViewSite) { IViewSite vs = (IViewSite) site; return CommonViewerSiteFactory.createCommonViewerSite(vs); } if (site instanceof IPageSite) { IPageSite ps = (IPageSite) site; return CommonViewerSiteFactory.createCommonViewerSite(configuration.getViewerId(), ps); } return CommonViewerSiteFactory.createCommonViewerSite(configuration.getViewerId(), viewer, configuration.getSite().getShell()); } private Object getInitialInput() { String visible = (String)getConfiguration().getProperty(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER); if (visible != null && !visible.equals(ModelSynchronizeParticipant.ALL_MODEL_PROVIDERS_VISIBLE)) { try { IModelProviderDescriptor desc = ModelProvider.getModelProviderDescriptor(visible); if (desc != null) return desc.getModelProvider(); } catch (CoreException e) { TeamUIPlugin.log(e); } } return getConfiguration().getProperty(ITeamContentProviderManager.P_SYNCHRONIZATION_CONTEXT); } /* (non-Javadoc) * @see org.eclipse.ui.navigator.internal.extensions.INavigatorContentServiceListener#onLoad(org.eclipse.ui.navigator.internal.extensions.NavigatorContentExtension) */ public void onLoad(INavigatorContentExtension anExtension) { extensions.add(anExtension); ISynchronizationContext context = getParticipant().getContext(); anExtension.getStateModel().setProperty(ITeamContentProviderManager.P_SYNCHRONIZATION_SCOPE, context.getScope()); anExtension.getStateModel().setProperty(ITeamContentProviderManager.P_SYNCHRONIZATION_PAGE_CONFIGURATION, getConfiguration()); anExtension.getStateModel().setProperty(ITeamContentProviderManager.P_SYNCHRONIZATION_CONTEXT, context); } private ModelSynchronizeParticipant getParticipant() { return (ModelSynchronizeParticipant)getConfiguration().getParticipant(); } /* (non-Javadoc) * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#getContextMenuId(org.eclipse.jface.viewers.StructuredViewer) */ protected String getContextMenuId(StructuredViewer viewer) { return ((CommonViewer)viewer).getNavigatorContentService().getViewerDescriptor().getPopupMenuId(); } /* (non-Javadoc) * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#registerContextMenu(org.eclipse.jface.viewers.StructuredViewer, org.eclipse.jface.action.MenuManager) */ protected void registerContextMenu(StructuredViewer viewer, MenuManager menuMgr) { actionService.prepareMenuForPlatformContributions(menuMgr, viewer, false); } /* (non-Javadoc) * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#fillContextMenu(org.eclipse.jface.viewers.StructuredViewer, org.eclipse.jface.action.IMenuManager) */ protected void fillContextMenu(StructuredViewer viewer, IMenuManager manager) { // Clear any handlers from the menu if (manager instanceof CommonMenuManager) { CommonMenuManager cmm = (CommonMenuManager) manager; cmm.clearHandlers(); } // Add the actions from the service (which willal so add the groups) ISelection selection = getViewer().getSelection(); actionService.setContext(new ActionContext(selection)); actionService.fillContextMenu(manager); // Add any programmatic menu items super.fillContextMenu(viewer, manager); } /* (non-Javadoc) * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#dispose() */ public void dispose() { TeamUI.getTeamContentProviderManager().removePropertyChangeListener(this); getConfiguration().removePropertyChangeListener(this); actionService.dispose(); super.dispose(); } /* (non-Javadoc) * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#updateActionBars(org.eclipse.jface.viewers.IStructuredSelection) */ protected void updateActionBars(IStructuredSelection selection) { super.updateActionBars(selection); if (!getConfiguration().getSite().isModal()) { actionService.setContext(new ActionContext(selection)); // This is non-standard behavior that is required by the common navigator framework (see bug 122808) SubActionBars subActionBars = (SubActionBars)getConfiguration().getProperty(PROP_ACTION_SERVICE_ACTION_BARS); if (subActionBars == null) { subActionBars = new CommonSubActionBars(getConfiguration().getSite().getActionBars()); getConfiguration().setProperty(PROP_ACTION_SERVICE_ACTION_BARS, subActionBars); } actionService.fillActionBars(subActionBars); } } /* (non-Javadoc) * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#createContextMenuManager(java.lang.String) */ protected MenuManager createContextMenuManager(String targetID) { return new CommonMenuManager(targetID); } /* (non-Javadoc) * @see org.eclipse.team.internal.ui.synchronize.StructuredViewerAdvisor#addContextMenuGroups(org.eclipse.jface.action.IMenuManager) */ protected void addContextMenuGroups(IMenuManager manager) { // Don't do anything. The groups will be added by the action service } public void addEmptyTreeListener(IEmptyTreeListener emptyTreeListener) { this.emptyTreeListener = emptyTreeListener; } public void treeEmpty(TreeViewer viewer) { if (emptyTreeListener != null) emptyTreeListener.treeEmpty(viewer); } public void notEmpty(TreeViewer viewer) { if (emptyTreeListener != null) emptyTreeListener.notEmpty(viewer); } public void propertyChange(final PropertyChangeEvent event) { if (event.getProperty().equals(ITeamContentProviderManager.PROP_ENABLED_MODEL_PROVIDERS)) { enableContentProviders((CommonViewer)getViewer(), getConfiguration()); } else if (event.getProperty().equals(ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER)) { enableContentProviders((CommonViewer)getViewer(), getConfiguration()); final Viewer viewer = getViewer(); Utils.syncExec(new Runnable() { public void run() { Object viewerInput = ModelSynchronizePage.getViewerInput(getConfiguration(), (String)event.getNewValue()); if (viewer != null && viewerInput != null) { viewer.setInput(viewerInput); } } }, (StructuredViewer)viewer); } else if (event.getProperty().equals(ITeamContentProviderManager.PROP_PAGE_LAYOUT)) { // TODO enableContentProviders((CommonViewer)getViewer(), getConfiguration()); } } protected boolean handleDoubleClick(StructuredViewer viewer, DoubleClickEvent event) { if (isOpenable(event.getSelection())) { return true; } return super.handleDoubleClick(viewer, event); } private boolean isOpenable(ISelection selection) { IStructuredSelection ss = (IStructuredSelection) selection; Object object = ss.getFirstElement(); if (object == null) return false; return getParticipant().hasCompareInputFor(object); } protected void expandToNextDiff(Object element) { ((TreeViewer)getViewer()).expandToLevel(element, AbstractTreeViewer.ALL_LEVELS); } }
true
true
public CommonViewerAdvisor(Composite parent, ISynchronizePageConfiguration configuration) { super(configuration); final CommonViewer viewer = CommonViewerAdvisor.createViewer(parent, configuration, this); TeamUI.getTeamContentProviderManager().addPropertyChangeListener(this); configuration.addPropertyChangeListener(this); GridData data = new GridData(GridData.FILL_BOTH); viewer.getControl().setLayoutData(data); viewer.getNavigatorContentService().addListener(this); initializeViewer(viewer); IBaseLabelProvider provider = viewer.getLabelProvider(); if (provider instanceof DecoratingLabelProvider) { DecoratingLabelProvider dlp = (DecoratingLabelProvider) provider; ILabelDecorator decorator = ((SynchronizePageConfiguration)configuration).getLabelDecorator(); if (decorator != null) { ILabelProvider lp = dlp.getLabelProvider(); dlp = new DecoratingLabelProvider( new DecoratingLabelProvider(lp, decorator), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()); viewer.setLabelProvider(dlp); } DecorationContext decorationContext = new DecorationContext(); decorationContext.putProperty(SynchronizationStateTester.PROP_TESTER, new SynchronizationStateTester() { public boolean isStateDecorationEnabled() { return false; } }); dlp.setDecorationContext(decorationContext); } }
public CommonViewerAdvisor(Composite parent, ISynchronizePageConfiguration configuration) { super(configuration); final CommonViewer viewer = CommonViewerAdvisor.createViewer(parent, configuration, this); TeamUI.getTeamContentProviderManager().addPropertyChangeListener(this); configuration.addPropertyChangeListener(this); GridData data = new GridData(GridData.FILL_BOTH); viewer.getControl().setLayoutData(data); viewer.getNavigatorContentService().addListener(this); initializeViewer(viewer); IBaseLabelProvider provider = viewer.getLabelProvider(); if (provider instanceof DecoratingLabelProvider) { DecoratingLabelProvider dlp = (DecoratingLabelProvider) provider; ILabelDecorator decorator = ((SynchronizePageConfiguration)configuration).getLabelDecorator(); if (decorator != null) { ILabelProvider lp = dlp.getLabelProvider(); dlp = new DecoratingLabelProvider( new DecoratingLabelProvider(lp, decorator), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()); viewer.setLabelProvider(dlp); } DecorationContext decorationContext = new DecorationContext(); decorationContext.putProperty(SynchronizationStateTester.PROP_TESTER, new SynchronizationStateTester() { public boolean isStateDecorationEnabled() { return false; } }); decorationContext.putProperty(IDecoration.DISABLE_REPLACE, Boolean.TRUE); dlp.setDecorationContext(decorationContext); } }
diff --git a/core-integ/src/main/java/org/apache/directory/server/core/integ/state/AbstractState.java b/core-integ/src/main/java/org/apache/directory/server/core/integ/state/AbstractState.java index c95d8475d6..ef656d53be 100644 --- a/core-integ/src/main/java/org/apache/directory/server/core/integ/state/AbstractState.java +++ b/core-integ/src/main/java/org/apache/directory/server/core/integ/state/AbstractState.java @@ -1,250 +1,257 @@ /* * 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.directory.server.core.integ.state; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.naming.NamingException; import org.apache.directory.server.core.DirectoryService; import org.apache.directory.server.core.entry.DefaultServerEntry; import org.apache.directory.server.core.integ.InheritableSettings; import org.apache.directory.shared.ldap.ldif.LdifEntry; import org.apache.directory.shared.ldap.ldif.LdifReader; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.junit.runners.model.Statement; import org.junit.runners.model.TestClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The abstract state of a test service, containing the default state * transitions * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ public abstract class AbstractState implements TestServiceState { /** The class logger */ private static final Logger LOG = LoggerFactory.getLogger( AbstractState.class ); /** The context for this test */ protected final TestServiceContext context; /** Error message when we can't destroy the service */ private static final String DESTROY_ERR = "Cannot destroy when service is in NonExistant state"; private static final String CLEANUP_ERROR = "Cannot cleanup when service is in NonExistant state"; private static final String STARTUP_ERR = "Cannot startup when service is in NonExistant state"; private static final String SHUTDOWN_ERR = "Cannot shutdown service in NonExistant state."; private static final String REVERT_ERROR = "Cannot revert when service is in NonExistant state"; /** * * Creates a new instance of AbstractState. * * @param context The associated context */ protected AbstractState( TestServiceContext context ) { this.context = context; } /** * Action where an attempt is made to create the service. Service * creation in this system is the combined instantiation and * configuration which takes place when the factory is used to get * a new instance of the service. * * @param settings The inherited settings * @throws NamingException if we can't create the service */ public void create( InheritableSettings settings ) throws NamingException { } /** * Action where an attempt is made to destroy the service. This * entails nulling out reference to it and triggering garbage * collection. */ public void destroy() { LOG.error( DESTROY_ERR ); throw new IllegalStateException( DESTROY_ERR ); } /** * Action where an attempt is made to erase the contents of the * working directory used by the service for various files including * partition database files. * * @throws IOException on errors while deleting the working directory */ public void cleanup() throws IOException { LOG.error( CLEANUP_ERROR ); throw new IllegalStateException( CLEANUP_ERROR ); } /** * Action where an attempt is made to start up the service. * * @throws Exception on failures to start the core directory service */ public void startup() throws Exception { LOG.error( STARTUP_ERR ); throw new IllegalStateException( STARTUP_ERR ); } /** * Action where an attempt is made to shutdown the service. * * @throws Exception on failures to stop the core directory service */ public void shutdown() throws Exception { LOG.error( SHUTDOWN_ERR ); throw new IllegalStateException( SHUTDOWN_ERR ); } /** * Action where an attempt is made to run a test against the service. * * All annotations should have already been processed for * InheritableSettings yet they and others can be processed since we have * access to the method annotations below * * @param testClass the class whose test method is to be run * @param statement the test method which is to be run * @param notifier a notifier to report failures to * @param settings the inherited settings and annotations associated with * the test method */ public void test( TestClass testClass, Statement statement, RunNotifier notifier, InheritableSettings settings ) { } /** * Action where an attempt is made to revert the service to it's * initial start up state by using a previous snapshot. * * @throws Exception on failures to revert the state of the core * directory service */ public void revert() throws Exception { LOG.error( REVERT_ERROR ); throw new IllegalStateException( REVERT_ERROR ); } /** * Inject the Ldifs if any * * @param service the instantiated directory service * @param settings the settings containing the ldif */ protected void injectLdifs( DirectoryService service, InheritableSettings settings ) { List<String> ldifs = new ArrayList<String>(); List<String> ldifFiles = new ArrayList<String>(); // First inject the LDIF files if any ldifFiles = settings.getLdifFiles( ldifFiles ); if ( ldifFiles.size() != 0 ) { for ( String ldifFile:ldifFiles ) { try { String className = settings.getParent().getDescription().getDisplayName(); Class<?> clazz = Class.forName( className ); URL url = clazz.getResource( ldifFile ); URI uri = url.toURI(); File file = new File( uri ); LdifReader ldifReader = new LdifReader( file ); for ( LdifEntry entry : ldifReader ) { service.getAdminSession().add( new DefaultServerEntry( service.getRegistries(), entry.getEntry() ) ); LOG.debug( "Successfully injected LDIF enry for test {}: {}", settings.getDescription(), entry ); } } catch ( Exception e ) { LOG.error( "Cannot inject the following entry : {}. Error : {}.", ldifFile, e.getMessage() ); } } } ldifs = settings.getLdifs( ldifs ); if ( ldifs.size() != 0 ) { for ( String ldif:ldifs ) { try { StringReader in = new StringReader( ldif ); LdifReader ldifReader = new LdifReader( in ); for ( LdifEntry entry : ldifReader ) { - service.getAdminSession().add( - new DefaultServerEntry( service.getRegistries(), entry.getEntry() ) ); - LOG.debug( "Successfully injected LDIF enry for test {}: {}", settings.getDescription(), entry ); + try + { + service.getAdminSession().add( + new DefaultServerEntry( service.getRegistries(), entry.getEntry() ) ); + LOG.debug( "Successfully injected LDIF enry for test {}: {}", settings.getDescription(), entry ); + } + catch ( Exception e ) + { + LOG.error( "Cannot inject the following entry : {}. Error : {}.", entry, e.getMessage() ); + } } } catch ( Exception e ) { - LOG.error( "Cannot inject the following entry : {}. Error : {}.", ldif, e.getMessage() ); + LOG.error( "Cannot inject the ldif entries. Error : {}.", e.getMessage() ); } } } } protected void testAborted( RunNotifier notifier, Description description, Throwable cause ) { notifier.fireTestStarted( description ); notifier.fireTestFailure( new Failure( description, cause ) ); notifier.fireTestFinished( description ); } }
false
true
protected void injectLdifs( DirectoryService service, InheritableSettings settings ) { List<String> ldifs = new ArrayList<String>(); List<String> ldifFiles = new ArrayList<String>(); // First inject the LDIF files if any ldifFiles = settings.getLdifFiles( ldifFiles ); if ( ldifFiles.size() != 0 ) { for ( String ldifFile:ldifFiles ) { try { String className = settings.getParent().getDescription().getDisplayName(); Class<?> clazz = Class.forName( className ); URL url = clazz.getResource( ldifFile ); URI uri = url.toURI(); File file = new File( uri ); LdifReader ldifReader = new LdifReader( file ); for ( LdifEntry entry : ldifReader ) { service.getAdminSession().add( new DefaultServerEntry( service.getRegistries(), entry.getEntry() ) ); LOG.debug( "Successfully injected LDIF enry for test {}: {}", settings.getDescription(), entry ); } } catch ( Exception e ) { LOG.error( "Cannot inject the following entry : {}. Error : {}.", ldifFile, e.getMessage() ); } } } ldifs = settings.getLdifs( ldifs ); if ( ldifs.size() != 0 ) { for ( String ldif:ldifs ) { try { StringReader in = new StringReader( ldif ); LdifReader ldifReader = new LdifReader( in ); for ( LdifEntry entry : ldifReader ) { service.getAdminSession().add( new DefaultServerEntry( service.getRegistries(), entry.getEntry() ) ); LOG.debug( "Successfully injected LDIF enry for test {}: {}", settings.getDescription(), entry ); } } catch ( Exception e ) { LOG.error( "Cannot inject the following entry : {}. Error : {}.", ldif, e.getMessage() ); } } } }
protected void injectLdifs( DirectoryService service, InheritableSettings settings ) { List<String> ldifs = new ArrayList<String>(); List<String> ldifFiles = new ArrayList<String>(); // First inject the LDIF files if any ldifFiles = settings.getLdifFiles( ldifFiles ); if ( ldifFiles.size() != 0 ) { for ( String ldifFile:ldifFiles ) { try { String className = settings.getParent().getDescription().getDisplayName(); Class<?> clazz = Class.forName( className ); URL url = clazz.getResource( ldifFile ); URI uri = url.toURI(); File file = new File( uri ); LdifReader ldifReader = new LdifReader( file ); for ( LdifEntry entry : ldifReader ) { service.getAdminSession().add( new DefaultServerEntry( service.getRegistries(), entry.getEntry() ) ); LOG.debug( "Successfully injected LDIF enry for test {}: {}", settings.getDescription(), entry ); } } catch ( Exception e ) { LOG.error( "Cannot inject the following entry : {}. Error : {}.", ldifFile, e.getMessage() ); } } } ldifs = settings.getLdifs( ldifs ); if ( ldifs.size() != 0 ) { for ( String ldif:ldifs ) { try { StringReader in = new StringReader( ldif ); LdifReader ldifReader = new LdifReader( in ); for ( LdifEntry entry : ldifReader ) { try { service.getAdminSession().add( new DefaultServerEntry( service.getRegistries(), entry.getEntry() ) ); LOG.debug( "Successfully injected LDIF enry for test {}: {}", settings.getDescription(), entry ); } catch ( Exception e ) { LOG.error( "Cannot inject the following entry : {}. Error : {}.", entry, e.getMessage() ); } } } catch ( Exception e ) { LOG.error( "Cannot inject the ldif entries. Error : {}.", e.getMessage() ); } } } }
diff --git a/plugins/sonar-reviews-plugin/src/test/java/org/sonar/plugins/reviews/jira/JiraLinkReviewActionTest.java b/plugins/sonar-reviews-plugin/src/test/java/org/sonar/plugins/reviews/jira/JiraLinkReviewActionTest.java index eeade69d6a..b73832cc59 100644 --- a/plugins/sonar-reviews-plugin/src/test/java/org/sonar/plugins/reviews/jira/JiraLinkReviewActionTest.java +++ b/plugins/sonar-reviews-plugin/src/test/java/org/sonar/plugins/reviews/jira/JiraLinkReviewActionTest.java @@ -1,149 +1,149 @@ /* * Sonar, open source software quality management tool. * Copyright (C) 2008-2012 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.reviews.jira; import com.atlassian.jira.rpc.soap.client.RemoteIssue; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.database.model.User; import org.sonar.api.reviews.ReviewContext; import org.sonar.api.security.UserFinder; import org.sonar.api.test.ReviewContextTestUtils; import org.sonar.core.review.ReviewCommentDao; import org.sonar.core.review.ReviewCommentDto; import org.sonar.core.review.ReviewDao; import org.sonar.core.review.ReviewDto; import org.sonar.plugins.reviews.jira.soap.JiraSOAPClient; import java.util.Collection; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class JiraLinkReviewActionTest { @Rule public ExpectedException thrown = ExpectedException.none(); private JiraLinkReviewAction action; private JiraSOAPClient soapClient; private ReviewDao reviewDao; private ReviewCommentDao reviewCommentDao; private UserFinder userFinder; @Before public void init() throws Exception { soapClient = mock(JiraSOAPClient.class); RemoteIssue remoteIssue = new RemoteIssue(); remoteIssue.setKey("FOO-15"); when(soapClient.createIssue(any(ReviewDto.class))).thenReturn(remoteIssue); reviewDao = mock(ReviewDao.class); when(reviewDao.findById(45L)).thenReturn(new ReviewDto().setId(45L)); userFinder = mock(UserFinder.class); User user = new User(); user.setId(12); when(userFinder.findByLogin("paul")).thenReturn(user); reviewCommentDao = mock(ReviewCommentDao.class); action = new JiraLinkReviewAction(soapClient, reviewDao, reviewCommentDao, userFinder); } @Test public void shouldExecute() throws Exception { ReviewContext reviewContext = ReviewContextTestUtils.createReviewContext("review={id=45}; user={login=paul}; params={comment.text=Hello world}"); action.execute(reviewContext); verify(reviewDao).findById(45L); verify(userFinder).findByLogin("paul"); verify(soapClient).createIssue(new ReviewDto().setId(45L)); ArgumentCaptor<ReviewCommentDto> commentCaptor = ArgumentCaptor.forClass(ReviewCommentDto.class); verify(reviewCommentDao).insert(commentCaptor.capture()); ReviewCommentDto comment = commentCaptor.getValue(); assertThat(comment.getReviewId(), is(45L)); assertThat(comment.getUserId(), is(12L)); assertThat(comment.getText(), is("Hello world\n\nReview linked to JIRA issue: http://localhost:8080/browse/FOO-15")); ArgumentCaptor<Collection> reviewCaptor = ArgumentCaptor.forClass(Collection.class); verify(reviewDao).update(reviewCaptor.capture()); ReviewDto reviewDto = (ReviewDto) reviewCaptor.getValue().iterator().next(); - assertThat(reviewDto.getData(), is(action.getId() + "=FOO-15")); + assertThat(reviewDto.getData(), is("jira-issue-key=FOO-15")); } @Test public void shouldNotAddLinesBeforeLinkIfNoTextProvided() throws Exception { ReviewContext reviewContext = ReviewContextTestUtils.createReviewContext("review={id=45}; user={login=paul}"); action.execute(reviewContext); ArgumentCaptor<ReviewCommentDto> commentCaptor = ArgumentCaptor.forClass(ReviewCommentDto.class); verify(reviewCommentDao).insert(commentCaptor.capture()); assertThat(commentCaptor.getValue().getText(), is("Review linked to JIRA issue: http://localhost:8080/browse/FOO-15")); } @Test public void shouldFailIfReviewIdNotProvided() throws Exception { ReviewContext reviewContext = ReviewContextTestUtils.createReviewContext(""); thrown.expect(IllegalStateException.class); thrown.expectMessage("The review id is missing."); action.execute(reviewContext); } @Test public void shouldFailIfReviewIdNotANumber() throws Exception { ReviewContext reviewContext = ReviewContextTestUtils.createReviewContext("review={id=toto}"); thrown.expect(IllegalStateException.class); thrown.expectMessage("The given review with id is not a valid number: toto"); action.execute(reviewContext); } @Test public void shouldFailIfReviewDoesNotExist() throws Exception { ReviewContext reviewContext = ReviewContextTestUtils.createReviewContext("review={id=100}"); thrown.expect(NullPointerException.class); thrown.expectMessage("The review with id '100' does not exist."); action.execute(reviewContext); } @Test public void shouldFailIfUserDoesNotExist() throws Exception { ReviewContext reviewContext = ReviewContextTestUtils.createReviewContext("review={id=45}; user={login=invisible_man}"); thrown.expect(NullPointerException.class); thrown.expectMessage("The user with login 'invisible_man' does not exist."); action.execute(reviewContext); } }
true
true
public void shouldExecute() throws Exception { ReviewContext reviewContext = ReviewContextTestUtils.createReviewContext("review={id=45}; user={login=paul}; params={comment.text=Hello world}"); action.execute(reviewContext); verify(reviewDao).findById(45L); verify(userFinder).findByLogin("paul"); verify(soapClient).createIssue(new ReviewDto().setId(45L)); ArgumentCaptor<ReviewCommentDto> commentCaptor = ArgumentCaptor.forClass(ReviewCommentDto.class); verify(reviewCommentDao).insert(commentCaptor.capture()); ReviewCommentDto comment = commentCaptor.getValue(); assertThat(comment.getReviewId(), is(45L)); assertThat(comment.getUserId(), is(12L)); assertThat(comment.getText(), is("Hello world\n\nReview linked to JIRA issue: http://localhost:8080/browse/FOO-15")); ArgumentCaptor<Collection> reviewCaptor = ArgumentCaptor.forClass(Collection.class); verify(reviewDao).update(reviewCaptor.capture()); ReviewDto reviewDto = (ReviewDto) reviewCaptor.getValue().iterator().next(); assertThat(reviewDto.getData(), is(action.getId() + "=FOO-15")); }
public void shouldExecute() throws Exception { ReviewContext reviewContext = ReviewContextTestUtils.createReviewContext("review={id=45}; user={login=paul}; params={comment.text=Hello world}"); action.execute(reviewContext); verify(reviewDao).findById(45L); verify(userFinder).findByLogin("paul"); verify(soapClient).createIssue(new ReviewDto().setId(45L)); ArgumentCaptor<ReviewCommentDto> commentCaptor = ArgumentCaptor.forClass(ReviewCommentDto.class); verify(reviewCommentDao).insert(commentCaptor.capture()); ReviewCommentDto comment = commentCaptor.getValue(); assertThat(comment.getReviewId(), is(45L)); assertThat(comment.getUserId(), is(12L)); assertThat(comment.getText(), is("Hello world\n\nReview linked to JIRA issue: http://localhost:8080/browse/FOO-15")); ArgumentCaptor<Collection> reviewCaptor = ArgumentCaptor.forClass(Collection.class); verify(reviewDao).update(reviewCaptor.capture()); ReviewDto reviewDto = (ReviewDto) reviewCaptor.getValue().iterator().next(); assertThat(reviewDto.getData(), is("jira-issue-key=FOO-15")); }
diff --git a/src/java/org/apache/fop/fo/expr/NamedColorFunction.java b/src/java/org/apache/fop/fo/expr/NamedColorFunction.java index 2bceec8dc..53b9effdb 100644 --- a/src/java/org/apache/fop/fo/expr/NamedColorFunction.java +++ b/src/java/org/apache/fop/fo/expr/NamedColorFunction.java @@ -1,112 +1,111 @@ /* * 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. */ /* $Id$ */ package org.apache.fop.fo.expr; import org.apache.fop.datatypes.PercentBase; import org.apache.fop.datatypes.PercentBaseContext; import org.apache.fop.fo.pagination.ColorProfile; import org.apache.fop.fo.pagination.Declarations; import org.apache.fop.fo.properties.ColorProperty; import org.apache.fop.fo.properties.Property; /** * Implements the rgb-named-color() function. * @since XSL-FO 2.0 */ class NamedColorFunction extends FunctionBase { /** * rgb-named-color() takes a 5 arguments. * {@inheritDoc} */ public int nbArgs() { return 5; } /** {@inheritDoc} */ public PercentBase getPercentBase() { return new NamedPercentBase(); } /** {@inheritDoc} */ public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { // Map color profile NCNAME to src from declarations/color-profile element String colorProfileName = args[3].getString(); String colorName = args[4].getString(); Declarations decls = pInfo.getFO().getRoot().getDeclarations(); ColorProfile cp = null; if (decls != null) { cp = decls.getColorProfile(colorProfileName); } if (cp == null) { PropertyException pe = new PropertyException("The " + colorProfileName + " color profile was not declared"); pe.setPropertyInfo(pInfo); throw pe; } - String src = (cp != null ? cp.getSrc() : ""); float red = 0, green = 0, blue = 0; red = args[0].getNumber().floatValue(); green = args[1].getNumber().floatValue(); blue = args[2].getNumber().floatValue(); /* Verify rgb replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("sRGB color values out of range. " + "Arguments to rgb-named-color() must be [0..255] or [0%..100%]"); } // rgb-named-color is replaced with fop-rgb-named-color which has an extra argument // containing the color profile src attribute as it is defined in the color-profile // declarations element. StringBuffer sb = new StringBuffer(); sb.append("fop-rgb-named-color("); sb.append(red / 255f); sb.append(',').append(green / 255f); sb.append(',').append(blue / 255f); sb.append(',').append(colorProfileName); - sb.append(',').append(src); + sb.append(',').append(cp.getSrc()); sb.append(", '").append(colorName).append('\''); sb.append(")"); return ColorProperty.getInstance(pInfo.getUserAgent(), sb.toString()); } private static final class NamedPercentBase implements PercentBase { /** {@inheritDoc} */ public int getBaseLength(PercentBaseContext context) throws PropertyException { return 0; } /** {@inheritDoc} */ public double getBaseValue() { return 255f; } /** {@inheritDoc} */ public int getDimension() { return 0; } } }
false
true
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { // Map color profile NCNAME to src from declarations/color-profile element String colorProfileName = args[3].getString(); String colorName = args[4].getString(); Declarations decls = pInfo.getFO().getRoot().getDeclarations(); ColorProfile cp = null; if (decls != null) { cp = decls.getColorProfile(colorProfileName); } if (cp == null) { PropertyException pe = new PropertyException("The " + colorProfileName + " color profile was not declared"); pe.setPropertyInfo(pInfo); throw pe; } String src = (cp != null ? cp.getSrc() : ""); float red = 0, green = 0, blue = 0; red = args[0].getNumber().floatValue(); green = args[1].getNumber().floatValue(); blue = args[2].getNumber().floatValue(); /* Verify rgb replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("sRGB color values out of range. " + "Arguments to rgb-named-color() must be [0..255] or [0%..100%]"); } // rgb-named-color is replaced with fop-rgb-named-color which has an extra argument // containing the color profile src attribute as it is defined in the color-profile // declarations element. StringBuffer sb = new StringBuffer(); sb.append("fop-rgb-named-color("); sb.append(red / 255f); sb.append(',').append(green / 255f); sb.append(',').append(blue / 255f); sb.append(',').append(colorProfileName); sb.append(',').append(src); sb.append(", '").append(colorName).append('\''); sb.append(")"); return ColorProperty.getInstance(pInfo.getUserAgent(), sb.toString()); }
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { // Map color profile NCNAME to src from declarations/color-profile element String colorProfileName = args[3].getString(); String colorName = args[4].getString(); Declarations decls = pInfo.getFO().getRoot().getDeclarations(); ColorProfile cp = null; if (decls != null) { cp = decls.getColorProfile(colorProfileName); } if (cp == null) { PropertyException pe = new PropertyException("The " + colorProfileName + " color profile was not declared"); pe.setPropertyInfo(pInfo); throw pe; } float red = 0, green = 0, blue = 0; red = args[0].getNumber().floatValue(); green = args[1].getNumber().floatValue(); blue = args[2].getNumber().floatValue(); /* Verify rgb replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("sRGB color values out of range. " + "Arguments to rgb-named-color() must be [0..255] or [0%..100%]"); } // rgb-named-color is replaced with fop-rgb-named-color which has an extra argument // containing the color profile src attribute as it is defined in the color-profile // declarations element. StringBuffer sb = new StringBuffer(); sb.append("fop-rgb-named-color("); sb.append(red / 255f); sb.append(',').append(green / 255f); sb.append(',').append(blue / 255f); sb.append(',').append(colorProfileName); sb.append(',').append(cp.getSrc()); sb.append(", '").append(colorName).append('\''); sb.append(")"); return ColorProperty.getInstance(pInfo.getUserAgent(), sb.toString()); }
diff --git a/src/com/evervolv/EVParts/UiOptions.java b/src/com/evervolv/EVParts/UiOptions.java index 5ea5c24..cddcc07 100644 --- a/src/com/evervolv/EVParts/UiOptions.java +++ b/src/com/evervolv/EVParts/UiOptions.java @@ -1,89 +1,89 @@ package com.evervolv.EVParts; import com.evervolv.EVParts.R; import com.evervolv.EVParts.R.xml; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.EditTextPreference; import android.preference.PreferenceScreen; import android.preference.Preference.OnPreferenceChangeListener; import android.widget.Toast; import android.util.Log; import android.provider.Settings; public class UiOptions extends PreferenceActivity implements OnPreferenceChangeListener { private static final String USE_SCREENOFF_ANIM = "use_screenoff_anim"; private static final String USE_SCREENON_ANIM = "use_screenon_anim"; private static final String BATTERY_OPTION = "battery_option"; private static final String HIDE_CLOCK_PREF = "hide_clock"; private static final String AM_PM_PREF = "hide_ampm"; private CheckBoxPreference mHideClock; private CheckBoxPreference mHideAmPm; private CheckBoxPreference mUseScreenOnAnim; private CheckBoxPreference mUseScreenOffAnim; private ListPreference mBatteryOption; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.ui_options); PreferenceScreen prefSet = getPreferenceScreen(); mUseScreenOnAnim = (CheckBoxPreference)prefSet.findPreference(USE_SCREENON_ANIM); mUseScreenOnAnim.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.USE_SCREENON_ANIM, 1) == 1); mUseScreenOffAnim = (CheckBoxPreference)prefSet.findPreference(USE_SCREENOFF_ANIM); mUseScreenOffAnim.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.USE_SCREENOFF_ANIM, 1) == 1); mBatteryOption = (ListPreference) prefSet.findPreference(BATTERY_OPTION); mBatteryOption.setOnPreferenceChangeListener(this); mHideClock = (CheckBoxPreference) prefSet.findPreference(HIDE_CLOCK_PREF); mHideClock.setOnPreferenceChangeListener(this); mHideClock.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.SHOW_STATUS_CLOCK, 1) == 0); mHideAmPm = (CheckBoxPreference) prefSet.findPreference(AM_PM_PREF); mHideAmPm.setOnPreferenceChangeListener(this); - mHideAmPm.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.SHOW_TWELVE_HOUR_CLOCK_PERIOD, 0) == 0); + mHideAmPm.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.SHOW_TWELVE_HOUR_CLOCK_PERIOD, 1) == 0); } public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { boolean value; if (preference == mUseScreenOnAnim) { value = mUseScreenOnAnim.isChecked(); Settings.System.putInt(getContentResolver(), Settings.System.USE_SCREENON_ANIM, value ? 1 : 0); } else if (preference == mUseScreenOffAnim) { value = mUseScreenOffAnim.isChecked(); Settings.System.putInt(getContentResolver(), Settings.System.USE_SCREENOFF_ANIM, value ? 1 : 0); } return true; } public boolean onPreferenceChange(Preference preference, Object objValue) { if (preference == mBatteryOption) { Settings.System.putInt(getContentResolver(), Settings.System.BATTERY_OPTION, Integer.valueOf((String) objValue)); } else if (preference == mHideClock) { Settings.System.putInt(getContentResolver(), Settings.System.SHOW_STATUS_CLOCK, mHideClock.isChecked() ? 1 : 0); } else if (preference == mHideAmPm) { Settings.System.putInt(getContentResolver(), Settings.System.SHOW_TWELVE_HOUR_CLOCK_PERIOD, mHideAmPm.isChecked() ? 1 : 0); } // always let the preference setting proceed. return true; } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.ui_options); PreferenceScreen prefSet = getPreferenceScreen(); mUseScreenOnAnim = (CheckBoxPreference)prefSet.findPreference(USE_SCREENON_ANIM); mUseScreenOnAnim.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.USE_SCREENON_ANIM, 1) == 1); mUseScreenOffAnim = (CheckBoxPreference)prefSet.findPreference(USE_SCREENOFF_ANIM); mUseScreenOffAnim.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.USE_SCREENOFF_ANIM, 1) == 1); mBatteryOption = (ListPreference) prefSet.findPreference(BATTERY_OPTION); mBatteryOption.setOnPreferenceChangeListener(this); mHideClock = (CheckBoxPreference) prefSet.findPreference(HIDE_CLOCK_PREF); mHideClock.setOnPreferenceChangeListener(this); mHideClock.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.SHOW_STATUS_CLOCK, 1) == 0); mHideAmPm = (CheckBoxPreference) prefSet.findPreference(AM_PM_PREF); mHideAmPm.setOnPreferenceChangeListener(this); mHideAmPm.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.SHOW_TWELVE_HOUR_CLOCK_PERIOD, 0) == 0); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.ui_options); PreferenceScreen prefSet = getPreferenceScreen(); mUseScreenOnAnim = (CheckBoxPreference)prefSet.findPreference(USE_SCREENON_ANIM); mUseScreenOnAnim.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.USE_SCREENON_ANIM, 1) == 1); mUseScreenOffAnim = (CheckBoxPreference)prefSet.findPreference(USE_SCREENOFF_ANIM); mUseScreenOffAnim.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.USE_SCREENOFF_ANIM, 1) == 1); mBatteryOption = (ListPreference) prefSet.findPreference(BATTERY_OPTION); mBatteryOption.setOnPreferenceChangeListener(this); mHideClock = (CheckBoxPreference) prefSet.findPreference(HIDE_CLOCK_PREF); mHideClock.setOnPreferenceChangeListener(this); mHideClock.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.SHOW_STATUS_CLOCK, 1) == 0); mHideAmPm = (CheckBoxPreference) prefSet.findPreference(AM_PM_PREF); mHideAmPm.setOnPreferenceChangeListener(this); mHideAmPm.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.SHOW_TWELVE_HOUR_CLOCK_PERIOD, 1) == 0); }
diff --git a/beam-gpf-common/src/main/java/org/esa/beam/gpf/common/mosaic/ui/MosaicFormModel.java b/beam-gpf-common/src/main/java/org/esa/beam/gpf/common/mosaic/ui/MosaicFormModel.java index 5c0c56c27..36ae058d2 100644 --- a/beam-gpf-common/src/main/java/org/esa/beam/gpf/common/mosaic/ui/MosaicFormModel.java +++ b/beam-gpf-common/src/main/java/org/esa/beam/gpf/common/mosaic/ui/MosaicFormModel.java @@ -1,161 +1,165 @@ package org.esa.beam.gpf.common.mosaic.ui; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.accessors.MapEntryAccessor; import org.esa.beam.framework.dataio.ProductIO; import org.esa.beam.framework.datamodel.CrsGeoCoding; import org.esa.beam.framework.datamodel.Product; import org.esa.beam.framework.gpf.annotations.ParameterDescriptorFactory; import org.esa.beam.util.math.MathUtils; import org.geotools.geometry.GeneralEnvelope; import org.geotools.referencing.CRS; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.opengis.geometry.Envelope; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.TransformException; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * @author Marco Peters * @version $ Revision $ Date $ * @since BEAM 4.7 */ class MosaicFormModel { private PropertyContainer container; public static final String PROPERTY_SOURCE_PRODUCT_FILES = "sourceProductFiles"; public static final String PROPERTY_UPDATE_PRODUCT = "updateProduct"; public static final String PROPERTY_UPDATE_MODE = "updateMode"; private Product refProduct; private File refProductFile; MosaicFormModel() { Map<String, Object> parameterMap = new HashMap<String, Object>(); container = ParameterDescriptorFactory.createMapBackedOperatorPropertyContainer("Mosaic", parameterMap); final PropertyDescriptor sourceFilesDescriptor = new PropertyDescriptor(PROPERTY_SOURCE_PRODUCT_FILES, new File[0].getClass()); container.addProperty(new Property(sourceFilesDescriptor, new MapEntryAccessor(parameterMap, PROPERTY_SOURCE_PRODUCT_FILES))); container.addProperty(new Property(new PropertyDescriptor(PROPERTY_UPDATE_PRODUCT, Product.class), new MapEntryAccessor(parameterMap, PROPERTY_UPDATE_PRODUCT))); container.addProperty(new Property(new PropertyDescriptor(PROPERTY_UPDATE_MODE, Boolean.class), new MapEntryAccessor(parameterMap, PROPERTY_UPDATE_MODE))); container.setValue(PROPERTY_UPDATE_MODE, false); try { container.setDefaultValues(); } catch (ValidationException ignore) { } } public PropertyContainer getPropertyContainer() { return container; } public Object getPropertyValue(String propertyName) { return container.getValue(propertyName); } public void setPropertyValue(String propertyName, Object value) { container.setValue(propertyName, value); } public Product getReferenceProduct() throws IOException { if (container.getValue(PROPERTY_SOURCE_PRODUCT_FILES) != null) { final File[] files = (File[]) container.getValue(PROPERTY_SOURCE_PRODUCT_FILES); if (files.length > 0) { try { if (!files[0].equals(refProductFile)) { refProductFile = files[0]; - refProduct.dispose(); - refProduct = null; + if (refProduct != null) { + refProduct.dispose(); + refProduct = null; + } refProduct = ProductIO.readProduct(refProductFile, null); } } catch (IOException e) { final String msg = String.format("Cannot read product '%s'", files[0].getPath()); throw new IOException(msg, e); } } else { - refProduct.dispose(); - refProduct = null; + if (refProduct != null) { + refProduct.dispose(); + refProduct = null; + } } } if (refProduct == null) { final String msg = String.format("No reference product available."); throw new IOException(msg); } return refProduct; } public Product getBoundaryProduct() throws FactoryException, TransformException { final CoordinateReferenceSystem mapCRS = getCrs(); if (mapCRS != null) { final double pixelSizeX = (Double) getPropertyValue("pixelSizeX"); final double pixelSizeY = (Double) getPropertyValue("pixelSizeY"); final GeneralEnvelope generalEnvelope = getGeoEnvelope(); final Envelope targetEnvelope = CRS.transform(generalEnvelope, mapCRS); final int sceneRasterWidth = MathUtils.floorInt(targetEnvelope.getSpan(0) / pixelSizeX); final int sceneRasterHeight = MathUtils.floorInt(targetEnvelope.getSpan(1) / pixelSizeY); final Product outputProduct = new Product("mosaic", "MosaicBounds", sceneRasterWidth, sceneRasterHeight); final Rectangle imageRect = new Rectangle(0, 0, sceneRasterWidth, sceneRasterHeight); final AffineTransform i2mTransform = new AffineTransform(); i2mTransform.translate(targetEnvelope.getMinimum(0), targetEnvelope.getMinimum(1)); i2mTransform.scale(pixelSizeX, pixelSizeY); i2mTransform.translate(-0.5, -0.5); outputProduct.setGeoCoding(new CrsGeoCoding(mapCRS, imageRect, i2mTransform)); return outputProduct; } return null; } void setWkt(CoordinateReferenceSystem crs) { if (crs != null) { setPropertyValue("wkt", crs.toWKT()); if (getPropertyValue("epsgCode") != null) { // clear default epsgCode, so wkt has precedence setPropertyValue("epsgCode", null); } } } private CoordinateReferenceSystem getCrs() throws FactoryException { final String crsCode = (String) getPropertyValue("epsgCode"); if (crsCode != null) { return CRS.decode(crsCode, true); } final String wkt = (String) getPropertyValue("wkt"); if (wkt != null) { return CRS.parseWKT(wkt); } return null; } GeneralEnvelope getGeoEnvelope() { final double west = (Double) getPropertyValue("westBound"); final double north = (Double) getPropertyValue("northBound"); final double east = (Double) getPropertyValue("eastBound"); final double south = (Double) getPropertyValue("southBound"); final Rectangle2D.Double geoBounds = new Rectangle2D.Double(); geoBounds.setFrameFromDiagonal(west, north, east, south); final GeneralEnvelope generalEnvelope = new GeneralEnvelope(geoBounds); generalEnvelope.setCoordinateReferenceSystem(DefaultGeographicCRS.WGS84); return generalEnvelope; } }
false
true
public Product getReferenceProduct() throws IOException { if (container.getValue(PROPERTY_SOURCE_PRODUCT_FILES) != null) { final File[] files = (File[]) container.getValue(PROPERTY_SOURCE_PRODUCT_FILES); if (files.length > 0) { try { if (!files[0].equals(refProductFile)) { refProductFile = files[0]; refProduct.dispose(); refProduct = null; refProduct = ProductIO.readProduct(refProductFile, null); } } catch (IOException e) { final String msg = String.format("Cannot read product '%s'", files[0].getPath()); throw new IOException(msg, e); } } else { refProduct.dispose(); refProduct = null; } } if (refProduct == null) { final String msg = String.format("No reference product available."); throw new IOException(msg); } return refProduct; }
public Product getReferenceProduct() throws IOException { if (container.getValue(PROPERTY_SOURCE_PRODUCT_FILES) != null) { final File[] files = (File[]) container.getValue(PROPERTY_SOURCE_PRODUCT_FILES); if (files.length > 0) { try { if (!files[0].equals(refProductFile)) { refProductFile = files[0]; if (refProduct != null) { refProduct.dispose(); refProduct = null; } refProduct = ProductIO.readProduct(refProductFile, null); } } catch (IOException e) { final String msg = String.format("Cannot read product '%s'", files[0].getPath()); throw new IOException(msg, e); } } else { if (refProduct != null) { refProduct.dispose(); refProduct = null; } } } if (refProduct == null) { final String msg = String.format("No reference product available."); throw new IOException(msg); } return refProduct; }
diff --git a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/search/BugzillaSearchPage.java b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/search/BugzillaSearchPage.java index ff723e06f..d68ca5069 100644 --- a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/search/BugzillaSearchPage.java +++ b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/search/BugzillaSearchPage.java @@ -1,1921 +1,1921 @@ /******************************************************************************* * Copyright (c) 2003, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.internal.bugzilla.ui.search; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.fieldassist.ComboContentAdapter; import org.eclipse.jface.fieldassist.ContentProposalAdapter; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.fieldassist.FieldDecoration; import org.eclipse.jface.fieldassist.FieldDecorationRegistry; import org.eclipse.jface.fieldassist.IContentProposalProvider; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.window.Window; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaCorePlugin; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaRepositoryQuery; import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants; import org.eclipse.mylyn.internal.bugzilla.core.RepositoryConfiguration; import org.eclipse.mylyn.internal.bugzilla.ui.BugzillaUiPlugin; import org.eclipse.mylyn.internal.bugzilla.ui.editor.KeywordsDialog; import org.eclipse.mylyn.internal.tasks.core.TaskRepositoryManager; import org.eclipse.mylyn.internal.tasks.ui.PersonProposalLabelProvider; import org.eclipse.mylyn.internal.tasks.ui.PersonProposalProvider; import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.internal.tasks.ui.util.WebBrowserDialog; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.tasks.core.RepositoryStatus; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.ui.search.AbstractRepositoryQueryPage; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; 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.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter; import org.eclipse.ui.internal.help.WorkbenchHelpSystem; import org.eclipse.ui.keys.IBindingService; import org.eclipse.ui.progress.IProgressService; /** * Bugzilla search page * * @author Mik Kersten (hardening of prototype) * @author Frank Becker */ public class BugzillaSearchPage extends AbstractRepositoryQueryPage implements Listener { private static final int LABEL_WIDTH = 58; private static final String NUM_DAYS_POSITIVE = "Number of days must be a positive integer. "; private static final String TITLE_BUGZILLA_QUERY = "Bugzilla Query"; private static final int HEIGHT_ATTRIBUTE_COMBO = 70; // protected Combo repositoryCombo = null; private static ArrayList<BugzillaSearchData> previousSummaryPatterns = new ArrayList<BugzillaSearchData>(20); private static ArrayList<BugzillaSearchData> previousEmailPatterns = new ArrayList<BugzillaSearchData>(20); private static ArrayList<BugzillaSearchData> previousEmailPatterns2 = new ArrayList<BugzillaSearchData>(20); private static ArrayList<BugzillaSearchData> previousCommentPatterns = new ArrayList<BugzillaSearchData>(20); private static ArrayList<BugzillaSearchData> previousKeywords = new ArrayList<BugzillaSearchData>(20); private boolean firstTime = true; private IDialogSettings fDialogSettings; private static final String[] patternOperationText = { "all words", "any word", "regexp", "notregexp" }; private static final String[] patternOperationValues = { "allwordssubstr", "anywordssubstr", "regexp", "notregexp" }; private static final String[] emailOperationText = { "substring", "exact", "regexp", "notregexp" }; private static final String[] emailOperationValues = { "substring", "exact", "regexp", "notregexp" }; private static final String[] keywordOperationText = { "all", "any", "none" }; private static final String[] keywordOperationValues = { "allwords", "anywords", "nowords" }; private static final String[] emailRoleValues = { "emailassigned_to1", "emailreporter1", "emailcc1", "emaillongdesc1" }; private static final String[] emailRoleValues2 = { "emailassigned_to2", "emailreporter2", "emailcc2", "emaillongdesc2" }; private BugzillaRepositoryQuery originalQuery = null; protected boolean restoring = false; private boolean restoreQueryOptions = true; protected Combo summaryPattern; protected Combo summaryOperation; protected List product; protected List os; protected List hardware; protected List priority; protected List severity; protected List resolution; protected List status; protected Combo commentOperation; protected Combo commentPattern; protected List component; protected List version; protected List target; protected Combo emailOperation; protected Combo emailOperation2; protected Combo emailPattern; protected Combo emailPattern2; protected Button[] emailButtons; protected Button[] emailButtons2; private Combo keywords; private Combo keywordsOperation; protected Text daysText; // /** File containing saved queries */ // protected static SavedQueryFile input; // /** "Remember query" button */ // protected Button saveButton; // /** "Saved queries..." button */ // protected Button loadButton; // /** Run a remembered query */ // protected boolean rememberedQuery = false; /** Index of the saved query to run */ protected int selIndex; // --------------- Configuration handling -------------- // Dialog store taskId constants protected final static String PAGE_NAME = "BugzillaSearchPage"; //$NON-NLS-1$ private static final String STORE_PRODUCT_ID = PAGE_NAME + ".PRODUCT"; private static final String STORE_COMPONENT_ID = PAGE_NAME + ".COMPONENT"; private static final String STORE_VERSION_ID = PAGE_NAME + ".VERSION"; private static final String STORE_MSTONE_ID = PAGE_NAME + ".MILESTONE"; private static final String STORE_STATUS_ID = PAGE_NAME + ".STATUS"; private static final String STORE_RESOLUTION_ID = PAGE_NAME + ".RESOLUTION"; private static final String STORE_SEVERITY_ID = PAGE_NAME + ".SEVERITY"; private static final String STORE_PRIORITY_ID = PAGE_NAME + ".PRIORITY"; private static final String STORE_HARDWARE_ID = PAGE_NAME + ".HARDWARE"; private static final String STORE_OS_ID = PAGE_NAME + ".OS"; private static final String STORE_SUMMARYMATCH_ID = PAGE_NAME + ".SUMMARYMATCH"; private static final String STORE_COMMENTMATCH_ID = PAGE_NAME + ".COMMENTMATCH"; private static final String STORE_EMAILMATCH_ID = PAGE_NAME + ".EMAILMATCH"; private static final String STORE_EMAIL2MATCH_ID = PAGE_NAME + ".EMAIL2MATCH"; private static final String STORE_EMAILBUTTON_ID = PAGE_NAME + ".EMAILATTR"; private static final String STORE_EMAIL2BUTTON_ID = PAGE_NAME + ".EMAIL2ATTR"; private static final String STORE_SUMMARYTEXT_ID = PAGE_NAME + ".SUMMARYTEXT"; private static final String STORE_COMMENTTEXT_ID = PAGE_NAME + ".COMMENTTEXT"; private static final String STORE_EMAILADDRESS_ID = PAGE_NAME + ".EMAILADDRESS"; private static final String STORE_EMAIL2ADDRESS_ID = PAGE_NAME + ".EMAIL2ADDRESS"; private static final String STORE_KEYWORDS_ID = PAGE_NAME + ".KEYWORDS"; private static final String STORE_KEYWORDSMATCH_ID = PAGE_NAME + ".KEYWORDSMATCH"; // private static final String STORE_REPO_ID = PAGE_NAME + ".REPO"; private RepositoryConfiguration repositoryConfiguration; private SelectionAdapter updateActionSelectionAdapter = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (isControlCreated()) { setPageComplete(isPageComplete()); } } }; private final class ModifyListenerImplementation implements ModifyListener { public void modifyText(ModifyEvent e) { if (isControlCreated()) { setPageComplete(isPageComplete()); } } } @Override public void setPageComplete(boolean complete) { super.setPageComplete(complete); if (scontainer != null) { scontainer.setPerformActionEnabled(complete); } } private static class BugzillaSearchData { /** Pattern to match on */ String pattern; /** Pattern matching criterion */ int operation; BugzillaSearchData(String pattern, int operation) { this.pattern = pattern; this.operation = operation; } } public BugzillaSearchPage() { super(TITLE_BUGZILLA_QUERY); // setTitle(TITLE); // setDescription(DESCRIPTION); // setPageComplete(false); } public BugzillaSearchPage(TaskRepository repository) { super(TITLE_BUGZILLA_QUERY); this.repository = repository; // setTitle(TITLE); // setDescription(DESCRIPTION); // setImageDescriptor(TaskListImages.BANNER_REPOSITORY); // setPageComplete(false); // try { // repositoryConfiguration = BugzillaCorePlugin.getRepositoryConfiguration(repository, false); // } catch (final CoreException e) { // PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { // public void run() { // MessageDialog.openError(Display.getDefault().getActiveShell(), "Bugzilla Search Page", // "Unable to get configuration. Ensure proper repository configuration in " // + TasksUiPlugin.LABEL_VIEW_REPOSITORIES + ".\n\n"); // } // }); // } } public BugzillaSearchPage(TaskRepository repository, BugzillaRepositoryQuery origQuery) { super(TITLE_BUGZILLA_QUERY, origQuery.getSummary()); originalQuery = origQuery; this.repository = repository; setDescription("Select the Bugzilla query parameters. Use the Update Attributes button to retrieve " + "updated values from the repository."); // setTitle(TITLE); // setDescription(DESCRIPTION); // setPageComplete(false); // try { // repositoryConfiguration = BugzillaCorePlugin.getRepositoryConfiguration(repository, false); // } catch (final CoreException e) { // PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { // public void run() { // MessageDialog.openError(Display.getDefault().getActiveShell(), "Bugzilla Search Page", // "Unable to get configuration. Ensure proper repository configuration in " // + TasksUiPlugin.LABEL_VIEW_REPOSITORIES + ".\n\n"); // } // }); // } } public void createControl(Composite parent) { readConfiguration(); Composite control = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(1, false); layout.marginHeight = 0; control.setLayout(layout); control.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL)); // if (scontainer == null) { // Not presenting in search pane so want query title // super.createControl(control); // Label lblName = new Label(control, SWT.NONE); // final GridData gridData = new GridData(); // lblName.setLayoutData(gridData); // lblName.setText("Query Title:"); // // title = new Text(control, SWT.BORDER); // title.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); // title.addModifyListener(new ModifyListener() { // public void modifyText(ModifyEvent e) { // setPageComplete(isPageComplete()); // } // }); // } // else { // // if (repository == null) { // // search pane so add repository selection // createRepositoryGroup(control); // } createOptionsGroup(control); createSearchGroup(control); // createSaveQuery(control); // createMaxHits(control); // input = new SavedQueryFile(BugzillaPlugin.getDefault().getStateLocation().toString(), "/queries"); // createUpdate(control); // if (originalQuery != null) { // try { // updateDefaults(originalQuery.getQueryUrl(), String.valueOf(originalQuery.getMaxHits())); // } catch (UnsupportedEncodingException e) { // // ignore // } // } setControl(control); WorkbenchHelpSystem.getInstance().setHelp(control, BugzillaUiPlugin.SEARCH_PAGE_CONTEXT); } protected void createOptionsGroup(Composite control) { GridLayout sashFormLayout = new GridLayout(); sashFormLayout.numColumns = 4; sashFormLayout.marginHeight = 5; sashFormLayout.marginWidth = 5; sashFormLayout.horizontalSpacing = 5; final Composite composite = new Composite(control, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); final GridLayout gridLayout = new GridLayout(); gridLayout.marginBottom = 8; gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; gridLayout.numColumns = 4; composite.setLayout(gridLayout); if (!inSearchContainer()) { final Label queryTitleLabel = new Label(composite, SWT.NONE); queryTitleLabel.setText("&Query Title:"); Text queryTitle = new Text(composite, SWT.BORDER); queryTitle.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); if (originalQuery != null) { queryTitle.setText(originalQuery.getSummary()); } queryTitle.addModifyListener(new ModifyListenerImplementation()); title = queryTitle; title.setFocus(); } // Info text Label labelSummary = new Label(composite, SWT.LEFT); - labelSummary.setText("&Summary:"); + labelSummary.setText("Summar&y:"); labelSummary.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT)); //labelSummary.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // Pattern combo summaryPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); summaryPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); summaryPattern.addModifyListener(new ModifyListenerImplementation()); summaryPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(summaryPattern, summaryOperation, previousSummaryPatterns); } }); summaryOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); summaryOperation.setItems(patternOperationText); summaryOperation.setText(patternOperationText[0]); summaryOperation.select(0); // Info text Label labelComment = new Label(composite, SWT.LEFT); labelComment.setText("&Comment:"); //labelComment.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // Comment pattern combo commentPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); commentPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1)); commentPattern.addModifyListener(new ModifyListenerImplementation()); commentPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(commentPattern, commentOperation, previousCommentPatterns); } }); commentOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); commentOperation.setItems(patternOperationText); commentOperation.setText(patternOperationText[0]); commentOperation.select(0); Label labelEmail = new Label(composite, SWT.LEFT); labelEmail.setText("&Email:"); //labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // pattern combo emailPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); emailPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); emailPattern.addModifyListener(new ModifyListenerImplementation()); emailPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(emailPattern, emailOperation, previousEmailPatterns); } }); ContentAssistCommandAdapter adapter = applyContentAssist(emailPattern, createContentProposalProvider()); ILabelProvider propsalLabelProvider = createProposalLabelProvider(); if (propsalLabelProvider != null) { adapter.setLabelProvider(propsalLabelProvider); } adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); Composite emailComposite = new Composite(composite, SWT.NONE); emailComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); GridLayout emailLayout = new GridLayout(); emailLayout.marginWidth = 0; emailLayout.marginHeight = 0; emailLayout.horizontalSpacing = 2; emailLayout.numColumns = 4; emailComposite.setLayout(emailLayout); Button button0 = new Button(emailComposite, SWT.CHECK); button0.setText("owner"); Button button1 = new Button(emailComposite, SWT.CHECK); button1.setText("reporter"); Button button2 = new Button(emailComposite, SWT.CHECK); button2.setText("cc"); Button button3 = new Button(emailComposite, SWT.CHECK); button3.setText("commenter"); emailButtons = new Button[] { button0, button1, button2, button3 }; // operation combo emailOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); emailOperation.setItems(emailOperationText); emailOperation.setText(emailOperationText[0]); emailOperation.select(0); // Email2 Label labelEmail2 = new Label(composite, SWT.LEFT); labelEmail2.setText("Email &2:"); //labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // pattern combo emailPattern2 = new Combo(composite, SWT.SINGLE | SWT.BORDER); emailPattern2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); emailPattern2.addModifyListener(new ModifyListenerImplementation()); emailPattern2.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(emailPattern2, emailOperation2, previousEmailPatterns2); } }); ContentAssistCommandAdapter adapter2 = applyContentAssist(emailPattern2, createContentProposalProvider()); ILabelProvider propsalLabelProvider2 = createProposalLabelProvider(); if (propsalLabelProvider2 != null) { adapter2.setLabelProvider(propsalLabelProvider2); } adapter2.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); Composite emailComposite2 = new Composite(composite, SWT.NONE); emailComposite2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); GridLayout emailLayout2 = new GridLayout(); emailLayout2.marginWidth = 0; emailLayout2.marginHeight = 0; emailLayout2.horizontalSpacing = 2; emailLayout2.numColumns = 4; emailComposite2.setLayout(emailLayout2); Button e2button0 = new Button(emailComposite2, SWT.CHECK); e2button0.setText("owner"); Button e2button1 = new Button(emailComposite2, SWT.CHECK); e2button1.setText("reporter"); Button e2button2 = new Button(emailComposite2, SWT.CHECK); e2button2.setText("cc"); Button e2button3 = new Button(emailComposite2, SWT.CHECK); e2button3.setText("commenter"); emailButtons2 = new Button[] { e2button0, e2button1, e2button2, e2button3 }; // operation combo emailOperation2 = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); emailOperation2.setItems(emailOperationText); emailOperation2.setText(emailOperationText[0]); emailOperation2.select(0); ///// Label labelKeywords = new Label(composite, SWT.NONE); labelKeywords.setText("&Keywords:"); labelKeywords.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT)); //labelKeywords.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Composite keywordsComposite = new Composite(composite, SWT.NONE); keywordsComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1)); GridLayout keywordsLayout = new GridLayout(); keywordsLayout.marginWidth = 0; keywordsLayout.marginHeight = 0; keywordsLayout.numColumns = 3; keywordsComposite.setLayout(keywordsLayout); keywordsOperation = new Combo(keywordsComposite, SWT.READ_ONLY); keywordsOperation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); keywordsOperation.setItems(keywordOperationText); keywordsOperation.setText(keywordOperationText[0]); keywordsOperation.select(0); keywords = new Combo(keywordsComposite, SWT.NONE); keywords.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); keywords.addModifyListener(new ModifyListenerImplementation()); keywords.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(keywords, keywordsOperation, previousKeywords); } }); Button keywordsSelectButton = new Button(keywordsComposite, SWT.NONE); keywordsSelectButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (repositoryConfiguration != null) { KeywordsDialog dialog = new KeywordsDialog(getShell(), keywords.getText(), // repositoryConfiguration.getKeywords()); if (dialog.open() == Window.OK) { keywords.setText(dialog.getSelectedKeywordsString()); } } } }); keywordsSelectButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); keywordsSelectButton.setText("Select..."); SashForm sashForm = new SashForm(control, SWT.VERTICAL); sashForm.setLayout(sashFormLayout); final GridData gd_sashForm = new GridData(SWT.FILL, SWT.FILL, true, true); gd_sashForm.widthHint = 500; sashForm.setLayoutData(gd_sashForm); GridLayout topLayout = new GridLayout(); topLayout.numColumns = 4; SashForm topForm = new SashForm(sashForm, SWT.NONE); GridData topLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1); topLayoutData.widthHint = 500; topForm.setLayoutData(topLayoutData); topForm.setLayout(topLayout); GridLayout productLayout = new GridLayout(); productLayout.marginWidth = 0; productLayout.marginHeight = 0; productLayout.horizontalSpacing = 0; Composite productComposite = new Composite(topForm, SWT.NONE); productComposite.setLayout(productLayout); Label productLabel = new Label(productComposite, SWT.LEFT); productLabel.setText("&Product:"); GridData productLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); productLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; product = new List(productComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); product.setLayoutData(productLayoutData); product.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (product.getSelectionIndex() != -1) { String[] selectedProducts = product.getSelection(); updateAttributesFromConfiguration(selectedProducts); } else { updateAttributesFromConfiguration(null); } if (restoring) { restoring = false; restoreWidgetValues(); } setPageComplete(isPageComplete()); } }); GridLayout componentLayout = new GridLayout(); componentLayout.marginWidth = 0; componentLayout.marginHeight = 0; componentLayout.horizontalSpacing = 0; Composite componentComposite = new Composite(topForm, SWT.NONE); componentComposite.setLayout(componentLayout); Label componentLabel = new Label(componentComposite, SWT.LEFT); componentLabel.setText("Compo&nent:"); component = new List(componentComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData componentLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); componentLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; component.setLayoutData(componentLayoutData); component.addSelectionListener(updateActionSelectionAdapter); Composite versionComposite = new Composite(topForm, SWT.NONE); GridLayout versionLayout = new GridLayout(); versionLayout.marginWidth = 0; versionLayout.marginHeight = 0; versionLayout.horizontalSpacing = 0; versionComposite.setLayout(versionLayout); Label versionLabel = new Label(versionComposite, SWT.LEFT); versionLabel.setText("Vers&ion:"); version = new List(versionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData versionLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); versionLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; version.setLayoutData(versionLayoutData); version.addSelectionListener(updateActionSelectionAdapter); Composite milestoneComposite = new Composite(topForm, SWT.NONE); GridLayout milestoneLayout = new GridLayout(); milestoneLayout.marginWidth = 0; milestoneLayout.marginHeight = 0; milestoneLayout.horizontalSpacing = 0; milestoneComposite.setLayout(milestoneLayout); Label milestoneLabel = new Label(milestoneComposite, SWT.LEFT); milestoneLabel.setText("&Milestone:"); target = new List(milestoneComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData targetLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); targetLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; target.setLayoutData(targetLayoutData); target.addSelectionListener(updateActionSelectionAdapter); SashForm bottomForm = new SashForm(sashForm, SWT.NONE); GridLayout bottomLayout = new GridLayout(); bottomLayout.numColumns = 6; bottomForm.setLayout(bottomLayout); GridData bottomLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1); bottomLayoutData.heightHint = 119; bottomLayoutData.widthHint = 400; bottomForm.setLayoutData(bottomLayoutData); Composite statusComposite = new Composite(bottomForm, SWT.NONE); GridLayout statusLayout = new GridLayout(); statusLayout.marginTop = 7; statusLayout.marginWidth = 0; statusLayout.horizontalSpacing = 0; statusLayout.marginHeight = 0; statusComposite.setLayout(statusLayout); Label statusLabel = new Label(statusComposite, SWT.LEFT); statusLabel.setText("Stat&us:"); status = new List(statusComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_status = new GridData(SWT.FILL, SWT.FILL, true, true); gd_status.heightHint = 60; status.setLayoutData(gd_status); status.addSelectionListener(updateActionSelectionAdapter); Composite resolutionComposite = new Composite(bottomForm, SWT.NONE); GridLayout resolutionLayout = new GridLayout(); resolutionLayout.marginTop = 7; resolutionLayout.marginWidth = 0; resolutionLayout.marginHeight = 0; resolutionLayout.horizontalSpacing = 0; resolutionComposite.setLayout(resolutionLayout); Label resolutionLabel = new Label(resolutionComposite, SWT.LEFT); resolutionLabel.setText("&Resolution:"); resolution = new List(resolutionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_resolution = new GridData(SWT.FILL, SWT.FILL, true, true); gd_resolution.heightHint = 60; resolution.setLayoutData(gd_resolution); resolution.addSelectionListener(updateActionSelectionAdapter); Composite priorityComposite = new Composite(bottomForm, SWT.NONE); GridLayout priorityLayout = new GridLayout(); priorityLayout.marginTop = 7; priorityLayout.marginWidth = 0; priorityLayout.marginHeight = 0; priorityLayout.horizontalSpacing = 0; priorityComposite.setLayout(priorityLayout); Label priorityLabel = new Label(priorityComposite, SWT.LEFT); priorityLabel.setText("Priori&ty:"); priority = new List(priorityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_priority = new GridData(SWT.FILL, SWT.FILL, true, true); gd_priority.heightHint = 60; priority.setLayoutData(gd_priority); priority.addSelectionListener(updateActionSelectionAdapter); Composite severityComposite = new Composite(bottomForm, SWT.NONE); GridLayout severityLayout = new GridLayout(); severityLayout.marginTop = 7; severityLayout.marginWidth = 0; severityLayout.marginHeight = 0; severityLayout.horizontalSpacing = 0; severityComposite.setLayout(severityLayout); Label severityLabel = new Label(severityComposite, SWT.LEFT); severityLabel.setText("Se&verity:"); severity = new List(severityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_severity = new GridData(SWT.FILL, SWT.FILL, true, true); gd_severity.heightHint = 60; severity.setLayoutData(gd_severity); severity.addSelectionListener(updateActionSelectionAdapter); Composite hardwareComposite = new Composite(bottomForm, SWT.NONE); GridLayout hardwareLayout = new GridLayout(); hardwareLayout.marginTop = 7; hardwareLayout.marginWidth = 0; hardwareLayout.marginHeight = 0; hardwareLayout.horizontalSpacing = 0; hardwareComposite.setLayout(hardwareLayout); Label hardwareLabel = new Label(hardwareComposite, SWT.LEFT); hardwareLabel.setText("Hard&ware:"); hardware = new List(hardwareComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_hardware = new GridData(SWT.FILL, SWT.FILL, true, true); gd_hardware.heightHint = 60; hardware.setLayoutData(gd_hardware); hardware.addSelectionListener(updateActionSelectionAdapter); Composite osComposite = new Composite(bottomForm, SWT.NONE); GridLayout osLayout = new GridLayout(); osLayout.marginTop = 7; osLayout.marginWidth = 0; osLayout.marginHeight = 0; osLayout.horizontalSpacing = 0; osComposite.setLayout(osLayout); Label osLabel = new Label(osComposite, SWT.LEFT); osLabel.setText("&Operating System:"); os = new List(osComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_os = new GridData(SWT.FILL, SWT.FILL, true, true); gd_os.heightHint = 60; os.setLayoutData(gd_os); os.addSelectionListener(updateActionSelectionAdapter); bottomForm.setWeights(new int[] { 88, 90, 50, 77, 88, 85 }); } private void createSearchGroup(Composite control) { Composite composite = new Composite(control, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); GridLayout gridLayout = new GridLayout(); gridLayout.marginTop = 7; gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; gridLayout.numColumns = 2; composite.setLayout(gridLayout); Label changedInTheLabel = new Label(composite, SWT.LEFT); changedInTheLabel.setLayoutData(new GridData()); changedInTheLabel.setText("Ch&anged in:"); Composite updateComposite = new Composite(composite, SWT.NONE); updateComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); GridLayout updateLayout = new GridLayout(3, false); updateLayout.marginWidth = 0; updateLayout.horizontalSpacing = 0; updateLayout.marginHeight = 0; updateComposite.setLayout(updateLayout); daysText = new Text(updateComposite, SWT.BORDER); daysText.setLayoutData(new GridData(40, SWT.DEFAULT)); daysText.setTextLimit(5); daysText.addListener(SWT.Modify, this); Label label = new Label(updateComposite, SWT.LEFT); label.setText(" days."); Button updateButton = new Button(updateComposite, SWT.PUSH); updateButton.setText("Up&date Attributes from Repository"); updateButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false)); updateButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (repository != null) { // try { updateConfiguration(true); // } catch (final CoreException e1) { // PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { // public void run() { // MessageDialog.openError(Display.getDefault().getActiveShell(), "Bugzilla Search Page", // "Unable to get configuration. Ensure proper repository configuration in " // + TasksUiPlugin.LABEL_VIEW_REPOSITORIES + ".\n\n"); // } // }); // } } else { MessageDialog.openInformation(Display.getCurrent().getActiveShell(), IBugzillaConstants.TITLE_MESSAGE_DIALOG, TaskRepositoryManager.MESSAGE_NO_REPOSITORY); } } }); } /** * Creates the buttons for remembering a query and accessing previously saved queries. */ protected Control createSaveQuery(Composite control) { GridLayout layout; GridData gd; Group group = new Group(control, SWT.NONE); layout = new GridLayout(3, false); group.setLayout(layout); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); gd = new GridData(GridData.BEGINNING | GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); gd.horizontalSpan = 2; group.setLayoutData(gd); // loadButton = new Button(group, SWT.PUSH | SWT.LEFT); // loadButton.setText("Saved Queries..."); // final BugzillaSearchPage bsp = this; // loadButton.addSelectionListener(new SelectionAdapter() { // // @Override // public void widgetSelected(SelectionEvent event) { // GetQueryDialog qd = new GetQueryDialog(getShell(), "Saved Queries", // input); // if (qd.open() == InputDialog.OK) { // selIndex = qd.getSelected(); // if (selIndex != -1) { // rememberedQuery = true; // performAction(); // bsp.getShell().close(); // } // } // } // }); // loadButton.setEnabled(true); // loadButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); // // saveButton = new Button(group, SWT.PUSH | SWT.LEFT); // saveButton.setText("Remember..."); // saveButton.addSelectionListener(new SelectionAdapter() { // // @Override // public void widgetSelected(SelectionEvent event) { // SaveQueryDialog qd = new SaveQueryDialog(getShell(), "Remember Query"); // if (qd.open() == InputDialog.OK) { // String qName = qd.getText(); // if (qName != null && qName.compareTo("") != 0) { // try { // input.add(getQueryParameters().toString(), qName, summaryPattern.getText()); // } catch (UnsupportedEncodingException e) { // /* // * Do nothing. Every implementation of the Java // * platform is required to support the standard // * charset "UTF-8" // */ // } // } // } // } // }); // saveButton.setEnabled(true); // saveButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); return group; } // public static SavedQueryFile getInput() { // return input; // } private void handleWidgetSelected(Combo widget, Combo operation, ArrayList<BugzillaSearchData> history) { if (widget.getSelectionIndex() < 0) return; int index = history.size() - 1 - widget.getSelectionIndex(); BugzillaSearchData patternData = history.get(index); if (patternData == null || !widget.getText().equals(patternData.pattern)) return; widget.setText(patternData.pattern); operation.setText(operation.getItem(patternData.operation)); } // TODO: avoid overriding? public boolean performAction() { if (restoreQueryOptions) { saveState(); } getPatternData(summaryPattern, summaryOperation, previousSummaryPatterns); getPatternData(commentPattern, commentOperation, previousCommentPatterns); getPatternData(emailPattern, emailOperation, previousEmailPatterns); getPatternData(emailPattern2, emailOperation2, previousEmailPatterns2); getPatternData(keywords, keywordsOperation, previousKeywords); String summaryText = summaryPattern.getText(); BugzillaUiPlugin.getDefault().getPreferenceStore().setValue(IBugzillaConstants.MOST_RECENT_QUERY, summaryText); return super.performAction(); } @Override public void setVisible(boolean visible) { if (visible && summaryPattern != null) { if (firstTime) { if (repository == null) { repository = TasksUiPlugin.getRepositoryManager().getDefaultRepository( BugzillaCorePlugin.REPOSITORY_KIND); } // Set<TaskRepository> repositories = TasksUiPlugin.getRepositoryManager().getRepositories(BugzillaCorePlugin.REPOSITORY_KIND); // String[] repositoryUrls = new String[repositories.size()]; // int i = 0; // int indexToSelect = 0; // for (Iterator<TaskRepository> iter = repositories.iterator(); iter.hasNext();) { // TaskRepository currRepsitory = iter.next(); // // if (i == 0 && repository == null) { // // repository = currRepsitory; // // indexToSelect = 0; // // } // if (repository != null && repository.equals(currRepsitory)) { // indexToSelect = i; // } // repositoryUrls[i] = currRepsitory.getUrl(); // i++; // } // IDialogSettings settings = getDialogSettings(); // if (repositoryCombo != null) { // repositoryCombo.setItems(repositoryUrls); // if (repositoryUrls.length == 0) { // MessageDialog.openInformation(Display.getCurrent().getActiveShell(), IBugzillaConstants.TITLE_MESSAGE_DIALOG, // TaskRepositoryManager.MESSAGE_NO_REPOSITORY); // } else { // String selectRepo = settings.get(STORE_REPO_ID); // if (selectRepo != null && repositoryCombo.indexOf(selectRepo) > -1) { // repositoryCombo.setText(selectRepo); // repository = TasksUiPlugin.getRepositoryManager().getRepository( // BugzillaCorePlugin.REPOSITORY_KIND, repositoryCombo.getText()); // if (repository == null) { // repository = TasksUiPlugin.getRepositoryManager().getDefaultRepository( BugzillaCorePlugin.REPOSITORY_KIND); // } // } else { // repositoryCombo.select(indexToSelect); // } // updateAttributesFromRepository(repositoryCombo.getText(), null, false); // } // } firstTime = false; // Set item and text here to prevent page from resizing for (String searchPattern : getPreviousPatterns(previousSummaryPatterns)) { summaryPattern.add(searchPattern); } // summaryPattern.setItems(getPreviousPatterns(previousSummaryPatterns)); for (String comment : getPreviousPatterns(previousCommentPatterns)) { commentPattern.add(comment); } // commentPattern.setItems(getPreviousPatterns(previousCommentPatterns)); for (String email : getPreviousPatterns(previousEmailPatterns)) { emailPattern.add(email); } for (String email : getPreviousPatterns(previousEmailPatterns2)) { emailPattern2.add(email); } // emailPattern.setItems(getPreviousPatterns(previousEmailPatterns)); for (String keyword : getPreviousPatterns(previousKeywords)) { keywords.add(keyword); } // TODO: update status, resolution, severity etc if possible... if (repository != null) { updateAttributesFromConfiguration(null); if (product.getItemCount() == 0) { try { repositoryConfiguration = BugzillaCorePlugin.getRepositoryConfiguration(repository, true, new NullProgressMonitor()); updateAttributesFromConfiguration(null); } catch (final CoreException e1) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { MessageDialog.openError(Display.getDefault().getActiveShell(), "Bugzilla Search Page", "Unable to get configuration. Ensure proper repository configuration in " + TasksUiPlugin.LABEL_VIEW_REPOSITORIES + ".\n\n"); } }); } } } if (originalQuery != null) { try { updateDefaults(originalQuery.getUrl()); } catch (UnsupportedEncodingException e) { // ignore } } } /* * hack: we have to select the correct product, then update the * attributes so the component/version/milestone lists have the * proper values, then we can restore all the widget selections. */ if (repository != null) { IDialogSettings settings = getDialogSettings(); String repoId = "." + repository.getRepositoryUrl(); if (getWizard() == null && restoreQueryOptions && settings.getArray(STORE_PRODUCT_ID + repoId) != null && product != null) { product.setSelection(nonNullArray(settings, STORE_PRODUCT_ID + repoId)); if (product.getSelection().length > 0) { updateAttributesFromConfiguration(product.getSelection()); } restoreWidgetValues(); } } setPageComplete(isPageComplete()); if (getWizard() == null) { // TODO: wierd check summaryPattern.setFocus(); } } super.setVisible(visible); } /** * Returns <code>true</code> if at least some parameter is given to query on. */ private boolean canQuery() { if (isControlCreated()) { return product.getSelectionCount() > 0 || component.getSelectionCount() > 0 || version.getSelectionCount() > 0 || target.getSelectionCount() > 0 || status.getSelectionCount() > 0 || resolution.getSelectionCount() > 0 || severity.getSelectionCount() > 0 || priority.getSelectionCount() > 0 || hardware.getSelectionCount() > 0 || os.getSelectionCount() > 0 || summaryPattern.getText().length() > 0 || commentPattern.getText().length() > 0 || emailPattern.getText().length() > 0 || emailPattern2.getText().length() > 0 || keywords.getText().length() > 0; } else { return false; } } @Override public boolean isPageComplete() { String message = null; if (daysText != null) { String days = daysText.getText(); if (days.length() > 0) { try { if (Integer.parseInt(days) < 0) { message = NUM_DAYS_POSITIVE + days + " is invalid."; setErrorMessage(message); return false; } } catch (NumberFormatException ex) { message = NUM_DAYS_POSITIVE + days + " is invalid."; setErrorMessage(message); return false; } } } return getWizard() == null ? canQuery() : canQuery() && super.isPageComplete(); } /** * Return search pattern data and update search history list. An existing entry will be updated or a new one * created. */ private BugzillaSearchData getPatternData(Combo widget, Combo operation, ArrayList<BugzillaSearchData> previousSearchQueryData) { String pattern = widget.getText(); if (pattern == null || pattern.trim().equals("")) { return null; } BugzillaSearchData match = null; int i = previousSearchQueryData.size() - 1; while (i >= 0) { match = previousSearchQueryData.get(i); if (pattern.equals(match.pattern)) { break; } i--; } if (i >= 0 && match != null) { match.operation = operation.getSelectionIndex(); // remove - will be added last (see below) previousSearchQueryData.remove(match); } else { match = new BugzillaSearchData(widget.getText(), operation.getSelectionIndex()); } previousSearchQueryData.add(match); return match; } /** * Returns an array of previous summary patterns */ private String[] getPreviousPatterns(ArrayList<BugzillaSearchData> patternHistory) { int size = patternHistory.size(); String[] patterns = new String[size]; for (int i = 0; i < size; i++) patterns[i] = (patternHistory.get(size - 1 - i)).pattern; return patterns; } public String getSearchURL(TaskRepository repository) { try { // if (rememberedQuery) { // return getQueryURL(repository, new StringBuffer(input.getQueryParameters(selIndex))); // } else { return getQueryURL(repository, getQueryParameters()); // } } catch (UnsupportedEncodingException e) { // ignore } return ""; } protected String getQueryURL(TaskRepository repository, StringBuffer params) { StringBuffer url = new StringBuffer(getQueryURLStart(repository).toString()); url.append(params); // HACK make sure that the searches come back sorted by priority. This // should be a search option though url.append("&order=Importance"); // url.append(BugzillaRepositoryUtil.contentTypeRDF); return url.toString(); } /** * Creates the bugzilla query URL start. * * Example: https://bugs.eclipse.org/bugs/buglist.cgi? */ private StringBuffer getQueryURLStart(TaskRepository repository) { StringBuffer sb = new StringBuffer(repository.getRepositoryUrl()); if (sb.charAt(sb.length() - 1) != '/') { sb.append('/'); } sb.append("buglist.cgi?"); return sb; } /** * Goes through the query form and builds up the query parameters. * * Example: short_desc_type=substring&amp;short_desc=bla&amp; ... TODO: The encoding here should match * TaskRepository.getCharacterEncoding() * * @throws UnsupportedEncodingException */ protected StringBuffer getQueryParameters() throws UnsupportedEncodingException { StringBuffer sb = new StringBuffer(); sb.append("short_desc_type="); sb.append(patternOperationValues[summaryOperation.getSelectionIndex()]); sb.append("&short_desc="); sb.append(URLEncoder.encode(summaryPattern.getText(), repository.getCharacterEncoding())); int[] selected = product.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&product="); sb.append(URLEncoder.encode(product.getItem(selected[i]), repository.getCharacterEncoding())); } selected = component.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&component="); sb.append(URLEncoder.encode(component.getItem(selected[i]), repository.getCharacterEncoding())); } selected = version.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&version="); sb.append(URLEncoder.encode(version.getItem(selected[i]), repository.getCharacterEncoding())); } selected = target.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&target_milestone="); sb.append(URLEncoder.encode(target.getItem(selected[i]), repository.getCharacterEncoding())); } sb.append("&long_desc_type="); sb.append(patternOperationValues[commentOperation.getSelectionIndex()]); sb.append("&long_desc="); sb.append(URLEncoder.encode(commentPattern.getText(), repository.getCharacterEncoding())); selected = status.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&bug_status="); sb.append(URLEncoder.encode(status.getItem(selected[i]), repository.getCharacterEncoding())); } selected = resolution.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&resolution="); sb.append(URLEncoder.encode(resolution.getItem(selected[i]), repository.getCharacterEncoding())); } selected = severity.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&bug_severity="); sb.append(URLEncoder.encode(severity.getItem(selected[i]), repository.getCharacterEncoding())); } selected = priority.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&priority="); sb.append(URLEncoder.encode(priority.getItem(selected[i]), repository.getCharacterEncoding())); } selected = hardware.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&ref_platform="); sb.append(URLEncoder.encode(hardware.getItem(selected[i]), repository.getCharacterEncoding())); } selected = os.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&op_sys="); sb.append(URLEncoder.encode(os.getItem(selected[i]), repository.getCharacterEncoding())); } if (emailPattern.getText() != null && !emailPattern.getText().trim().equals("")) { boolean selectionMade = false; for (Button button : emailButtons) { if (button.getSelection()) { selectionMade = true; break; } } if (selectionMade) { for (int i = 0; i < emailButtons.length; i++) { if (emailButtons[i].getSelection()) { sb.append("&"); sb.append(emailRoleValues[i]); sb.append("=1"); } } sb.append("&emailtype1="); sb.append(emailOperationValues[emailOperation.getSelectionIndex()]); sb.append("&email1="); sb.append(URLEncoder.encode(emailPattern.getText(), repository.getCharacterEncoding())); } } if (emailPattern2.getText() != null && !emailPattern2.getText().trim().equals("")) { boolean selectionMade = false; for (Button button : emailButtons2) { if (button.getSelection()) { selectionMade = true; break; } } if (selectionMade) { for (int i = 0; i < emailButtons2.length; i++) { if (emailButtons2[i].getSelection()) { sb.append("&"); sb.append(emailRoleValues2[i]); sb.append("=1"); } } sb.append("&emailtype2="); sb.append(emailOperationValues[emailOperation2.getSelectionIndex()]); sb.append("&email2="); sb.append(URLEncoder.encode(emailPattern2.getText(), repository.getCharacterEncoding())); } } if (daysText.getText() != null && !daysText.getText().equals("")) { try { Integer.parseInt(daysText.getText()); sb.append("&changedin="); sb.append(URLEncoder.encode(daysText.getText(), repository.getCharacterEncoding())); } catch (NumberFormatException ignored) { // this means that the days is not a number, so don't worry } } if (keywords.getText() != null && !keywords.getText().trim().equals("")) { sb.append("&keywords_type="); sb.append(keywordOperationValues[keywordsOperation.getSelectionIndex()]); sb.append("&keywords="); sb.append(URLEncoder.encode(keywords.getText().replace(',', ' '), repository.getCharacterEncoding())); } return sb; } public IDialogSettings getDialogSettings() { IDialogSettings settings = BugzillaUiPlugin.getDefault().getDialogSettings(); fDialogSettings = settings.getSection(PAGE_NAME); if (fDialogSettings == null) fDialogSettings = settings.addNewSection(PAGE_NAME); return fDialogSettings; } /** * Initializes itself from the stored page settings. */ private void readConfiguration() { getDialogSettings(); } private void updateAttributesFromConfiguration(String[] selectedProducts) { if(repositoryConfiguration == null) { updateConfiguration(false); } if (repositoryConfiguration != null) { if (selectedProducts == null) { java.util.List<String> products = repositoryConfiguration.getProducts(); String[] productsList = products.toArray(new String[products.size()]); Arrays.sort(productsList, String.CASE_INSENSITIVE_ORDER); product.setItems(productsList); } String[] componentsList = BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_COMPONENT, selectedProducts, repositoryConfiguration); Arrays.sort(componentsList, String.CASE_INSENSITIVE_ORDER); component.setItems(componentsList); version.setItems(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_VERSION, selectedProducts, repositoryConfiguration)); target.setItems(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_TARGET, selectedProducts, repositoryConfiguration)); status.setItems(convertStringListToArray(repositoryConfiguration.getStatusValues())); resolution.setItems(convertStringListToArray(repositoryConfiguration.getResolutions())); severity.setItems(convertStringListToArray(repositoryConfiguration.getSeverities())); priority.setItems(convertStringListToArray(repositoryConfiguration.getPriorities())); hardware.setItems(convertStringListToArray(repositoryConfiguration.getPlatforms())); os.setItems(convertStringListToArray(repositoryConfiguration.getOSs())); } } public TaskRepository getRepository() { return repository; } public void setRepository(TaskRepository repository) { this.repository = repository; } public boolean canFlipToNextPage() { // if (getErrorMessage() != null) // return false; // // return true; return false; } public void handleEvent(Event event) { if (getWizard() != null) { getWizard().getContainer().updateButtons(); } } /** * TODO: get rid of this? */ public void updateDefaults(String startingUrl) throws UnsupportedEncodingException { // String serverName = startingUrl.substring(0, // startingUrl.indexOf("?")); startingUrl = startingUrl.substring(startingUrl.indexOf("?") + 1); String[] options = startingUrl.split("&"); for (String option : options) { String key = option.substring(0, option.indexOf("=")); String value = URLDecoder.decode(option.substring(option.indexOf("=") + 1), repository.getCharacterEncoding()); if (key == null) continue; if (key.equals("short_desc")) { summaryPattern.setText(value); } else if (key.equals("short_desc_type")) { if (value.equals("allwordssubstr")) value = "all words"; else if (value.equals("anywordssubstr")) value = "any word"; int index = 0; for (String item : summaryOperation.getItems()) { if (item.compareTo(value) == 0) break; index++; } if (index < summaryOperation.getItemCount()) { summaryOperation.select(index); } } else if (key.equals("product")) { String[] sel = product.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; product.setSelection(selList.toArray(sel)); updateAttributesFromConfiguration(selList.toArray(sel)); } else if (key.equals("component")) { String[] sel = component.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; component.setSelection(selList.toArray(sel)); } else if (key.equals("version")) { String[] sel = version.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; version.setSelection(selList.toArray(sel)); } else if (key.equals("target_milestone")) { // XXX String[] sel = target.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; target.setSelection(selList.toArray(sel)); } else if (key.equals("version")) { String[] sel = version.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; version.setSelection(selList.toArray(sel)); } else if (key.equals("long_desc_type")) { if (value.equals("allwordssubstr")) value = "all words"; else if (value.equals("anywordssubstr")) value = "any word"; int index = 0; for (String item : commentOperation.getItems()) { if (item.compareTo(value) == 0) break; index++; } if (index < commentOperation.getItemCount()) { commentOperation.select(index); } } else if (key.equals("long_desc")) { commentPattern.setText(value); } else if (key.equals("bug_status")) { String[] sel = status.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; status.setSelection(selList.toArray(sel)); } else if (key.equals("resolution")) { String[] sel = resolution.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; resolution.setSelection(selList.toArray(sel)); } else if (key.equals("bug_severity")) { String[] sel = severity.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; severity.setSelection(selList.toArray(sel)); } else if (key.equals("priority")) { String[] sel = priority.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; priority.setSelection(selList.toArray(sel)); } else if (key.equals("ref_platform")) { String[] sel = hardware.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; hardware.setSelection(selList.toArray(sel)); } else if (key.equals("op_sys")) { String[] sel = os.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; os.setSelection(selList.toArray(sel)); } else if (key.equals("emailassigned_to1")) { // HACK: email // buttons // assumed to be // in same // position if (value.equals("1")) emailButtons[0].setSelection(true); else emailButtons[0].setSelection(false); } else if (key.equals("emailreporter1")) { // HACK: email // buttons assumed // to be in same // position if (value.equals("1")) emailButtons[1].setSelection(true); else emailButtons[1].setSelection(false); } else if (key.equals("emailcc1")) { // HACK: email buttons // assumed to be in same // position if (value.equals("1")) emailButtons[2].setSelection(true); else emailButtons[2].setSelection(false); } else if (key.equals("emaillongdesc1")) { // HACK: email // buttons assumed // to be in same // position if (value.equals("1")) emailButtons[3].setSelection(true); else emailButtons[3].setSelection(false); } else if (key.equals("emailtype1")) { int index = 0; for (String item : emailOperation.getItems()) { if (item.compareTo(value) == 0) break; index++; } if (index < emailOperation.getItemCount()) { emailOperation.select(index); } } else if (key.equals("email1")) { emailPattern.setText(value); } else if (key.equals("emailassigned_to2")) { // HACK: email // buttons // assumed to be // in same // position if (value.equals("1")) emailButtons2[0].setSelection(true); else emailButtons2[0].setSelection(false); } else if (key.equals("emailreporter2")) { // HACK: email // buttons assumed // to be in same // position if (value.equals("1")) emailButtons2[1].setSelection(true); else emailButtons2[1].setSelection(false); } else if (key.equals("emailcc2")) { // HACK: email buttons // assumed to be in same // position if (value.equals("1")) emailButtons2[2].setSelection(true); else emailButtons2[2].setSelection(false); } else if (key.equals("emaillongdesc2")) { // HACK: email // buttons assumed // to be in same // position if (value.equals("1")) emailButtons2[3].setSelection(true); else emailButtons2[3].setSelection(false); } else if (key.equals("emailtype2")) { int index = 0; for (String item : emailOperation2.getItems()) { if (item.compareTo(value) == 0) break; index++; } if (index < emailOperation2.getItemCount()) { emailOperation2.select(index); } } else if (key.equals("email2")) { emailPattern2.setText(value); } else if (key.equals("changedin")) { daysText.setText(value); } else if (key.equals("keywords")) { keywords.setText(value.replace(' ', ',')); } else if (key.equals("keywords_type")) { int index = 0; for (String item : keywordOperationValues) { if (item.equals(value)) { keywordsOperation.select(index); break; } index++; } } } } @Override public BugzillaRepositoryQuery getQuery() { if (originalQuery == null) { try { originalQuery = new BugzillaRepositoryQuery(repository.getRepositoryUrl(), getQueryURL(repository, getQueryParameters()), getQueryTitle()); } catch (UnsupportedEncodingException e) { return null; } } else { try { originalQuery.setUrl(getQueryURL(repository, getQueryParameters())); // originalQuery.setMaxHits(Integer.parseInt(getMaxHits())); originalQuery.setHandleIdentifier(getQueryTitle()); } catch (UnsupportedEncodingException e) { return null; } } return originalQuery; } private String[] nonNullArray(IDialogSettings settings, String id) { String[] value = settings.getArray(id); if (value == null) { return new String[] {}; } return value; } private void restoreWidgetValues() { try { IDialogSettings settings = getDialogSettings(); String repoId = "." + repository.getRepositoryUrl(); if (!restoreQueryOptions || settings.getArray(STORE_PRODUCT_ID + repoId) == null || product == null) { return; } // set widgets to stored values product.setSelection(nonNullArray(settings, STORE_PRODUCT_ID + repoId)); component.setSelection(nonNullArray(settings, STORE_COMPONENT_ID + repoId)); version.setSelection(nonNullArray(settings, STORE_VERSION_ID + repoId)); target.setSelection(nonNullArray(settings, STORE_MSTONE_ID + repoId)); status.setSelection(nonNullArray(settings, STORE_STATUS_ID + repoId)); resolution.setSelection(nonNullArray(settings, STORE_RESOLUTION_ID + repoId)); severity.setSelection(nonNullArray(settings, STORE_SEVERITY_ID + repoId)); priority.setSelection(nonNullArray(settings, STORE_PRIORITY_ID + repoId)); hardware.setSelection(nonNullArray(settings, STORE_HARDWARE_ID + repoId)); os.setSelection(nonNullArray(settings, STORE_OS_ID + repoId)); summaryOperation.select(settings.getInt(STORE_SUMMARYMATCH_ID + repoId)); commentOperation.select(settings.getInt(STORE_COMMENTMATCH_ID + repoId)); emailOperation.select(settings.getInt(STORE_EMAILMATCH_ID + repoId)); for (int i = 0; i < emailButtons.length; i++) { emailButtons[i].setSelection(settings.getBoolean(STORE_EMAILBUTTON_ID + i + repoId)); } summaryPattern.setText(settings.get(STORE_SUMMARYTEXT_ID + repoId)); commentPattern.setText(settings.get(STORE_COMMENTTEXT_ID + repoId)); emailPattern.setText(settings.get(STORE_EMAILADDRESS_ID + repoId)); try { emailOperation2.select(settings.getInt(STORE_EMAIL2MATCH_ID + repoId)); } catch (Exception e) { //ignore } for (int i = 0; i < emailButtons2.length; i++) { emailButtons2[i].setSelection(settings.getBoolean(STORE_EMAIL2BUTTON_ID + i + repoId)); } emailPattern2.setText(settings.get(STORE_EMAIL2ADDRESS_ID + repoId)); if (settings.get(STORE_KEYWORDS_ID + repoId) != null) { keywords.setText(settings.get(STORE_KEYWORDS_ID + repoId)); keywordsOperation.select(settings.getInt(STORE_KEYWORDSMATCH_ID + repoId)); } } catch (IllegalArgumentException e) { //ignore } } public void saveState() { String repoId = "." + repository.getRepositoryUrl(); IDialogSettings settings = getDialogSettings(); settings.put(STORE_PRODUCT_ID + repoId, product.getSelection()); settings.put(STORE_COMPONENT_ID + repoId, component.getSelection()); settings.put(STORE_VERSION_ID + repoId, version.getSelection()); settings.put(STORE_MSTONE_ID + repoId, target.getSelection()); settings.put(STORE_STATUS_ID + repoId, status.getSelection()); settings.put(STORE_RESOLUTION_ID + repoId, resolution.getSelection()); settings.put(STORE_SEVERITY_ID + repoId, severity.getSelection()); settings.put(STORE_PRIORITY_ID + repoId, priority.getSelection()); settings.put(STORE_HARDWARE_ID + repoId, hardware.getSelection()); settings.put(STORE_OS_ID + repoId, os.getSelection()); settings.put(STORE_SUMMARYMATCH_ID + repoId, summaryOperation.getSelectionIndex()); settings.put(STORE_COMMENTMATCH_ID + repoId, commentOperation.getSelectionIndex()); settings.put(STORE_EMAILMATCH_ID + repoId, emailOperation.getSelectionIndex()); for (int i = 0; i < emailButtons.length; i++) { settings.put(STORE_EMAILBUTTON_ID + i + repoId, emailButtons[i].getSelection()); } settings.put(STORE_SUMMARYTEXT_ID + repoId, summaryPattern.getText()); settings.put(STORE_COMMENTTEXT_ID + repoId, commentPattern.getText()); settings.put(STORE_EMAILADDRESS_ID + repoId, emailPattern.getText()); settings.put(STORE_EMAIL2ADDRESS_ID + repoId, emailPattern2.getText()); settings.put(STORE_EMAIL2MATCH_ID + repoId, emailOperation2.getSelectionIndex()); for (int i = 0; i < emailButtons2.length; i++) { settings.put(STORE_EMAIL2BUTTON_ID + i + repoId, emailButtons2[i].getSelection()); } settings.put(STORE_KEYWORDS_ID + repoId, keywords.getText()); settings.put(STORE_KEYWORDSMATCH_ID + repoId, keywordsOperation.getSelectionIndex()); // settings.put(STORE_REPO_ID, repositoryCombo.getText()); } /* Testing hook to see if any products are present */ public int getProductCount() throws Exception { return product.getItemCount(); } public boolean isRestoreQueryOptions() { return restoreQueryOptions; } public void setRestoreQueryOptions(boolean restoreQueryOptions) { this.restoreQueryOptions = restoreQueryOptions; } /** * Adds content assist to the given text field. * * @param text * text field to decorate. * @param proposalProvider * instance providing content proposals * @return the ContentAssistCommandAdapter for the field. */ // API 3.0 get this from the AttributeEditorToolkit private ContentAssistCommandAdapter applyContentAssist(Combo text, IContentProposalProvider proposalProvider) { ControlDecoration controlDecoration = new ControlDecoration(text, (SWT.TOP | SWT.LEFT)); controlDecoration.setMarginWidth(0); controlDecoration.setShowHover(true); controlDecoration.setShowOnlyOnFocus(true); FieldDecoration contentProposalImage = FieldDecorationRegistry.getDefault().getFieldDecoration( FieldDecorationRegistry.DEC_CONTENT_PROPOSAL); controlDecoration.setImage(contentProposalImage.getImage()); ComboContentAdapter textContentAdapter = new ComboContentAdapter(); ContentAssistCommandAdapter adapter = new ContentAssistCommandAdapter(text, textContentAdapter, proposalProvider, "org.eclipse.ui.edit.text.contentAssist.proposals", new char[0]); IBindingService bindingService = (IBindingService) PlatformUI.getWorkbench().getService(IBindingService.class); controlDecoration.setDescriptionText(NLS.bind("Content Assist Available ({0})", bindingService.getBestActiveBindingFormattedFor(adapter.getCommandId()))); return adapter; } /** * Creates an IContentProposalProvider to provide content assist proposals for the given attribute. * * @param attribute * attribute for which to provide content assist. * @return the IContentProposalProvider. */ // API 3.0 get this from the AttributeEditorToolkit? private IContentProposalProvider createContentProposalProvider() { return new PersonProposalProvider(repository.getRepositoryUrl(), repository.getConnectorKind()); } // API 3.0 get this from the AttributeEditorToolkit? private ILabelProvider createProposalLabelProvider() { return new PersonProposalLabelProvider(); } private String[] convertStringListToArray(java.util.List<String> stringList) { return stringList.toArray(new String[stringList.size()]); } private void updateConfiguration(final boolean force) { if (repository != null) { IRunnableWithProgress updateRunnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (monitor == null) { monitor = new NullProgressMonitor(); } try { monitor.beginTask("Updating search options...", IProgressMonitor.UNKNOWN); repositoryConfiguration = BugzillaCorePlugin.getRepositoryConfiguration(repository, force, monitor); } catch (final Exception e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } }; try { // TODO: make cancelable (bug 143011) if (getContainer() != null) { getContainer().run(true, true, updateRunnable); } else if (scontainer != null) { scontainer.getRunnableContext().run(true, true, updateRunnable); } else { IProgressService service = PlatformUI.getWorkbench().getProgressService(); service.busyCursorWhile(updateRunnable); } } catch (InvocationTargetException ex) { Shell shell = null; if (getWizard() != null && getWizard().getContainer() != null) { shell = getWizard().getContainer().getShell(); } if (shell == null && getControl() != null) { shell = getControl().getShell(); } if (ex.getCause() instanceof CoreException) { CoreException cause = ((CoreException) ex.getCause()); if (cause.getStatus() instanceof RepositoryStatus && ((RepositoryStatus) cause.getStatus()).isHtmlMessage()) { // TOOD: use StatusManager // this.setControlsEnabled(false); // scontainer.setPerformActionEnabled(false); if (shell != null) { shell.setEnabled(false); } WebBrowserDialog dialog = new WebBrowserDialog(shell, "Error updating search options", null, cause.getStatus().getMessage(), NONE, new String[] { IDialogConstants.OK_LABEL }, 0, ((RepositoryStatus) cause.getStatus()).getHtmlMessage()); dialog.setBlockOnOpen(true); dialog.open(); if (shell != null) { shell.setEnabled(true); } return; // this.setPageComplete(this.isPageComplete()); // this.setControlsEnabled(true); } else { StatusHandler.log(new Status(IStatus.ERROR, BugzillaUiPlugin.PLUGIN_ID, cause.getMessage(), cause)); } } if(ex.getCause() instanceof OperationCanceledException) { return; } MessageDialog.openError(shell, "Error updating search options", "Error was: " + ex.getCause().getMessage()); return; } catch (InterruptedException ex) { return; } updateAttributesFromConfiguration(null); } } }
true
true
protected void createOptionsGroup(Composite control) { GridLayout sashFormLayout = new GridLayout(); sashFormLayout.numColumns = 4; sashFormLayout.marginHeight = 5; sashFormLayout.marginWidth = 5; sashFormLayout.horizontalSpacing = 5; final Composite composite = new Composite(control, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); final GridLayout gridLayout = new GridLayout(); gridLayout.marginBottom = 8; gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; gridLayout.numColumns = 4; composite.setLayout(gridLayout); if (!inSearchContainer()) { final Label queryTitleLabel = new Label(composite, SWT.NONE); queryTitleLabel.setText("&Query Title:"); Text queryTitle = new Text(composite, SWT.BORDER); queryTitle.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); if (originalQuery != null) { queryTitle.setText(originalQuery.getSummary()); } queryTitle.addModifyListener(new ModifyListenerImplementation()); title = queryTitle; title.setFocus(); } // Info text Label labelSummary = new Label(composite, SWT.LEFT); labelSummary.setText("&Summary:"); labelSummary.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT)); //labelSummary.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // Pattern combo summaryPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); summaryPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); summaryPattern.addModifyListener(new ModifyListenerImplementation()); summaryPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(summaryPattern, summaryOperation, previousSummaryPatterns); } }); summaryOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); summaryOperation.setItems(patternOperationText); summaryOperation.setText(patternOperationText[0]); summaryOperation.select(0); // Info text Label labelComment = new Label(composite, SWT.LEFT); labelComment.setText("&Comment:"); //labelComment.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // Comment pattern combo commentPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); commentPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1)); commentPattern.addModifyListener(new ModifyListenerImplementation()); commentPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(commentPattern, commentOperation, previousCommentPatterns); } }); commentOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); commentOperation.setItems(patternOperationText); commentOperation.setText(patternOperationText[0]); commentOperation.select(0); Label labelEmail = new Label(composite, SWT.LEFT); labelEmail.setText("&Email:"); //labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // pattern combo emailPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); emailPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); emailPattern.addModifyListener(new ModifyListenerImplementation()); emailPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(emailPattern, emailOperation, previousEmailPatterns); } }); ContentAssistCommandAdapter adapter = applyContentAssist(emailPattern, createContentProposalProvider()); ILabelProvider propsalLabelProvider = createProposalLabelProvider(); if (propsalLabelProvider != null) { adapter.setLabelProvider(propsalLabelProvider); } adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); Composite emailComposite = new Composite(composite, SWT.NONE); emailComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); GridLayout emailLayout = new GridLayout(); emailLayout.marginWidth = 0; emailLayout.marginHeight = 0; emailLayout.horizontalSpacing = 2; emailLayout.numColumns = 4; emailComposite.setLayout(emailLayout); Button button0 = new Button(emailComposite, SWT.CHECK); button0.setText("owner"); Button button1 = new Button(emailComposite, SWT.CHECK); button1.setText("reporter"); Button button2 = new Button(emailComposite, SWT.CHECK); button2.setText("cc"); Button button3 = new Button(emailComposite, SWT.CHECK); button3.setText("commenter"); emailButtons = new Button[] { button0, button1, button2, button3 }; // operation combo emailOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); emailOperation.setItems(emailOperationText); emailOperation.setText(emailOperationText[0]); emailOperation.select(0); // Email2 Label labelEmail2 = new Label(composite, SWT.LEFT); labelEmail2.setText("Email &2:"); //labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // pattern combo emailPattern2 = new Combo(composite, SWT.SINGLE | SWT.BORDER); emailPattern2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); emailPattern2.addModifyListener(new ModifyListenerImplementation()); emailPattern2.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(emailPattern2, emailOperation2, previousEmailPatterns2); } }); ContentAssistCommandAdapter adapter2 = applyContentAssist(emailPattern2, createContentProposalProvider()); ILabelProvider propsalLabelProvider2 = createProposalLabelProvider(); if (propsalLabelProvider2 != null) { adapter2.setLabelProvider(propsalLabelProvider2); } adapter2.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); Composite emailComposite2 = new Composite(composite, SWT.NONE); emailComposite2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); GridLayout emailLayout2 = new GridLayout(); emailLayout2.marginWidth = 0; emailLayout2.marginHeight = 0; emailLayout2.horizontalSpacing = 2; emailLayout2.numColumns = 4; emailComposite2.setLayout(emailLayout2); Button e2button0 = new Button(emailComposite2, SWT.CHECK); e2button0.setText("owner"); Button e2button1 = new Button(emailComposite2, SWT.CHECK); e2button1.setText("reporter"); Button e2button2 = new Button(emailComposite2, SWT.CHECK); e2button2.setText("cc"); Button e2button3 = new Button(emailComposite2, SWT.CHECK); e2button3.setText("commenter"); emailButtons2 = new Button[] { e2button0, e2button1, e2button2, e2button3 }; // operation combo emailOperation2 = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); emailOperation2.setItems(emailOperationText); emailOperation2.setText(emailOperationText[0]); emailOperation2.select(0); ///// Label labelKeywords = new Label(composite, SWT.NONE); labelKeywords.setText("&Keywords:"); labelKeywords.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT)); //labelKeywords.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Composite keywordsComposite = new Composite(composite, SWT.NONE); keywordsComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1)); GridLayout keywordsLayout = new GridLayout(); keywordsLayout.marginWidth = 0; keywordsLayout.marginHeight = 0; keywordsLayout.numColumns = 3; keywordsComposite.setLayout(keywordsLayout); keywordsOperation = new Combo(keywordsComposite, SWT.READ_ONLY); keywordsOperation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); keywordsOperation.setItems(keywordOperationText); keywordsOperation.setText(keywordOperationText[0]); keywordsOperation.select(0); keywords = new Combo(keywordsComposite, SWT.NONE); keywords.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); keywords.addModifyListener(new ModifyListenerImplementation()); keywords.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(keywords, keywordsOperation, previousKeywords); } }); Button keywordsSelectButton = new Button(keywordsComposite, SWT.NONE); keywordsSelectButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (repositoryConfiguration != null) { KeywordsDialog dialog = new KeywordsDialog(getShell(), keywords.getText(), // repositoryConfiguration.getKeywords()); if (dialog.open() == Window.OK) { keywords.setText(dialog.getSelectedKeywordsString()); } } } }); keywordsSelectButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); keywordsSelectButton.setText("Select..."); SashForm sashForm = new SashForm(control, SWT.VERTICAL); sashForm.setLayout(sashFormLayout); final GridData gd_sashForm = new GridData(SWT.FILL, SWT.FILL, true, true); gd_sashForm.widthHint = 500; sashForm.setLayoutData(gd_sashForm); GridLayout topLayout = new GridLayout(); topLayout.numColumns = 4; SashForm topForm = new SashForm(sashForm, SWT.NONE); GridData topLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1); topLayoutData.widthHint = 500; topForm.setLayoutData(topLayoutData); topForm.setLayout(topLayout); GridLayout productLayout = new GridLayout(); productLayout.marginWidth = 0; productLayout.marginHeight = 0; productLayout.horizontalSpacing = 0; Composite productComposite = new Composite(topForm, SWT.NONE); productComposite.setLayout(productLayout); Label productLabel = new Label(productComposite, SWT.LEFT); productLabel.setText("&Product:"); GridData productLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); productLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; product = new List(productComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); product.setLayoutData(productLayoutData); product.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (product.getSelectionIndex() != -1) { String[] selectedProducts = product.getSelection(); updateAttributesFromConfiguration(selectedProducts); } else { updateAttributesFromConfiguration(null); } if (restoring) { restoring = false; restoreWidgetValues(); } setPageComplete(isPageComplete()); } }); GridLayout componentLayout = new GridLayout(); componentLayout.marginWidth = 0; componentLayout.marginHeight = 0; componentLayout.horizontalSpacing = 0; Composite componentComposite = new Composite(topForm, SWT.NONE); componentComposite.setLayout(componentLayout); Label componentLabel = new Label(componentComposite, SWT.LEFT); componentLabel.setText("Compo&nent:"); component = new List(componentComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData componentLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); componentLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; component.setLayoutData(componentLayoutData); component.addSelectionListener(updateActionSelectionAdapter); Composite versionComposite = new Composite(topForm, SWT.NONE); GridLayout versionLayout = new GridLayout(); versionLayout.marginWidth = 0; versionLayout.marginHeight = 0; versionLayout.horizontalSpacing = 0; versionComposite.setLayout(versionLayout); Label versionLabel = new Label(versionComposite, SWT.LEFT); versionLabel.setText("Vers&ion:"); version = new List(versionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData versionLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); versionLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; version.setLayoutData(versionLayoutData); version.addSelectionListener(updateActionSelectionAdapter); Composite milestoneComposite = new Composite(topForm, SWT.NONE); GridLayout milestoneLayout = new GridLayout(); milestoneLayout.marginWidth = 0; milestoneLayout.marginHeight = 0; milestoneLayout.horizontalSpacing = 0; milestoneComposite.setLayout(milestoneLayout); Label milestoneLabel = new Label(milestoneComposite, SWT.LEFT); milestoneLabel.setText("&Milestone:"); target = new List(milestoneComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData targetLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); targetLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; target.setLayoutData(targetLayoutData); target.addSelectionListener(updateActionSelectionAdapter); SashForm bottomForm = new SashForm(sashForm, SWT.NONE); GridLayout bottomLayout = new GridLayout(); bottomLayout.numColumns = 6; bottomForm.setLayout(bottomLayout); GridData bottomLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1); bottomLayoutData.heightHint = 119; bottomLayoutData.widthHint = 400; bottomForm.setLayoutData(bottomLayoutData); Composite statusComposite = new Composite(bottomForm, SWT.NONE); GridLayout statusLayout = new GridLayout(); statusLayout.marginTop = 7; statusLayout.marginWidth = 0; statusLayout.horizontalSpacing = 0; statusLayout.marginHeight = 0; statusComposite.setLayout(statusLayout); Label statusLabel = new Label(statusComposite, SWT.LEFT); statusLabel.setText("Stat&us:"); status = new List(statusComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_status = new GridData(SWT.FILL, SWT.FILL, true, true); gd_status.heightHint = 60; status.setLayoutData(gd_status); status.addSelectionListener(updateActionSelectionAdapter); Composite resolutionComposite = new Composite(bottomForm, SWT.NONE); GridLayout resolutionLayout = new GridLayout(); resolutionLayout.marginTop = 7; resolutionLayout.marginWidth = 0; resolutionLayout.marginHeight = 0; resolutionLayout.horizontalSpacing = 0; resolutionComposite.setLayout(resolutionLayout); Label resolutionLabel = new Label(resolutionComposite, SWT.LEFT); resolutionLabel.setText("&Resolution:"); resolution = new List(resolutionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_resolution = new GridData(SWT.FILL, SWT.FILL, true, true); gd_resolution.heightHint = 60; resolution.setLayoutData(gd_resolution); resolution.addSelectionListener(updateActionSelectionAdapter); Composite priorityComposite = new Composite(bottomForm, SWT.NONE); GridLayout priorityLayout = new GridLayout(); priorityLayout.marginTop = 7; priorityLayout.marginWidth = 0; priorityLayout.marginHeight = 0; priorityLayout.horizontalSpacing = 0; priorityComposite.setLayout(priorityLayout); Label priorityLabel = new Label(priorityComposite, SWT.LEFT); priorityLabel.setText("Priori&ty:"); priority = new List(priorityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_priority = new GridData(SWT.FILL, SWT.FILL, true, true); gd_priority.heightHint = 60; priority.setLayoutData(gd_priority); priority.addSelectionListener(updateActionSelectionAdapter); Composite severityComposite = new Composite(bottomForm, SWT.NONE); GridLayout severityLayout = new GridLayout(); severityLayout.marginTop = 7; severityLayout.marginWidth = 0; severityLayout.marginHeight = 0; severityLayout.horizontalSpacing = 0; severityComposite.setLayout(severityLayout); Label severityLabel = new Label(severityComposite, SWT.LEFT); severityLabel.setText("Se&verity:"); severity = new List(severityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_severity = new GridData(SWT.FILL, SWT.FILL, true, true); gd_severity.heightHint = 60; severity.setLayoutData(gd_severity); severity.addSelectionListener(updateActionSelectionAdapter); Composite hardwareComposite = new Composite(bottomForm, SWT.NONE); GridLayout hardwareLayout = new GridLayout(); hardwareLayout.marginTop = 7; hardwareLayout.marginWidth = 0; hardwareLayout.marginHeight = 0; hardwareLayout.horizontalSpacing = 0; hardwareComposite.setLayout(hardwareLayout); Label hardwareLabel = new Label(hardwareComposite, SWT.LEFT); hardwareLabel.setText("Hard&ware:"); hardware = new List(hardwareComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_hardware = new GridData(SWT.FILL, SWT.FILL, true, true); gd_hardware.heightHint = 60; hardware.setLayoutData(gd_hardware); hardware.addSelectionListener(updateActionSelectionAdapter); Composite osComposite = new Composite(bottomForm, SWT.NONE); GridLayout osLayout = new GridLayout(); osLayout.marginTop = 7; osLayout.marginWidth = 0; osLayout.marginHeight = 0; osLayout.horizontalSpacing = 0; osComposite.setLayout(osLayout); Label osLabel = new Label(osComposite, SWT.LEFT); osLabel.setText("&Operating System:"); os = new List(osComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_os = new GridData(SWT.FILL, SWT.FILL, true, true); gd_os.heightHint = 60; os.setLayoutData(gd_os); os.addSelectionListener(updateActionSelectionAdapter); bottomForm.setWeights(new int[] { 88, 90, 50, 77, 88, 85 }); }
protected void createOptionsGroup(Composite control) { GridLayout sashFormLayout = new GridLayout(); sashFormLayout.numColumns = 4; sashFormLayout.marginHeight = 5; sashFormLayout.marginWidth = 5; sashFormLayout.horizontalSpacing = 5; final Composite composite = new Composite(control, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); final GridLayout gridLayout = new GridLayout(); gridLayout.marginBottom = 8; gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; gridLayout.numColumns = 4; composite.setLayout(gridLayout); if (!inSearchContainer()) { final Label queryTitleLabel = new Label(composite, SWT.NONE); queryTitleLabel.setText("&Query Title:"); Text queryTitle = new Text(composite, SWT.BORDER); queryTitle.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); if (originalQuery != null) { queryTitle.setText(originalQuery.getSummary()); } queryTitle.addModifyListener(new ModifyListenerImplementation()); title = queryTitle; title.setFocus(); } // Info text Label labelSummary = new Label(composite, SWT.LEFT); labelSummary.setText("Summar&y:"); labelSummary.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT)); //labelSummary.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // Pattern combo summaryPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); summaryPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); summaryPattern.addModifyListener(new ModifyListenerImplementation()); summaryPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(summaryPattern, summaryOperation, previousSummaryPatterns); } }); summaryOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); summaryOperation.setItems(patternOperationText); summaryOperation.setText(patternOperationText[0]); summaryOperation.select(0); // Info text Label labelComment = new Label(composite, SWT.LEFT); labelComment.setText("&Comment:"); //labelComment.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // Comment pattern combo commentPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); commentPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1)); commentPattern.addModifyListener(new ModifyListenerImplementation()); commentPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(commentPattern, commentOperation, previousCommentPatterns); } }); commentOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); commentOperation.setItems(patternOperationText); commentOperation.setText(patternOperationText[0]); commentOperation.select(0); Label labelEmail = new Label(composite, SWT.LEFT); labelEmail.setText("&Email:"); //labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // pattern combo emailPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); emailPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); emailPattern.addModifyListener(new ModifyListenerImplementation()); emailPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(emailPattern, emailOperation, previousEmailPatterns); } }); ContentAssistCommandAdapter adapter = applyContentAssist(emailPattern, createContentProposalProvider()); ILabelProvider propsalLabelProvider = createProposalLabelProvider(); if (propsalLabelProvider != null) { adapter.setLabelProvider(propsalLabelProvider); } adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); Composite emailComposite = new Composite(composite, SWT.NONE); emailComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); GridLayout emailLayout = new GridLayout(); emailLayout.marginWidth = 0; emailLayout.marginHeight = 0; emailLayout.horizontalSpacing = 2; emailLayout.numColumns = 4; emailComposite.setLayout(emailLayout); Button button0 = new Button(emailComposite, SWT.CHECK); button0.setText("owner"); Button button1 = new Button(emailComposite, SWT.CHECK); button1.setText("reporter"); Button button2 = new Button(emailComposite, SWT.CHECK); button2.setText("cc"); Button button3 = new Button(emailComposite, SWT.CHECK); button3.setText("commenter"); emailButtons = new Button[] { button0, button1, button2, button3 }; // operation combo emailOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); emailOperation.setItems(emailOperationText); emailOperation.setText(emailOperationText[0]); emailOperation.select(0); // Email2 Label labelEmail2 = new Label(composite, SWT.LEFT); labelEmail2.setText("Email &2:"); //labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // pattern combo emailPattern2 = new Combo(composite, SWT.SINGLE | SWT.BORDER); emailPattern2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); emailPattern2.addModifyListener(new ModifyListenerImplementation()); emailPattern2.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(emailPattern2, emailOperation2, previousEmailPatterns2); } }); ContentAssistCommandAdapter adapter2 = applyContentAssist(emailPattern2, createContentProposalProvider()); ILabelProvider propsalLabelProvider2 = createProposalLabelProvider(); if (propsalLabelProvider2 != null) { adapter2.setLabelProvider(propsalLabelProvider2); } adapter2.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); Composite emailComposite2 = new Composite(composite, SWT.NONE); emailComposite2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); GridLayout emailLayout2 = new GridLayout(); emailLayout2.marginWidth = 0; emailLayout2.marginHeight = 0; emailLayout2.horizontalSpacing = 2; emailLayout2.numColumns = 4; emailComposite2.setLayout(emailLayout2); Button e2button0 = new Button(emailComposite2, SWT.CHECK); e2button0.setText("owner"); Button e2button1 = new Button(emailComposite2, SWT.CHECK); e2button1.setText("reporter"); Button e2button2 = new Button(emailComposite2, SWT.CHECK); e2button2.setText("cc"); Button e2button3 = new Button(emailComposite2, SWT.CHECK); e2button3.setText("commenter"); emailButtons2 = new Button[] { e2button0, e2button1, e2button2, e2button3 }; // operation combo emailOperation2 = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); emailOperation2.setItems(emailOperationText); emailOperation2.setText(emailOperationText[0]); emailOperation2.select(0); ///// Label labelKeywords = new Label(composite, SWT.NONE); labelKeywords.setText("&Keywords:"); labelKeywords.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT)); //labelKeywords.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Composite keywordsComposite = new Composite(composite, SWT.NONE); keywordsComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1)); GridLayout keywordsLayout = new GridLayout(); keywordsLayout.marginWidth = 0; keywordsLayout.marginHeight = 0; keywordsLayout.numColumns = 3; keywordsComposite.setLayout(keywordsLayout); keywordsOperation = new Combo(keywordsComposite, SWT.READ_ONLY); keywordsOperation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); keywordsOperation.setItems(keywordOperationText); keywordsOperation.setText(keywordOperationText[0]); keywordsOperation.select(0); keywords = new Combo(keywordsComposite, SWT.NONE); keywords.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); keywords.addModifyListener(new ModifyListenerImplementation()); keywords.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(keywords, keywordsOperation, previousKeywords); } }); Button keywordsSelectButton = new Button(keywordsComposite, SWT.NONE); keywordsSelectButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (repositoryConfiguration != null) { KeywordsDialog dialog = new KeywordsDialog(getShell(), keywords.getText(), // repositoryConfiguration.getKeywords()); if (dialog.open() == Window.OK) { keywords.setText(dialog.getSelectedKeywordsString()); } } } }); keywordsSelectButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); keywordsSelectButton.setText("Select..."); SashForm sashForm = new SashForm(control, SWT.VERTICAL); sashForm.setLayout(sashFormLayout); final GridData gd_sashForm = new GridData(SWT.FILL, SWT.FILL, true, true); gd_sashForm.widthHint = 500; sashForm.setLayoutData(gd_sashForm); GridLayout topLayout = new GridLayout(); topLayout.numColumns = 4; SashForm topForm = new SashForm(sashForm, SWT.NONE); GridData topLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1); topLayoutData.widthHint = 500; topForm.setLayoutData(topLayoutData); topForm.setLayout(topLayout); GridLayout productLayout = new GridLayout(); productLayout.marginWidth = 0; productLayout.marginHeight = 0; productLayout.horizontalSpacing = 0; Composite productComposite = new Composite(topForm, SWT.NONE); productComposite.setLayout(productLayout); Label productLabel = new Label(productComposite, SWT.LEFT); productLabel.setText("&Product:"); GridData productLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); productLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; product = new List(productComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); product.setLayoutData(productLayoutData); product.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (product.getSelectionIndex() != -1) { String[] selectedProducts = product.getSelection(); updateAttributesFromConfiguration(selectedProducts); } else { updateAttributesFromConfiguration(null); } if (restoring) { restoring = false; restoreWidgetValues(); } setPageComplete(isPageComplete()); } }); GridLayout componentLayout = new GridLayout(); componentLayout.marginWidth = 0; componentLayout.marginHeight = 0; componentLayout.horizontalSpacing = 0; Composite componentComposite = new Composite(topForm, SWT.NONE); componentComposite.setLayout(componentLayout); Label componentLabel = new Label(componentComposite, SWT.LEFT); componentLabel.setText("Compo&nent:"); component = new List(componentComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData componentLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); componentLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; component.setLayoutData(componentLayoutData); component.addSelectionListener(updateActionSelectionAdapter); Composite versionComposite = new Composite(topForm, SWT.NONE); GridLayout versionLayout = new GridLayout(); versionLayout.marginWidth = 0; versionLayout.marginHeight = 0; versionLayout.horizontalSpacing = 0; versionComposite.setLayout(versionLayout); Label versionLabel = new Label(versionComposite, SWT.LEFT); versionLabel.setText("Vers&ion:"); version = new List(versionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData versionLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); versionLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; version.setLayoutData(versionLayoutData); version.addSelectionListener(updateActionSelectionAdapter); Composite milestoneComposite = new Composite(topForm, SWT.NONE); GridLayout milestoneLayout = new GridLayout(); milestoneLayout.marginWidth = 0; milestoneLayout.marginHeight = 0; milestoneLayout.horizontalSpacing = 0; milestoneComposite.setLayout(milestoneLayout); Label milestoneLabel = new Label(milestoneComposite, SWT.LEFT); milestoneLabel.setText("&Milestone:"); target = new List(milestoneComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData targetLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); targetLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; target.setLayoutData(targetLayoutData); target.addSelectionListener(updateActionSelectionAdapter); SashForm bottomForm = new SashForm(sashForm, SWT.NONE); GridLayout bottomLayout = new GridLayout(); bottomLayout.numColumns = 6; bottomForm.setLayout(bottomLayout); GridData bottomLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1); bottomLayoutData.heightHint = 119; bottomLayoutData.widthHint = 400; bottomForm.setLayoutData(bottomLayoutData); Composite statusComposite = new Composite(bottomForm, SWT.NONE); GridLayout statusLayout = new GridLayout(); statusLayout.marginTop = 7; statusLayout.marginWidth = 0; statusLayout.horizontalSpacing = 0; statusLayout.marginHeight = 0; statusComposite.setLayout(statusLayout); Label statusLabel = new Label(statusComposite, SWT.LEFT); statusLabel.setText("Stat&us:"); status = new List(statusComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_status = new GridData(SWT.FILL, SWT.FILL, true, true); gd_status.heightHint = 60; status.setLayoutData(gd_status); status.addSelectionListener(updateActionSelectionAdapter); Composite resolutionComposite = new Composite(bottomForm, SWT.NONE); GridLayout resolutionLayout = new GridLayout(); resolutionLayout.marginTop = 7; resolutionLayout.marginWidth = 0; resolutionLayout.marginHeight = 0; resolutionLayout.horizontalSpacing = 0; resolutionComposite.setLayout(resolutionLayout); Label resolutionLabel = new Label(resolutionComposite, SWT.LEFT); resolutionLabel.setText("&Resolution:"); resolution = new List(resolutionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_resolution = new GridData(SWT.FILL, SWT.FILL, true, true); gd_resolution.heightHint = 60; resolution.setLayoutData(gd_resolution); resolution.addSelectionListener(updateActionSelectionAdapter); Composite priorityComposite = new Composite(bottomForm, SWT.NONE); GridLayout priorityLayout = new GridLayout(); priorityLayout.marginTop = 7; priorityLayout.marginWidth = 0; priorityLayout.marginHeight = 0; priorityLayout.horizontalSpacing = 0; priorityComposite.setLayout(priorityLayout); Label priorityLabel = new Label(priorityComposite, SWT.LEFT); priorityLabel.setText("Priori&ty:"); priority = new List(priorityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_priority = new GridData(SWT.FILL, SWT.FILL, true, true); gd_priority.heightHint = 60; priority.setLayoutData(gd_priority); priority.addSelectionListener(updateActionSelectionAdapter); Composite severityComposite = new Composite(bottomForm, SWT.NONE); GridLayout severityLayout = new GridLayout(); severityLayout.marginTop = 7; severityLayout.marginWidth = 0; severityLayout.marginHeight = 0; severityLayout.horizontalSpacing = 0; severityComposite.setLayout(severityLayout); Label severityLabel = new Label(severityComposite, SWT.LEFT); severityLabel.setText("Se&verity:"); severity = new List(severityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_severity = new GridData(SWT.FILL, SWT.FILL, true, true); gd_severity.heightHint = 60; severity.setLayoutData(gd_severity); severity.addSelectionListener(updateActionSelectionAdapter); Composite hardwareComposite = new Composite(bottomForm, SWT.NONE); GridLayout hardwareLayout = new GridLayout(); hardwareLayout.marginTop = 7; hardwareLayout.marginWidth = 0; hardwareLayout.marginHeight = 0; hardwareLayout.horizontalSpacing = 0; hardwareComposite.setLayout(hardwareLayout); Label hardwareLabel = new Label(hardwareComposite, SWT.LEFT); hardwareLabel.setText("Hard&ware:"); hardware = new List(hardwareComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_hardware = new GridData(SWT.FILL, SWT.FILL, true, true); gd_hardware.heightHint = 60; hardware.setLayoutData(gd_hardware); hardware.addSelectionListener(updateActionSelectionAdapter); Composite osComposite = new Composite(bottomForm, SWT.NONE); GridLayout osLayout = new GridLayout(); osLayout.marginTop = 7; osLayout.marginWidth = 0; osLayout.marginHeight = 0; osLayout.horizontalSpacing = 0; osComposite.setLayout(osLayout); Label osLabel = new Label(osComposite, SWT.LEFT); osLabel.setText("&Operating System:"); os = new List(osComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_os = new GridData(SWT.FILL, SWT.FILL, true, true); gd_os.heightHint = 60; os.setLayoutData(gd_os); os.addSelectionListener(updateActionSelectionAdapter); bottomForm.setWeights(new int[] { 88, 90, 50, 77, 88, 85 }); }
diff --git a/src/org/biojava/bio/seq/db/biosql/HypersonicDBHelper.java b/src/org/biojava/bio/seq/db/biosql/HypersonicDBHelper.java index 3a5af9a5d..db1150b35 100644 --- a/src/org/biojava/bio/seq/db/biosql/HypersonicDBHelper.java +++ b/src/org/biojava/bio/seq/db/biosql/HypersonicDBHelper.java @@ -1,99 +1,99 @@ /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.bio.seq.db.biosql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import org.biojava.bio.BioRuntimeException; //import org.biojava.utils.JDBCConnectionPool; /** * This is a <code>DBHelper</code> that provides support for the * Hypersonic RDBMS. See the <a href="http://hsqldb.sourceforge.net/">HSQLDB home page</a> * * @author Len Trigg */ public class HypersonicDBHelper extends DBHelper { // Inherit docs public int getInsertID(Connection conn, String table, String columnName) throws SQLException { Statement st = null; ResultSet rs = null; try { st = conn.createStatement(); rs = st.executeQuery("call identity()"); int id = -1; if (rs.next()) { id = rs.getInt(1); } if (id < 0) { throw new SQLException("Couldn't get last insert id"); } return id; } finally { if (rs != null) try { rs.close(); } catch (SQLException se) { } if (st != null) try { st.close(); } catch (SQLException se) { } } } // Inherit docs public boolean containsTable(DataSource ds, String tablename) { if (ds == null) { throw new NullPointerException("Require a datasource."); } if ((tablename == null) || (tablename.length() == 0)) { throw new IllegalArgumentException("Invalid table name given"); } //System.err.println("Checking for table existence: " + tablename); Connection conn = null; try { boolean present; conn = ds.getConnection(); PreparedStatement ps = null; try { - ps = conn.prepareStatement("select top 0 * from " + tablename); + ps = conn.prepareStatement("select top 1 * from " + tablename); ps.executeQuery(); present = true; } catch (SQLException ex) { //System.err.println("Table " + tablename + " does not exist."); present = false; } finally { if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } } return present; } catch (SQLException ex) { throw new BioRuntimeException(ex); } } }
true
true
public boolean containsTable(DataSource ds, String tablename) { if (ds == null) { throw new NullPointerException("Require a datasource."); } if ((tablename == null) || (tablename.length() == 0)) { throw new IllegalArgumentException("Invalid table name given"); } //System.err.println("Checking for table existence: " + tablename); Connection conn = null; try { boolean present; conn = ds.getConnection(); PreparedStatement ps = null; try { ps = conn.prepareStatement("select top 0 * from " + tablename); ps.executeQuery(); present = true; } catch (SQLException ex) { //System.err.println("Table " + tablename + " does not exist."); present = false; } finally { if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } } return present; } catch (SQLException ex) { throw new BioRuntimeException(ex); } }
public boolean containsTable(DataSource ds, String tablename) { if (ds == null) { throw new NullPointerException("Require a datasource."); } if ((tablename == null) || (tablename.length() == 0)) { throw new IllegalArgumentException("Invalid table name given"); } //System.err.println("Checking for table existence: " + tablename); Connection conn = null; try { boolean present; conn = ds.getConnection(); PreparedStatement ps = null; try { ps = conn.prepareStatement("select top 1 * from " + tablename); ps.executeQuery(); present = true; } catch (SQLException ex) { //System.err.println("Table " + tablename + " does not exist."); present = false; } finally { if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } } return present; } catch (SQLException ex) { throw new BioRuntimeException(ex); } }
diff --git a/src/main/java/be/Balor/Manager/Commands/Items/Kit.java b/src/main/java/be/Balor/Manager/Commands/Items/Kit.java index 7af999f3..4399f092 100644 --- a/src/main/java/be/Balor/Manager/Commands/Items/Kit.java +++ b/src/main/java/be/Balor/Manager/Commands/Items/Kit.java @@ -1,101 +1,102 @@ /************************************************************************ * This file is part of AdminCmd. * * AdminCmd is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AdminCmd is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AdminCmd. If not, see <http://www.gnu.org/licenses/>. ************************************************************************/ package be.Balor.Manager.Commands.Items; import java.util.ArrayList; import java.util.HashMap; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import be.Balor.Manager.ACCommand; import be.Balor.Tools.Utils; import be.Balor.bukkit.AdminCmd.ACHelper; /** * @author Balor (aka Antoine Aflalo) * */ public class Kit extends ACCommand { /** * */ public Kit() { permNode = "admincmd.item.add"; cmdName = "bal_kit"; other = true; } /* * (non-Javadoc) * * @see be.Balor.Manager.ACCommand#execute(org.bukkit.command.CommandSender, * java.lang.String[]) */ @Override public void execute(CommandSender sender, String... args) { // which material? Player target; if (args.length == 0) { Utils.sI18n(sender, "kitList", "list", ACHelper.getInstance().getKitList()); return; } ArrayList<ItemStack> items = ACHelper.getInstance().getKit(args[0]); - if(items==null) + if(items.isEmpty()) { Utils.sI18n(sender, "kitNotFound", "kit", args[0]); return; } target = Utils.getUser(sender, args, permNode, 1, true); if (target == null) { return; } HashMap<String, String> replace = new HashMap<String, String>(); + replace.put("kit", args[0]); if (Utils.isPlayer(sender, false)) { if (!target.equals(sender)) { replace.put("sender", ((Player) sender).getName()); Utils.sI18n(target, "kitOtherPlayer", replace); replace.remove("sender"); replace.put("target", target.getName()); Utils.sI18n(sender, "kitCommandSender", replace); } else Utils.sI18n(sender, "kitYourself", replace); } else { replace.put("sender", "Server Admin"); Utils.sI18n(target, "kitOtherPlayer", replace); replace.remove("sender"); replace.put("target", target.getName()); Utils.sI18n(sender, "kitCommandSender", replace); } target.getInventory().addItem(items.toArray(new ItemStack[] {})); } /* * (non-Javadoc) * * @see be.Balor.Manager.ACCommand#argsCheck(java.lang.String[]) */ @Override public boolean argsCheck(String... args) { return args != null; } }
false
true
public void execute(CommandSender sender, String... args) { // which material? Player target; if (args.length == 0) { Utils.sI18n(sender, "kitList", "list", ACHelper.getInstance().getKitList()); return; } ArrayList<ItemStack> items = ACHelper.getInstance().getKit(args[0]); if(items==null) { Utils.sI18n(sender, "kitNotFound", "kit", args[0]); return; } target = Utils.getUser(sender, args, permNode, 1, true); if (target == null) { return; } HashMap<String, String> replace = new HashMap<String, String>(); if (Utils.isPlayer(sender, false)) { if (!target.equals(sender)) { replace.put("sender", ((Player) sender).getName()); Utils.sI18n(target, "kitOtherPlayer", replace); replace.remove("sender"); replace.put("target", target.getName()); Utils.sI18n(sender, "kitCommandSender", replace); } else Utils.sI18n(sender, "kitYourself", replace); } else { replace.put("sender", "Server Admin"); Utils.sI18n(target, "kitOtherPlayer", replace); replace.remove("sender"); replace.put("target", target.getName()); Utils.sI18n(sender, "kitCommandSender", replace); } target.getInventory().addItem(items.toArray(new ItemStack[] {})); }
public void execute(CommandSender sender, String... args) { // which material? Player target; if (args.length == 0) { Utils.sI18n(sender, "kitList", "list", ACHelper.getInstance().getKitList()); return; } ArrayList<ItemStack> items = ACHelper.getInstance().getKit(args[0]); if(items.isEmpty()) { Utils.sI18n(sender, "kitNotFound", "kit", args[0]); return; } target = Utils.getUser(sender, args, permNode, 1, true); if (target == null) { return; } HashMap<String, String> replace = new HashMap<String, String>(); replace.put("kit", args[0]); if (Utils.isPlayer(sender, false)) { if (!target.equals(sender)) { replace.put("sender", ((Player) sender).getName()); Utils.sI18n(target, "kitOtherPlayer", replace); replace.remove("sender"); replace.put("target", target.getName()); Utils.sI18n(sender, "kitCommandSender", replace); } else Utils.sI18n(sender, "kitYourself", replace); } else { replace.put("sender", "Server Admin"); Utils.sI18n(target, "kitOtherPlayer", replace); replace.remove("sender"); replace.put("target", target.getName()); Utils.sI18n(sender, "kitCommandSender", replace); } target.getInventory().addItem(items.toArray(new ItemStack[] {})); }
diff --git a/restcomm.rcml/src/main/java/org/mobicents/servlet/sip/restcomm/interpreter/tagstrategy/GatherTagStrategy.java b/restcomm.rcml/src/main/java/org/mobicents/servlet/sip/restcomm/interpreter/tagstrategy/GatherTagStrategy.java index ee7e0b96f..530d77b6a 100644 --- a/restcomm.rcml/src/main/java/org/mobicents/servlet/sip/restcomm/interpreter/tagstrategy/GatherTagStrategy.java +++ b/restcomm.rcml/src/main/java/org/mobicents/servlet/sip/restcomm/interpreter/tagstrategy/GatherTagStrategy.java @@ -1,242 +1,242 @@ /* * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.servlet.sip.restcomm.interpreter.tagstrategy; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.apache.log4j.Logger; import org.mobicents.servlet.sip.restcomm.annotations.concurrency.NotThreadSafe; import org.mobicents.servlet.sip.restcomm.interpreter.TagStrategyException; import org.mobicents.servlet.sip.restcomm.entities.Notification; import org.mobicents.servlet.sip.restcomm.interpreter.RcmlInterpreter; import org.mobicents.servlet.sip.restcomm.interpreter.RcmlInterpreterContext; import org.mobicents.servlet.sip.restcomm.media.api.Call; import org.mobicents.servlet.sip.restcomm.media.api.CallException; import org.mobicents.servlet.sip.restcomm.util.StringUtils; import org.mobicents.servlet.sip.restcomm.xml.Attribute; import org.mobicents.servlet.sip.restcomm.xml.Tag; import org.mobicents.servlet.sip.restcomm.xml.rcml.Pause; import org.mobicents.servlet.sip.restcomm.xml.rcml.Play; import org.mobicents.servlet.sip.restcomm.xml.rcml.RcmlTag; import org.mobicents.servlet.sip.restcomm.xml.rcml.Say; import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.NumDigits; /** * @author quintana.thomas@gmail.com (Thomas Quintana) */ @NotThreadSafe public final class GatherTagStrategy extends RcmlTagStrategy { private static final Logger logger = Logger.getLogger(GatherTagStrategy.class); private static final Pattern finishOnKeyPattern = Pattern.compile("[\\*#0-9]{1}"); private URI action; private String method; private int timeout; private String finishOnKey; private int numDigits; public GatherTagStrategy() { super(); } @Override public void execute(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { try { // Collect some digits. final List<URI> announcements = getAnnouncements(interpreter, context, tag); final Call call = context.getCall(); try { if(Call.Status.IN_PROGRESS == call.getStatus()) { call.playAndCollect(announcements, numDigits, 1,timeout, timeout, finishOnKey); } } catch(final CallException exception) { exception.printStackTrace(); } // Redirect to action URI.; final String digits = call.getDigits(); - if(digits.length() > 0) { + if(digits != null && digits.length() > 0) { final List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("Digits", digits)); interpreter.load(action, method, parameters); interpreter.redirect(); } } catch(final Exception exception) { interpreter.failed(); interpreter.notify(context, Notification.ERROR, 12400); logger.error(exception); throw new TagStrategyException(exception); } } private List<URI> getAnnouncements(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { final List<Tag> children = tag.getChildren(); final List<URI> announcements = new ArrayList<URI>(); for(final Tag child : children) { final String name = child.getName(); if(Say.NAME.equals(name)) { announcements.addAll(getSay(interpreter, context, (RcmlTag)child)); } else if(Play.NAME.equals(name)) { announcements.addAll(getPlay(interpreter, context, (RcmlTag)child)); } else if(Pause.NAME.equals(name)) { announcements.addAll(getPause(interpreter, context, (RcmlTag)child)); } tag.setHasBeenVisited(true); } return announcements; } private int getNumDigits(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) { final Attribute attribute = tag.getAttribute(NumDigits.NAME); if(attribute == null) { return Short.MAX_VALUE; } final String value = attribute.getValue(); if(StringUtils.isPositiveInteger(value)) { final int result = Integer.parseInt(value); if(result >= 1) { return result; } } interpreter.notify(context, Notification.WARNING, 13314); return Short.MAX_VALUE; } private List<URI> getPause(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) { int length = getLength(interpreter, context, tag); if(length == -1) { length = 1; } return pause(length); } private List<URI> getPlay(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { int loop = getLoop(interpreter, context, tag); if(loop == -1) { loop = 1; } final URI uri = getUri(interpreter, context, tag); if(uri == null) { interpreter.failed(); interpreter.notify(context, Notification.ERROR, 13325); throw new TagStrategyException("There is no resource to play."); } final List<URI> announcements = new ArrayList<URI>(); if(uri != null) { for(int counter = 0; counter < loop; counter++) { announcements.add(uri); } } return announcements; } private List<URI> getSay(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) { String gender = getGender(interpreter, context, tag); if(gender == null) { interpreter.notify(context, Notification.WARNING, 13321); gender = "man"; } String language = getLanguage(interpreter, context, tag); if(language == null) { language = "en"; } int loop = getLoop(interpreter, context, tag); if(loop == -1) { loop = 1; } final String text = tag.getText(); if(text == null || text.isEmpty()) { interpreter.notify(context, Notification.WARNING, 13322); } final List<URI> announcements = new ArrayList<URI>(); if(text != null) { final URI uri = say(gender, language, text); for(int counter = 0; counter < loop; counter++) { announcements.add(uri); } } return announcements; } @Override public void initialize(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { super.initialize(interpreter, context, tag); initAction(interpreter, context, tag); initMethod(interpreter, context, tag); initTimeout(interpreter, context, tag); initFinishOnKey(interpreter, context, tag); numDigits = getNumDigits(interpreter, context, tag); } private void initAction(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { try { action = getAction(interpreter, context, tag); if(action == null) { action = interpreter.getCurrentResourceUri(); } } catch(final IllegalArgumentException exception) { interpreter.failed(); interpreter.notify(context, Notification.ERROR, 11100); throw new TagStrategyException(exception); } } private void initMethod(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { method = getMethod(interpreter, context, tag); if(!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) { interpreter.notify(context, Notification.WARNING, 13312); method = "POST"; } } private void initTimeout(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { final Object object = getTimeout(interpreter, context, tag); if(object == null) { timeout = 5; } else { timeout = (Integer)object; if(timeout == -1) { interpreter.notify(context, Notification.WARNING, 13313); timeout = 5; } } } private void initFinishOnKey(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { finishOnKey = getFinishOnKey(interpreter, context, tag); if(finishOnKey == null) { finishOnKey = "#"; } else { if(!finishOnKeyPattern.matcher(finishOnKey).matches()) { interpreter.notify(context, Notification.WARNING, 13310); finishOnKey = "#"; } } } }
true
true
@Override public void execute(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { try { // Collect some digits. final List<URI> announcements = getAnnouncements(interpreter, context, tag); final Call call = context.getCall(); try { if(Call.Status.IN_PROGRESS == call.getStatus()) { call.playAndCollect(announcements, numDigits, 1,timeout, timeout, finishOnKey); } } catch(final CallException exception) { exception.printStackTrace(); } // Redirect to action URI.; final String digits = call.getDigits(); if(digits.length() > 0) { final List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("Digits", digits)); interpreter.load(action, method, parameters); interpreter.redirect(); } } catch(final Exception exception) { interpreter.failed(); interpreter.notify(context, Notification.ERROR, 12400); logger.error(exception); throw new TagStrategyException(exception); } }
@Override public void execute(final RcmlInterpreter interpreter, final RcmlInterpreterContext context, final RcmlTag tag) throws TagStrategyException { try { // Collect some digits. final List<URI> announcements = getAnnouncements(interpreter, context, tag); final Call call = context.getCall(); try { if(Call.Status.IN_PROGRESS == call.getStatus()) { call.playAndCollect(announcements, numDigits, 1,timeout, timeout, finishOnKey); } } catch(final CallException exception) { exception.printStackTrace(); } // Redirect to action URI.; final String digits = call.getDigits(); if(digits != null && digits.length() > 0) { final List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("Digits", digits)); interpreter.load(action, method, parameters); interpreter.redirect(); } } catch(final Exception exception) { interpreter.failed(); interpreter.notify(context, Notification.ERROR, 12400); logger.error(exception); throw new TagStrategyException(exception); } }
diff --git a/serenity-app/src/main/java/us/nineworlds/serenity/core/services/MusicTrackRetrievalIntentService.java b/serenity-app/src/main/java/us/nineworlds/serenity/core/services/MusicTrackRetrievalIntentService.java index 3da60272..9a586aa9 100644 --- a/serenity-app/src/main/java/us/nineworlds/serenity/core/services/MusicTrackRetrievalIntentService.java +++ b/serenity-app/src/main/java/us/nineworlds/serenity/core/services/MusicTrackRetrievalIntentService.java @@ -1,137 +1,138 @@ /** * The MIT License (MIT) * Copyright (c) 2012 David Carver * 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 us.nineworlds.serenity.core.services; import java.io.IOException; import java.util.ArrayList; import java.util.List; import us.nineworlds.plex.rest.model.impl.Directory; import us.nineworlds.plex.rest.model.impl.Media; import us.nineworlds.plex.rest.model.impl.MediaContainer; import us.nineworlds.plex.rest.model.impl.Part; import us.nineworlds.plex.rest.model.impl.Track; import us.nineworlds.serenity.SerenityApplication; import us.nineworlds.serenity.core.model.impl.AudioTrackContentInfo; import us.nineworlds.serenity.core.model.impl.MusicAlbumContentInfo; import android.content.Intent; import android.os.Bundle; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.util.Log; /** * A service that retrieves music information from the Plex Media Server. * * @author dcarver * */ public class MusicTrackRetrievalIntentService extends AbstractPlexRESTIntentService { private static final String MUSIC_RETRIEVAL_INTENT_SERVICE = "MusicTrackRetrievalIntentService"; protected List<AudioTrackContentInfo> musicContentList = null; protected String key; protected String category; public MusicTrackRetrievalIntentService() { super(MUSIC_RETRIEVAL_INTENT_SERVICE); musicContentList = new ArrayList<AudioTrackContentInfo>(); } @Override public void sendMessageResults(Intent intent) { Bundle extras = intent.getExtras(); if (extras != null) { Messenger messenger = (Messenger) extras.get("MESSENGER"); Message msg = Message.obtain(); msg.obj = musicContentList; try { messenger.send(msg); } catch (RemoteException ex) { Log.e(getClass().getName(), "Unable to send message", ex); } } } @Override protected void onHandleIntent(Intent intent) { key = intent.getExtras().getString("key", ""); createPosters(); sendMessageResults(intent); } protected void createPosters() { MediaContainer mc = null; try { factory = SerenityApplication.getPlexFactory(); mc = retrieveVideos(); } catch (IOException ex) { Log.e("AbstractPosterImageGalleryAdapter", "Unable to talk to server: ", ex); } catch (Exception e) { Log.e("AbstractPosterImageGalleryAdapter", "Oops.", e); } if (mc != null && mc.getSize() > 0) { createVideoContent(mc); } } protected void createVideoContent(MediaContainer mc) { String baseUrl = factory.baseURL(); List<Track> tracks = mc.getTracks(); String mediaTagId = Long.valueOf(mc.getMediaTagVersion()).toString(); for (Track track : tracks) { AudioTrackContentInfo mpi = new AudioTrackContentInfo(); mpi.setMediaTagIdentifier(mediaTagId); mpi.setId(track.getKey()); mpi.setSummary(track.getSummary()); mpi.setDuration(track.getDuration()); List<Media> medias = track.getMedias(); Media mediaTrack = medias.get(0); mpi.setAudioChannels(mediaTrack.getAudioChannels()); List<Part> parts = mediaTrack.getVideoPart(); Part part = parts.get(0); mpi.setDirectPlayUrl(baseUrl + part.getKey()); mpi.setTitle(track .getTitle()); + mpi.setParentPosterURL(baseUrl + mc.getParentPosterURL().substring(1)); mpi.setImageURL(baseUrl + mc.getParentPosterURL().substring(1)); musicContentList.add(mpi); } } protected MediaContainer retrieveVideos() throws Exception { return factory.retrieveMusicMetaData(key); } }
true
true
protected void createVideoContent(MediaContainer mc) { String baseUrl = factory.baseURL(); List<Track> tracks = mc.getTracks(); String mediaTagId = Long.valueOf(mc.getMediaTagVersion()).toString(); for (Track track : tracks) { AudioTrackContentInfo mpi = new AudioTrackContentInfo(); mpi.setMediaTagIdentifier(mediaTagId); mpi.setId(track.getKey()); mpi.setSummary(track.getSummary()); mpi.setDuration(track.getDuration()); List<Media> medias = track.getMedias(); Media mediaTrack = medias.get(0); mpi.setAudioChannels(mediaTrack.getAudioChannels()); List<Part> parts = mediaTrack.getVideoPart(); Part part = parts.get(0); mpi.setDirectPlayUrl(baseUrl + part.getKey()); mpi.setTitle(track .getTitle()); mpi.setImageURL(baseUrl + mc.getParentPosterURL().substring(1)); musicContentList.add(mpi); } }
protected void createVideoContent(MediaContainer mc) { String baseUrl = factory.baseURL(); List<Track> tracks = mc.getTracks(); String mediaTagId = Long.valueOf(mc.getMediaTagVersion()).toString(); for (Track track : tracks) { AudioTrackContentInfo mpi = new AudioTrackContentInfo(); mpi.setMediaTagIdentifier(mediaTagId); mpi.setId(track.getKey()); mpi.setSummary(track.getSummary()); mpi.setDuration(track.getDuration()); List<Media> medias = track.getMedias(); Media mediaTrack = medias.get(0); mpi.setAudioChannels(mediaTrack.getAudioChannels()); List<Part> parts = mediaTrack.getVideoPart(); Part part = parts.get(0); mpi.setDirectPlayUrl(baseUrl + part.getKey()); mpi.setTitle(track .getTitle()); mpi.setParentPosterURL(baseUrl + mc.getParentPosterURL().substring(1)); mpi.setImageURL(baseUrl + mc.getParentPosterURL().substring(1)); musicContentList.add(mpi); } }
diff --git a/src/org/irmacard/web/restapi/resources/VerificationProtocolResource.java b/src/org/irmacard/web/restapi/resources/VerificationProtocolResource.java index 868c5d1..e9567d7 100644 --- a/src/org/irmacard/web/restapi/resources/VerificationProtocolResource.java +++ b/src/org/irmacard/web/restapi/resources/VerificationProtocolResource.java @@ -1,147 +1,147 @@ package org.irmacard.web.restapi.resources; import java.lang.reflect.Type; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.UUID; import net.sourceforge.scuba.smartcards.IResponseAPDU; import net.sourceforge.scuba.smartcards.ResponseAPDU; import net.sourceforge.scuba.util.Hex; import org.irmacard.web.restapi.IRMASetup; import org.irmacard.web.restapi.util.CommandSet; import org.irmacard.web.restapi.util.ProtocolCommandSerializer; import org.irmacard.web.restapi.util.ResponseAPDUDeserializer; import org.restlet.resource.Post; import org.restlet.resource.ServerResource; import service.ProtocolCommand; import service.ProtocolResponses; import com.google.gson.Gson; import com.google.gson.GsonBuilder; 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 credentials.Attributes; import credentials.CredentialsException; import credentials.Nonce; import credentials.idemix.IdemixCredentials; import credentials.idemix.IdemixNonce; import credentials.idemix.spec.IdemixVerifySpecification; import credentials.idemix.util.VerifyCredentialInformation; /** * Resource for the verification protocol. * @author Maarten Everts * */ public class VerificationProtocolResource extends ServerResource { private final String ISSUER = "MijnOverheid"; private final String CRED_NAME = "ageLower"; private final String VERIFIER = "UitzendingGemist"; private final String SPEC_NAME = "ageLowerOver16"; @Post("json") public String handlePost (String value) { Integer crednr = Integer.parseInt((String) getRequestAttributes().get("crednr")); String id = (String) getRequestAttributes().get("id"); String round = (String) getRequestAttributes().get("round"); if (id == null) { return step0(crednr,value); } else if (round != null && round.equals("1")) { return step1(crednr,value,id); } return null; } /** * Start new verification protocol * @param crednr credential number * @param value request body * @return */ public String step0(int crednr, String value) { Gson gson = new GsonBuilder(). setPrettyPrinting(). registerTypeAdapter(ProtocolCommand.class, new ProtocolCommandSerializer()). create(); VerifyCredentialInformation vci = new VerifyCredentialInformation( ISSUER, CRED_NAME, VERIFIER, SPEC_NAME); IdemixCredentials ic = new IdemixCredentials(); IdemixVerifySpecification vspec = vci.getIdemixVerifySpecification(); try { CommandSet cs = new CommandSet(); Nonce nonce = ic.generateNonce(vspec); cs.commands = ic.requestProofCommands(vspec, nonce); // Save the state, use random id as key UUID id = UUID.randomUUID(); BigInteger intNonce = ((IdemixNonce)nonce).getNonce(); @SuppressWarnings("unchecked") Map<String ,BigInteger> noncemap = (Map<String,BigInteger>)getContext().getAttributes().get("noncemap"); noncemap.put(id.toString(), intNonce); cs.responseurl = getReference().getPath() + "/" + id.toString() + "/1"; return gson.toJson(cs); } catch (CredentialsException e) { e.printStackTrace(); } return null; } /** * Handle the next step of the verification protocol. * @param crednr credential number * @param value request body (with the card responses) * @param verificationId * @return */ public String step1(int crednr, String value, String verificationId) { Gson gson = new GsonBuilder(). setPrettyPrinting(). registerTypeAdapter(IResponseAPDU.class, new ResponseAPDUDeserializer()). create(); // Get the nonce based on the id @SuppressWarnings("unchecked") Map<String ,BigInteger> noncemap = (Map<String,BigInteger>)getContext().getAttributes().get("noncemap"); BigInteger intNonce = noncemap.get(verificationId); IdemixNonce nonce = new IdemixNonce(intNonce); ProtocolResponses responses = gson.fromJson(value, ProtocolResponses.class); VerifyCredentialInformation vci = new VerifyCredentialInformation( ISSUER, CRED_NAME, VERIFIER, SPEC_NAME); IdemixCredentials ic = new IdemixCredentials(); IdemixVerifySpecification vspec = vci.getIdemixVerifySpecification(); try { Attributes attr = ic.verifyProofResponses(vspec, nonce, responses); // TODO: do something with the results! if (attr == null) { return "{\"response\": \"invalid\"}"; } else { attr.print(); - return "{\"response\": \"valid\"}"; + return "{\"response\": \"valid\", \"url\": \"http://spuitenenslikken.bnn.nl/\"}"; } } catch (CredentialsException e) { e.printStackTrace(); return "{\"response\": \"invalid\"}"; } } }
true
true
public String step1(int crednr, String value, String verificationId) { Gson gson = new GsonBuilder(). setPrettyPrinting(). registerTypeAdapter(IResponseAPDU.class, new ResponseAPDUDeserializer()). create(); // Get the nonce based on the id @SuppressWarnings("unchecked") Map<String ,BigInteger> noncemap = (Map<String,BigInteger>)getContext().getAttributes().get("noncemap"); BigInteger intNonce = noncemap.get(verificationId); IdemixNonce nonce = new IdemixNonce(intNonce); ProtocolResponses responses = gson.fromJson(value, ProtocolResponses.class); VerifyCredentialInformation vci = new VerifyCredentialInformation( ISSUER, CRED_NAME, VERIFIER, SPEC_NAME); IdemixCredentials ic = new IdemixCredentials(); IdemixVerifySpecification vspec = vci.getIdemixVerifySpecification(); try { Attributes attr = ic.verifyProofResponses(vspec, nonce, responses); // TODO: do something with the results! if (attr == null) { return "{\"response\": \"invalid\"}"; } else { attr.print(); return "{\"response\": \"valid\"}"; } } catch (CredentialsException e) { e.printStackTrace(); return "{\"response\": \"invalid\"}"; } }
public String step1(int crednr, String value, String verificationId) { Gson gson = new GsonBuilder(). setPrettyPrinting(). registerTypeAdapter(IResponseAPDU.class, new ResponseAPDUDeserializer()). create(); // Get the nonce based on the id @SuppressWarnings("unchecked") Map<String ,BigInteger> noncemap = (Map<String,BigInteger>)getContext().getAttributes().get("noncemap"); BigInteger intNonce = noncemap.get(verificationId); IdemixNonce nonce = new IdemixNonce(intNonce); ProtocolResponses responses = gson.fromJson(value, ProtocolResponses.class); VerifyCredentialInformation vci = new VerifyCredentialInformation( ISSUER, CRED_NAME, VERIFIER, SPEC_NAME); IdemixCredentials ic = new IdemixCredentials(); IdemixVerifySpecification vspec = vci.getIdemixVerifySpecification(); try { Attributes attr = ic.verifyProofResponses(vspec, nonce, responses); // TODO: do something with the results! if (attr == null) { return "{\"response\": \"invalid\"}"; } else { attr.print(); return "{\"response\": \"valid\", \"url\": \"http://spuitenenslikken.bnn.nl/\"}"; } } catch (CredentialsException e) { e.printStackTrace(); return "{\"response\": \"invalid\"}"; } }
diff --git a/org.emftext.sdk.ui/src/org/emftext/sdk/ui/actions/GenerateAllAction.java b/org.emftext.sdk.ui/src/org/emftext/sdk/ui/actions/GenerateAllAction.java index 0114b0bfd..cc7f2edee 100644 --- a/org.emftext.sdk.ui/src/org/emftext/sdk/ui/actions/GenerateAllAction.java +++ b/org.emftext.sdk.ui/src/org/emftext/sdk/ui/actions/GenerateAllAction.java @@ -1,139 +1,142 @@ /******************************************************************************* * Copyright (c) 2006-2012 * Software Technology Group, Dresden University of Technology * DevBoost GmbH, Berlin, Amtsgericht Charlottenburg, HRB 140026 * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Software Technology Group - TU Dresden, Germany; * DevBoost GmbH - Berlin, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.ui.actions; import java.util.Iterator; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.emf.codegen.ecore.generator.Generator; import org.eclipse.emf.codegen.ecore.genmodel.GenModel; import org.eclipse.emf.codegen.ecore.genmodel.generator.GenBaseGeneratorAdapter; import org.eclipse.emf.common.util.BasicMonitor; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.plugin.EcorePlugin; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.emftext.sdk.concretesyntax.resource.cs.mopp.CsMetaInformation; import org.emftext.sdk.concretesyntax.resource.cs.ui.CsUIPlugin; import org.emftext.sdk.ui.jobs.GenerateResourcePluginsJob; /** * The {@link GenerateAllAction} visits the selected elements and all their * children to find generator models and concrete syntax definitions. For all * found models the respective code generator is invoked (Ecode model code for * all generator models and EMFText resource plug-in code for all syntax * definitions). */ public class GenerateAllAction implements IObjectActionDelegate { private ISelection selection; public void run(IAction action) { if (selection instanceof IStructuredSelection) { Iterator<?> it = ((IStructuredSelection) selection).iterator(); while (it.hasNext()) { Object o = it.next(); if (o instanceof IResource) { IResource resource = (IResource) o; try { traverse(resource); } catch (CoreException e) { CsUIPlugin.logError("Exception while traversing selection", e); } } } } } private void traverse(IResource resource) throws CoreException { if (resource instanceof IFile) { IFile file = (IFile) resource; process(file); } else { resource.accept(new IResourceVisitor() { @Override public boolean visit(IResource resource) throws CoreException { process(resource); return true; } }); } } private void process(IResource resource) throws CoreException { if (resource instanceof IFile) { final IFile file = (IFile) resource; String fileExtension = file.getFileExtension(); Job job = null; + if (fileExtension == null) { + return; + } if (fileExtension.equals(new CsMetaInformation().getSyntaxName())) { job = new GenerateResourcePluginsJob("Generating resource project for " + file.getName(), file); } else if (fileExtension.equals("genmodel")) { job = new Job("Generate metamodel code job") { @Override protected IStatus run(IProgressMonitor monitor) { URI uri = URI.createPlatformResourceURI(file.getFullPath().toString(), true); ResourceSet rs = new ResourceSetImpl(); rs.getURIConverter().getURIMap().putAll(EcorePlugin.computePlatformURIMap()); Resource genModelResource = rs.getResource(uri, true); EList<EObject> contents = genModelResource.getContents(); for (EObject eObject : contents) { if (eObject instanceof GenModel) { GenModel genModel = (GenModel) eObject; genModel.reconcile(); genModel.setCanGenerate(true); Generator generator = new Generator(); generator.setInput(genModel); String type = GenBaseGeneratorAdapter.MODEL_PROJECT_TYPE; generator.generate(genModel, type, new BasicMonitor()); } } return Status.OK_STATUS; } }; } if (job != null) { job.setUser(true); job.schedule(); } } } public void selectionChanged(IAction action, ISelection selection) { this.selection = selection; } public void setActivePart(IAction action, IWorkbenchPart part) { // do nothing } }
true
true
private void process(IResource resource) throws CoreException { if (resource instanceof IFile) { final IFile file = (IFile) resource; String fileExtension = file.getFileExtension(); Job job = null; if (fileExtension.equals(new CsMetaInformation().getSyntaxName())) { job = new GenerateResourcePluginsJob("Generating resource project for " + file.getName(), file); } else if (fileExtension.equals("genmodel")) { job = new Job("Generate metamodel code job") { @Override protected IStatus run(IProgressMonitor monitor) { URI uri = URI.createPlatformResourceURI(file.getFullPath().toString(), true); ResourceSet rs = new ResourceSetImpl(); rs.getURIConverter().getURIMap().putAll(EcorePlugin.computePlatformURIMap()); Resource genModelResource = rs.getResource(uri, true); EList<EObject> contents = genModelResource.getContents(); for (EObject eObject : contents) { if (eObject instanceof GenModel) { GenModel genModel = (GenModel) eObject; genModel.reconcile(); genModel.setCanGenerate(true); Generator generator = new Generator(); generator.setInput(genModel); String type = GenBaseGeneratorAdapter.MODEL_PROJECT_TYPE; generator.generate(genModel, type, new BasicMonitor()); } } return Status.OK_STATUS; } }; } if (job != null) { job.setUser(true); job.schedule(); } } }
private void process(IResource resource) throws CoreException { if (resource instanceof IFile) { final IFile file = (IFile) resource; String fileExtension = file.getFileExtension(); Job job = null; if (fileExtension == null) { return; } if (fileExtension.equals(new CsMetaInformation().getSyntaxName())) { job = new GenerateResourcePluginsJob("Generating resource project for " + file.getName(), file); } else if (fileExtension.equals("genmodel")) { job = new Job("Generate metamodel code job") { @Override protected IStatus run(IProgressMonitor monitor) { URI uri = URI.createPlatformResourceURI(file.getFullPath().toString(), true); ResourceSet rs = new ResourceSetImpl(); rs.getURIConverter().getURIMap().putAll(EcorePlugin.computePlatformURIMap()); Resource genModelResource = rs.getResource(uri, true); EList<EObject> contents = genModelResource.getContents(); for (EObject eObject : contents) { if (eObject instanceof GenModel) { GenModel genModel = (GenModel) eObject; genModel.reconcile(); genModel.setCanGenerate(true); Generator generator = new Generator(); generator.setInput(genModel); String type = GenBaseGeneratorAdapter.MODEL_PROJECT_TYPE; generator.generate(genModel, type, new BasicMonitor()); } } return Status.OK_STATUS; } }; } if (job != null) { job.setUser(true); job.schedule(); } } }
diff --git a/lenskit-slopeone/src/main/java/org/grouplens/lenskit/slopeone/SlopeOneRatingPredictor.java b/lenskit-slopeone/src/main/java/org/grouplens/lenskit/slopeone/SlopeOneRatingPredictor.java index b40f68b45..efd8e95a4 100644 --- a/lenskit-slopeone/src/main/java/org/grouplens/lenskit/slopeone/SlopeOneRatingPredictor.java +++ b/lenskit-slopeone/src/main/java/org/grouplens/lenskit/slopeone/SlopeOneRatingPredictor.java @@ -1,91 +1,91 @@ /* * LensKit, an open source recommender systems toolkit. * Copyright 2010-2012 Regents of the University of Minnesota and contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.grouplens.lenskit.slopeone; import it.unimi.dsi.fastutil.longs.LongIterator; import org.grouplens.lenskit.RatingPredictor; import org.grouplens.lenskit.baseline.BaselinePredictor; import org.grouplens.lenskit.core.AbstractItemScorer; import org.grouplens.lenskit.data.Event; import org.grouplens.lenskit.data.UserHistory; import org.grouplens.lenskit.data.dao.DataAccessObject; import org.grouplens.lenskit.data.history.RatingVectorUserHistorySummarizer; import org.grouplens.lenskit.vectors.MutableSparseVector; import org.grouplens.lenskit.vectors.SparseVector; import org.grouplens.lenskit.vectors.VectorEntry; import javax.annotation.Nonnull; import javax.inject.Inject; /** * A <tt>RatingPredictor<tt> that implements the Slope One algorithm. */ public class SlopeOneRatingPredictor extends AbstractItemScorer implements RatingPredictor { protected SlopeOneModel model; @Inject public SlopeOneRatingPredictor(DataAccessObject dao, SlopeOneModel model) { super(dao); this.model = model; } @Override public void score(@Nonnull UserHistory<? extends Event> history, @Nonnull MutableSparseVector scores) { SparseVector user = RatingVectorUserHistorySummarizer.makeRatingVector(history); int nUnpred = 0; for (VectorEntry e: scores.fast(VectorEntry.State.EITHER)) { final long predicteeItem = e.getKey(); if (!user.containsKey(predicteeItem)) { double total = 0; int nitems = 0; LongIterator ratingIter = user.keySet().iterator(); while (ratingIter.hasNext()) { long currentItem = ratingIter.nextLong(); int nusers = model.getCoratings(predicteeItem, currentItem); if (nusers != 0) { double currentDev = model.getDeviation(predicteeItem, currentItem); total += currentDev + user.get(currentItem); nitems++; } } if (nitems != 0) { double predValue = total/nitems; predValue = model.getDomain().clampValue(predValue); scores.set(e, predValue); } else { nUnpred += 1; scores.clear(e); } } } //Use Baseline Predictor if necessary final BaselinePredictor baseline = model.getBaselinePredictor(); - if (baseline != null && nUnpred == 0) { + if (baseline != null && nUnpred > 0) { baseline.predict(history.getUserId(), user, scores, false); } } public SlopeOneModel getModel() { return model; } }
true
true
public void score(@Nonnull UserHistory<? extends Event> history, @Nonnull MutableSparseVector scores) { SparseVector user = RatingVectorUserHistorySummarizer.makeRatingVector(history); int nUnpred = 0; for (VectorEntry e: scores.fast(VectorEntry.State.EITHER)) { final long predicteeItem = e.getKey(); if (!user.containsKey(predicteeItem)) { double total = 0; int nitems = 0; LongIterator ratingIter = user.keySet().iterator(); while (ratingIter.hasNext()) { long currentItem = ratingIter.nextLong(); int nusers = model.getCoratings(predicteeItem, currentItem); if (nusers != 0) { double currentDev = model.getDeviation(predicteeItem, currentItem); total += currentDev + user.get(currentItem); nitems++; } } if (nitems != 0) { double predValue = total/nitems; predValue = model.getDomain().clampValue(predValue); scores.set(e, predValue); } else { nUnpred += 1; scores.clear(e); } } } //Use Baseline Predictor if necessary final BaselinePredictor baseline = model.getBaselinePredictor(); if (baseline != null && nUnpred == 0) { baseline.predict(history.getUserId(), user, scores, false); } }
public void score(@Nonnull UserHistory<? extends Event> history, @Nonnull MutableSparseVector scores) { SparseVector user = RatingVectorUserHistorySummarizer.makeRatingVector(history); int nUnpred = 0; for (VectorEntry e: scores.fast(VectorEntry.State.EITHER)) { final long predicteeItem = e.getKey(); if (!user.containsKey(predicteeItem)) { double total = 0; int nitems = 0; LongIterator ratingIter = user.keySet().iterator(); while (ratingIter.hasNext()) { long currentItem = ratingIter.nextLong(); int nusers = model.getCoratings(predicteeItem, currentItem); if (nusers != 0) { double currentDev = model.getDeviation(predicteeItem, currentItem); total += currentDev + user.get(currentItem); nitems++; } } if (nitems != 0) { double predValue = total/nitems; predValue = model.getDomain().clampValue(predValue); scores.set(e, predValue); } else { nUnpred += 1; scores.clear(e); } } } //Use Baseline Predictor if necessary final BaselinePredictor baseline = model.getBaselinePredictor(); if (baseline != null && nUnpred > 0) { baseline.predict(history.getUserId(), user, scores, false); } }
diff --git a/loci/visbio/MacAdapter.java b/loci/visbio/MacAdapter.java index 6033a0b61..10b30915d 100644 --- a/loci/visbio/MacAdapter.java +++ b/loci/visbio/MacAdapter.java @@ -1,97 +1,97 @@ // // MacAdapter.java // /* VisBio application for visualization of multidimensional biological image data. Copyright (C) 2002-2003 Curtis Rueden. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.visbio; import com.apple.eawt.*; import loci.visbio.VisBioFrame; import loci.visbio.ExitManager; import loci.visbio.help.HelpManager; import loci.visbio.state.OptionManager; /** An adapter for handling the Mac OS X application menu items. */ public class MacAdapter extends ApplicationAdapter { // Note: This class will only compile on Macintosh systems. However, since // no other classes depend on it directly (i.e., they reference it via // reflection), the rest of VisBio should still compile on non-Macintoshes. // Alternately, the code can be compiled on other platforms with the // "AppleJavaExtensions" stub jar available from: // http://developer.apple.com/samplecode/Sample_Code/Java.htm // -- Fields -- /** Linked VisBio frame. */ private VisBioFrame bio; // -- Constructor -- /** Constructs a Mac OS X adapter. */ public MacAdapter(VisBioFrame bio) { this.bio = bio; } // -- ApplicationAdapter API methods -- /** Handles the About menu item. */ public void handleAbout(ApplicationEvent evt) { HelpManager hm = (HelpManager) bio.getManager(HelpManager.class); if (hm == null) evt.setHandled(false); else { evt.setHandled(true); - hm.helpShow("About"); + hm.helpAbout(); } } /** Handles the Preferences menu item. */ public void handlePreferences(ApplicationEvent evt) { OptionManager om = (OptionManager) bio.getManager(OptionManager.class); if (om == null) evt.setHandled(false); else { evt.setHandled(true); om.fileOptions(); } } /** Handles the Quit menu item. */ public void handleQuit(ApplicationEvent evt) { ExitManager em = (ExitManager) bio.getManager(ExitManager.class); if (em == null) evt.setHandled(true); else { evt.setHandled(false); em.fileExit(); } } // -- New API methods -- /** Associates the VisBio frame with a Mac OS X adapter. */ public static void link(VisBioFrame bio) { Application app = new Application(); app.setEnabledPreferencesMenu(true); app.addApplicationListener(new MacAdapter(bio)); } }
true
true
public void handleAbout(ApplicationEvent evt) { HelpManager hm = (HelpManager) bio.getManager(HelpManager.class); if (hm == null) evt.setHandled(false); else { evt.setHandled(true); hm.helpShow("About"); } }
public void handleAbout(ApplicationEvent evt) { HelpManager hm = (HelpManager) bio.getManager(HelpManager.class); if (hm == null) evt.setHandled(false); else { evt.setHandled(true); hm.helpAbout(); } }
diff --git a/src/de/quadrillenschule/liquidroid/model/Initiativen.java b/src/de/quadrillenschule/liquidroid/model/Initiativen.java index b894b7f..e0904bc 100644 --- a/src/de/quadrillenschule/liquidroid/model/Initiativen.java +++ b/src/de/quadrillenschule/liquidroid/model/Initiativen.java @@ -1,176 +1,180 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.quadrillenschule.liquidroid.model; import android.content.SharedPreferences; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** * * @author andi */ public class Initiativen extends MultiInstanceInitiativen { private ArrayList<Integer> existingIssueIds = new ArrayList<Integer>(); SharedPreferences instancePrefs; public Initiativen(SharedPreferences instancePrefs) { super(); this.instancePrefs = instancePrefs; } public Initiativen getSelectedIssues() { Initiativen retval = new Initiativen(instancePrefs); String[] selectedissues_str = instancePrefs.getString("selectedissues", "0").split(":"); ArrayList<Integer> selectedIssues = new ArrayList<Integer>(); for (String s : selectedissues_str) { try { selectedIssues.add(Integer.parseInt(s)); } catch (Exception e) { } } for (Integer i : selectedIssues) { for (Initiative ini : findByIssueID(i)) { retval.add(ini); } } return retval; } public boolean isPositionSelected(int pos) { Initiative myini = this.get(pos); String[] selectedissues_str = instancePrefs.getString("selectedissues", "0").split(":"); for (String s : selectedissues_str) { try { if (Integer.parseInt(s) == myini.issue_id) { return true; } } catch (Exception e) { } } return false; } public boolean isIssueSelected(int issueid) { Initiativen myinis = findByIssueID(issueid); if (myinis.size() <= 0) { return false; } Initiative myini = myinis.get(0); String[] selectedissues_str = instancePrefs.getString("selectedissues", "0").split(":"); for (String s : selectedissues_str) { try { if (Integer.parseInt(s) == myini.issue_id) { return true; } } catch (Exception e) { } } return false; } public void setSelectedIssue(int issueid, boolean value) { String selectedIssuesString = instancePrefs.getString("selectedissues", ""); if (value) { //Shall be selected if (this.getSelectedIssues().findByIssueID(issueid).size() == 0) { //is not selected selectedIssuesString = selectedIssuesString + ":" + issueid; LQFBInstances.selectionUpdatesForRefresh = true; } else { //is already selected - change noting } } else { //Shall not be selected if (this.getSelectedIssues().findByIssueID(issueid).size() == 0) { //is not selected do nothing } else { //is selected, unselect LQFBInstances.selectionUpdatesForRefresh = true; String newselectedissues = ""; + if (!selectedIssuesString.contains(":")){ + //must be lastone + selectedIssuesString=""; + } for (String snippet : selectedIssuesString.split(":")) { if (!snippet.equals(issueid + "")) { newselectedissues += snippet + ":"; } } int len = newselectedissues.length(); if (len > 0) { selectedIssuesString = newselectedissues.substring(0, len - 1); } } } SharedPreferences.Editor editor = instancePrefs.edit(); selectedIssuesString = selectedIssuesString.replaceAll("::", ":"); if (selectedIssuesString.startsWith(":")) { selectedIssuesString = selectedIssuesString.substring(1); } if (selectedIssuesString.endsWith(":")) { selectedIssuesString = selectedIssuesString.substring(0, selectedIssuesString.length() - 1); } editor.putString("selectedissues", selectedIssuesString); editor.commit(); } @Override public boolean add(Initiative ini) { if (!existingIssueIds.contains((Integer) ini.issue_id)) { existingIssueIds.add((Integer) ini.issue_id); return super.add(ini); } processDuplicate(ini); return false; } private void processDuplicate(Initiative ini) { Initiative existing = findByIssueID(ini.issue_id).get(0); } @Override public void clear() { existingIssueIds.clear(); super.clear(); } @Override public Initiative remove(int i) { existingIssueIds.remove((Integer) get(i).issue_id); return super.remove(i); } public Initiativen findByIssueID(int find) { Initiativen retval = new Initiativen(instancePrefs); for (Initiative i : this) { if (i.issue_id == find) { retval.add(i); } } return retval; } public Initiativen findByName(String name) { Initiativen retval = new Initiativen(instancePrefs); for (Initiative i : this) { if (i.name == name) { retval.add(i); } } return retval; } }
true
true
public void setSelectedIssue(int issueid, boolean value) { String selectedIssuesString = instancePrefs.getString("selectedissues", ""); if (value) { //Shall be selected if (this.getSelectedIssues().findByIssueID(issueid).size() == 0) { //is not selected selectedIssuesString = selectedIssuesString + ":" + issueid; LQFBInstances.selectionUpdatesForRefresh = true; } else { //is already selected - change noting } } else { //Shall not be selected if (this.getSelectedIssues().findByIssueID(issueid).size() == 0) { //is not selected do nothing } else { //is selected, unselect LQFBInstances.selectionUpdatesForRefresh = true; String newselectedissues = ""; for (String snippet : selectedIssuesString.split(":")) { if (!snippet.equals(issueid + "")) { newselectedissues += snippet + ":"; } } int len = newselectedissues.length(); if (len > 0) { selectedIssuesString = newselectedissues.substring(0, len - 1); } } } SharedPreferences.Editor editor = instancePrefs.edit(); selectedIssuesString = selectedIssuesString.replaceAll("::", ":"); if (selectedIssuesString.startsWith(":")) { selectedIssuesString = selectedIssuesString.substring(1); } if (selectedIssuesString.endsWith(":")) { selectedIssuesString = selectedIssuesString.substring(0, selectedIssuesString.length() - 1); } editor.putString("selectedissues", selectedIssuesString); editor.commit(); }
public void setSelectedIssue(int issueid, boolean value) { String selectedIssuesString = instancePrefs.getString("selectedissues", ""); if (value) { //Shall be selected if (this.getSelectedIssues().findByIssueID(issueid).size() == 0) { //is not selected selectedIssuesString = selectedIssuesString + ":" + issueid; LQFBInstances.selectionUpdatesForRefresh = true; } else { //is already selected - change noting } } else { //Shall not be selected if (this.getSelectedIssues().findByIssueID(issueid).size() == 0) { //is not selected do nothing } else { //is selected, unselect LQFBInstances.selectionUpdatesForRefresh = true; String newselectedissues = ""; if (!selectedIssuesString.contains(":")){ //must be lastone selectedIssuesString=""; } for (String snippet : selectedIssuesString.split(":")) { if (!snippet.equals(issueid + "")) { newselectedissues += snippet + ":"; } } int len = newselectedissues.length(); if (len > 0) { selectedIssuesString = newselectedissues.substring(0, len - 1); } } } SharedPreferences.Editor editor = instancePrefs.edit(); selectedIssuesString = selectedIssuesString.replaceAll("::", ":"); if (selectedIssuesString.startsWith(":")) { selectedIssuesString = selectedIssuesString.substring(1); } if (selectedIssuesString.endsWith(":")) { selectedIssuesString = selectedIssuesString.substring(0, selectedIssuesString.length() - 1); } editor.putString("selectedissues", selectedIssuesString); editor.commit(); }
diff --git a/server-coreless/src/main/java/org/openqa/selenium/server/testgenerator/XlateHtmlSeleneseToJava.java b/server-coreless/src/main/java/org/openqa/selenium/server/testgenerator/XlateHtmlSeleneseToJava.java index 3d1c702b..ca2a3449 100644 --- a/server-coreless/src/main/java/org/openqa/selenium/server/testgenerator/XlateHtmlSeleneseToJava.java +++ b/server-coreless/src/main/java/org/openqa/selenium/server/testgenerator/XlateHtmlSeleneseToJava.java @@ -1,789 +1,792 @@ /* * Created on Mar 12, 2006 * */ package org.openqa.selenium.server.testgenerator; import java.io.*; import java.util.*; import javax.xml.parsers.*; import org.w3c.dom.*; /** * Given an HTML file containing a Selenese test case, generate equivalent Java code w/ calls * to the Selenium object to execute that same test case. * * @author nsproul * */ public class XlateHtmlSeleneseToJava { static Set<String> generatedJavaClassNames = new HashSet<String>(); private static Map<String, Class> funcTypes = null; private static Map<String, Integer> funcArgCounts = null; static final String BEGIN_SELENESE = ">>>>>"; static final String END_SELENESE = "<<<<<"; static final String SELENESE_TOKEN_DIVIDER = "//////"; static final String DIR = "dir"; static final String FILE= "file"; static HashMap<String, String> declaredVariables = new HashMap<String, String>(); private static int varNameSeed = 1; private static String BOL = "\t\t\t"; private static String EOL = "\n" + BOL; private static int timeOut = 30000; private static String domain; private static boolean silentMode = false; private static boolean dontThrowOnTranslationDifficulties = false; private static String packageName = "com.thoughtworks.selenium.corebased"; public static void main(String[] args) throws IOException { if (args.length < 2) { Usage("too few args"); return; } boolean generateSuite = false; HashMap<String, Boolean> skipList = new HashMap<String, Boolean>(); HashMap<String, String> inputFileList = new HashMap<String, String>(); String javaSeleneseFileDirectoryName = args[0]; for (int j = 1; j < args.length; j++) { if (args[j].equals("-silent")) { silentMode = true; } else if (args[j].equals("-skip")) { skipList.put(args[++j], Boolean.TRUE); } else if (args[j].equals("-dontThrowOnTranslationDifficulties")) { dontThrowOnTranslationDifficulties = true; } else if (args[j].equals("-package")) { packageName = args[++j]; } else if (args[j].equals("-suite")) { generateSuite = true; } else if (args[j].equals("-dir")) { String dirName = args[++j]; inputFileList.put(dirName, DIR); } else { inputFileList.put(args[j], FILE); } } for (Iterator it = inputFileList.keySet().iterator(); it.hasNext();) { String s = (String) it.next(); if (FILE.equals(inputFileList.get(s))) { String htmlSeleneseFileName = s; generateJavaClassFromSeleneseHtml(htmlSeleneseFileName, javaSeleneseFileDirectoryName); } else if (DIR.equals(inputFileList.get(s))) { String dirName = s; File dir = new File(dirName); if (!dir.isDirectory()) { Usage("-dir is not a directory: " + dirName); } String children[] = dir.list(); for (int k = 0; k < children.length; k++) { String fileName = children[k]; if (skipList.containsKey(fileName)) { System.out.println("Skipping " + fileName); } else if (fileName.indexOf(".htm")!=-1 && fileName.indexOf("Suite")==-1) { generateJavaClassFromSeleneseHtml(dirName + "/" + fileName, javaSeleneseFileDirectoryName); } } } } if (generateSuite) { generateSuite(javaSeleneseFileDirectoryName); } } private static void initializeFuncTypes() { if (funcTypes != null) return; funcTypes = new HashMap<String, Class>(); funcArgCounts = new HashMap<String, Integer>(); InputStream stream = XlateHtmlSeleneseToJava.class.getResourceAsStream("/core/iedoc.xml"); if (stream==null) { throw new RuntimeException("could not find /core/iedoc.xml on the class path"); } try { Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(stream); NodeList functions = d.getElementsByTagName("function"); for (int i = 0; i < functions.getLength(); i++) { Element function = (Element) functions.item(i); String funcName = function.getAttribute("name"); NodeList returnElements = function.getElementsByTagName("return"); funcArgCounts.put(funcName, function.getElementsByTagName("param").getLength()); if (returnElements.getLength() == 0) { funcTypes.put(funcName, void.class); } else { Element ret = (Element) returnElements.item(0); String retType = ret.getAttribute("type"); if ("boolean".equals(retType)) { funcTypes.put(funcName, boolean.class); } else if ("string".equals(retType)) { funcTypes.put(funcName, String.class); } else if ("string[]".equals(retType)) { funcTypes.put(funcName, String[].class); } else if ("number".equals(retType)) { funcTypes.put(funcName, Number.class); } else { throw new RuntimeException("could not resolve type " + retType); } } } } catch (Exception e) { throw new RuntimeException(e); } } private static boolean isBoolean(String op) { return (boolean.class.equals(getOpType(op))); } private static Class getOpType(String opParm) { initializeFuncTypes(); String op = opParm; op = op.replaceFirst("AndWait$", ""); op = op.replaceFirst("Not([A-Z])", "$1"); if (funcTypes.get(op) != null) { return funcTypes.get(op); } op = op.replaceFirst("(assert|verify|store)", "get"); if (funcTypes.get(op) != null) { return funcTypes.get(op); } op = op.replaceFirst("get", "is"); if (funcTypes.get(op) != null) { return funcTypes.get(op); } System.out.println("could not find " + opParm + " (" + op + ")"); // if we get here, apparently op has no direct analog in Selenium. So just look at the name and guess: if (op.matches(".*Length$")) { return int.class; } if (op.matches(".*(Present|Visible|Editable)$") || op.matches("^is.+")) { return boolean.class; } return String.class; } private static void generateSuite(String javaSeleneseFileDirectoryName) throws IOException { if (generatedJavaClassNames.size()==1) { return; // this is a test run focusing on a single file, so a suite wouldn't be useful } String beginning = "package " + packageName + ";\n" + "\n" + "import junit.framework.Test;\n" + "import junit.framework.TestSuite;\n" + "\n" + "public class SeleneseSuite {\n" + " static public Test suite() {\n" + " TestSuite suite = new TestSuite();\n"; String ending = " return suite;\n" + " }\n" + "}\n"; StringBuffer middle = new StringBuffer(); Iterator i = generatedJavaClassNames.iterator(); while (i.hasNext()) { String generatedJavaClassName = (String) i.next(); if (!generatedJavaClassName.equals("TestJavascriptParameters")){ middle.append(" suite.addTestSuite(") .append(generatedJavaClassName) .append(".class);\n"); } } WriteFileContents(beginning + middle + ending, openFile(javaSeleneseFileDirectoryName + "/SeleneseSuite.java")); } private static void generateJavaClassFromSeleneseHtml(String htmlSeleneseFileName, String javaSeleneseFileDirectoryName) throws IOException { String base = htmlSeleneseFileName; base = base.replaceAll(".*/", ""); base = base.replaceAll("\\.html?$", ""); String javaSeleneseFileName = javaSeleneseFileDirectoryName + "/" + base + ".java"; generatedJavaClassNames.add(base); System.out.println("Generating test class " + base + " from\t" + htmlSeleneseFileName + "..."); File htmlSeleneseFile = openFile(htmlSeleneseFileName); File javaSeleneseFile = openFile(javaSeleneseFileName); try { javaSeleneseFile.createNewFile(); } catch (IOException e) { Usage(e.toString()); } if (!htmlSeleneseFile.canRead()) { Usage("can't read " + htmlSeleneseFileName); } if (!javaSeleneseFile.canWrite()) { Usage("can't write " + javaSeleneseFileName); } String htmlSelenese = ReadFileContents(htmlSeleneseFile); String javaSelenese = XlateString(base, htmlSeleneseFileName, htmlSelenese); WriteFileContents(javaSelenese, javaSeleneseFile); } private static void WriteFileContents(String s, File f) throws IOException { FileWriter output = new FileWriter(f); if (!silentMode) { System.out.println(">>>>" + s + "<<<<"); } output.write(s); output.close(); } protected static String possiblyDeclare(boolean isBoolean, String variableName) { if (!declaredVariables.containsKey(variableName)) { declaredVariables.put(variableName, variableName); return (isBoolean ? "boolean" : "String") + " " + variableName; } return variableName; } private static String XlateString(String base, String htmlSeleneseFileName, String htmlSelenese) { declaredVariables.clear(); domain = null; String preamble = "package " + packageName + ";\n" + "import com.thoughtworks.selenium.*;\n" + "/**\n" + " * @author XlateHtmlSeleneseToJava\n" + " * Generated from " + htmlSeleneseFileName + ".\n" + " */\n" + "public class " + base + " extends SeleneseTestCase\n" + "{\n" + " public void " + makeTestName(base) + "() throws Throwable {\n\t\ttry {\n\t\t\t"; StringBuffer java = new StringBuffer(); if (htmlSelenese.indexOf("/core/scripts/narcissus-parse.js\"></script>")!=-1) { throw new RuntimeException("no support for translating narcissus JavaScript-based tests"); } String body = htmlSelenese.replaceAll("[\n]", ""); body = body.replaceAll("\\s*<", "<"); body = body.replaceAll("</?em/?>", ""); body = body.replaceAll("\r", ""); body = body.replaceAll("</?[bi]/?>", ""); body = body.replaceFirst(".*<title>([^<]+)</title>.*?<table.*?>", "\n"); body = body.replaceAll("<br>", ""); // these pop up all over and break other regexps body = body.replaceAll("\\\\", "\\\\\\\\"); // double the backslashes to avoid invalid escape sequences body = body.replaceAll(">\\s*<", "><"); body = body.replaceAll("</?tbody>", ""); body = body.replaceAll("<tr><t[dh]\\s+(rowspan=\"1\"\\s+)?colspan=\"3\">([^<]+)</t[dh]></tr>", "\n/* $2 */\n"); if (!silentMode) { System.out.println("-------------------------------------------------------------\n" + body); } body = body.replaceAll("&nbsp;?", ""); // sic -- need to match test code's typos body = body.replaceAll("</table>.*?<table.*?>", ""); body = body.replaceAll("</table>.*", ""); body = body.replaceAll("</?tbody>", ""); if (!silentMode) { System.out.println("-------------------------------------------------------------\n" + body); } // since I use <tr> to decide where to call the selenium object, make sure there's // no leading comment which would confuse matters: body = body.replaceAll("(<tr>)(<!--.*?-->)", "$2$1"); body = body.replaceAll("<!--\\s*", EOL + "/* "); body = body.replaceAll("\\s*-->", " */\n"); body = body.replaceAll("<tr>\\s*(<td>)?", BEGIN_SELENESE); body = body.replaceAll("</tr>", END_SELENESE + "\n"); body = body.replaceAll("</td><td>", SELENESE_TOKEN_DIVIDER); body = body.replaceAll("</?td>", ""); body = body.replaceAll("\\s*\\)", ")"); body = body.replaceAll("<td/>", ""); if (!silentMode) { System.out.println("-------------------------------------------------------------\n" + body); } String lines[] = body.split("\n"); for (int j = 0; j < lines.length;) { String line = lines[j]; if (!line.startsWith(BEGIN_SELENESE)) { java.append(line); j++; } else { j = XlateSeleneseStatement(java, lines, j); } java.append("\n"); } String possibleSetup = (domain==null ? "" : "\tpublic void setUp() throws Exception {\n" + "\t\tsuper.setUp(\"" + domain + "\");\n" + "\t}\n"); if (!silentMode) { System.out.println("-------------------------------------------------------------\n" + java); } String ending = "\n\t\t\tcheckForVerificationErrors();\n\t\t}\n\t\tfinally {\n\t\t\tclearVerificationErrors();\n\t\t}\n\t}\n" + possibleSetup + "}\n"; return preamble + java.toString() + ending; } private static String makeTestName(String base) { if (base.startsWith("test")) { return base; } if (base.startsWith("Test")) { return base.replaceFirst("Test", "test"); } return "test" + base; } private static int XlateSeleneseStatement(StringBuffer java, String[] lines, int j) { return XlateSeleneseStatement(java, lines, j, true); } private static int XlateSeleneseStatement(StringBuffer java, String[] lines, int j, boolean tryCatchAllowed) { String line = lines[j]; String splitTokens[] = line.replaceFirst(BEGIN_SELENESE, "").replaceFirst(END_SELENESE, "").split(SELENESE_TOKEN_DIVIDER); String tokens[] = getValuesOrBlankStrings(splitTokens); String op = tokens[0]; if (op.equals("typeRepeated")) { lines[j] = lines[j].replaceFirst("typeRepeated", "type"); op = tokens[0] = "type"; tokens[2] = tokens[2] + tokens[2]; } if (op.startsWith("waitFor") && !op.equals("waitForCondition") && !op.equals("waitForPopUp") && !op.equals("waitForPageToLoad") ) { String conditionCkVarName = "sawCondition" + j; java.append("\t\t\tboolean " + conditionCkVarName + " = false;"+ EOL) .append("for (int second = 0; second < 60; second++) {" + EOL) .append("\ttry {" + EOL) .append("\t\tif ("); lines[j] = lines[j].replaceFirst("waitFor", "assert"); StringBuffer testStatementSB = new StringBuffer(); XlateSeleneseStatement(testStatementSB, lines, j, false); String testStatement = testStatementSB.toString(); if (testStatement.matches("^/\\*.*\\*/$")) { // oops -- the translator returns a comment and when it cannot figure out how to translate something. // a comment in this context will not do. Arbitrarily add "false" so that the output will at least compile: testStatement += " false"; } testStatement = testStatement.replaceAll("\t//.*", ""); testStatement = testStatement.replaceFirst("^\\s*", ""); if (testStatement.startsWith("assertTrue")) { testStatement = testStatement.replaceFirst("assertTrue", ""); } else if (testStatement.startsWith("assertEquals")) { testStatement = testStatement.replaceFirst("assertEquals", "seleniumEquals"); } else if (testStatement.startsWith("assertNotEquals")) { testStatement = testStatement.replaceFirst("assertNotEquals", "!seleniumEquals"); } testStatement = testStatement.replaceFirst(";$", ""); java.append(testStatement) .append(") {" + EOL) .append("\t\t\t" + conditionCkVarName + " = true;"+ EOL) .append("\t\t\tbreak;" + EOL) .append("\t\t}" + EOL) .append("\t}" + EOL) .append("\tcatch (Exception ignore) {" + EOL) .append("\t}" + EOL) .append("\tpause(1000);" + EOL) .append("}" + EOL) .append("assertTrue(" + conditionCkVarName + ");" + EOL); } else if (op.matches("setTimeout")) { timeOut = Integer.parseInt(tokens[1]); } else if (op.matches(".*(Error|Failure)OnNext") || op.matches("verify(Element)?(Not)?(Editable|Visible|Present|Selected)")) { String throwCkVarName = "sawThrow" + j; if (tryCatchAllowed) { java.append(EOL + "boolean " + throwCkVarName + " = false;" + EOL + "try {" + EOL + "\t"); } boolean throwExpected; if (op.indexOf("ErrorOnNext") != -1 || op.indexOf("FailureOnNext") != -1) { throwExpected = true; j++; } else { java.append("// originally " + tokens[0] + "|" + tokens[1] + "|" + tokens[2] + EOL); throwExpected = false; } String wrapper = (lines[j].startsWith(BEGIN_SELENESE + "verify")) ? "verify" : "assert"; lines[j] = lines[j].replaceFirst("verify", "assert"); StringBuffer testStatement = new StringBuffer(); XlateSeleneseStatement(testStatement, lines, j, false); // need an exception to catch; \t is to avoid changing commented-out pre-xlation line java.append(testStatement.toString().replaceFirst("\tverify", "\tassert")); if (tryCatchAllowed) { java.append(EOL + "}" + EOL + "catch (Throwable e) {" + EOL + "\t" + "" + throwCkVarName + " = true;" + EOL + "}" + EOL + wrapper + (throwExpected ? "True" : "False") + "(" + throwCkVarName + ");" + EOL); } } else { java.append(XlateSeleneseStatementTokens(op, tokens, line)); } return j+1; } private static String XlateSeleneseStatementTokens(String op, String[] tokens, String oldLine) { boolean isBoolean = isBoolean(op); String commentedSelenese = "\t\t\t// " + oldLine .replaceFirst(BEGIN_SELENESE, "") .replaceFirst(END_SELENESE, "") .replaceAll(SELENESE_TOKEN_DIVIDER, "|") + EOL; String beginning = commentedSelenese; String ending = ";"; if (op.equals("echo")) { return beginning.replaceFirst("\n", "") + ": op not meaningful from rc client"; } if (op.endsWith("AndWait")) { ending += EOL + "selenium.waitForPageToLoad(\"" + timeOut + "\");"; op = op.replaceFirst("AndWait", ""); tokens[0] = tokens[0].replaceFirst("AndWait", ""); } if (op.equals("storeText")) { return beginning + "String " + tokens[2] + " = selenium.getText(" + quote(tokens[1]) + ");"; } if (op.equals("storeTextLength")) { return beginning + "Integer " + tokens[2] + " = new Integer(selenium.getText(" + quote(tokens[1]) + ").length());"; } if (op.equals("store")) { return beginning + possiblyDeclare(isBoolean, tokens[2]) + " = " + XlateSeleneseArgument(tokens[1]) + ";"; } if (op.equals("storeAttribute")) { return beginning + possiblyDeclare(false, tokens[2]) + " = selenium.getAttribute(" + XlateSeleneseArgument(tokens[1]) + ");"; } if (op.equals("storeBodyText")) { return beginning + possiblyDeclare(false, tokens[1]) + " = this.getText();"; } if (op.equals("storeValue")) { if (tokens[2].equals("")) { return beginning + possiblyDeclare(false, tokens[1]) + " = this.getText();"; } return beginning + possiblyDeclare(false, tokens[2]) + " = selenium.getValue(" + XlateSeleneseArgument(tokens[1]) + ");"; } if (op.startsWith("store")) { return beginning + possiblyDeclare(isBoolean, tokens[1]) + " = " + (op.endsWith("NotPresent") ? "!" : "") + "selenium." + (isBoolean ? "is" : "get") + op.replaceFirst("store", "") + "();"; } if (op.startsWith("verify") || op.startsWith("assert")) { String middle; if (op.startsWith("verify")) { beginning += "verifyEquals("; } else { beginning += "assertEquals("; } ending = ")" + ending; op = op.replaceFirst("assert|verify", ""); if (op.equals("ElementPresent") || op.equals("ElementNotPresent") || op.equals("TextPresent") || op.equals("TextNotPresent") || op.equals("Checked") || op.equals("NotChecked") || op.equals("Selected") || op.equals("NotSelected") || op.equals("Editable") || op.equals("NotEditable") || op.equals("Visible") || op.equals("NotVisible")) { String possibleInversion = ""; if (op.indexOf("Not")!=-1) { possibleInversion = "!"; op = op.replaceFirst("Not", ""); } if (op.equals("Selected")) { if (tokens[2].equals("")) { return commentedSelenese + "fail(\"No option selected\");"; } return "\t\t\tassertEquals(" + XlateSeleneseArgument(getSelectOptionLocatorValue(tokens[2])) + ", selenium.getSelected" + getSelectGetterFlavor(tokens[2]) + "(" + XlateSeleneseArgument(tokens[1]) + "));"; } return "\t\t\tassertTrue(" + possibleInversion + "selenium.is" + op + "(" + XlateSeleneseArgument(tokens[1]) + "));"; } if (op.equals("SomethingSelected")) { return commentedSelenese + "assertTrue(selenium.getSelectedIndexes(" + XlateSeleneseArgument(tokens[1]) + ").length != 0);"; } if (op.equals("NotSomethingSelected")) { return commentedSelenese + "try {selenium.getSelectedIndexes(" + XlateSeleneseArgument(tokens[1]) + ");} catch(Throwable e) {}"; } if (op.startsWith("Not")) { beginning = invertAssertion(beginning); op = op.replaceFirst("Not", ""); } if (op.equals("TextLength")) { middle = XlateSeleneseArgument(tokens[2]) + ", \"\" + selenium.getText(" + XlateSeleneseArgument(tokens[1]) + ").length()"; } else if (op.equals("Confirmation") || op.equals("HtmlSource") || op.equals("Location")) { middle = XlateSeleneseArgument(tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Title")) { middle = XlateSeleneseArgument("*" + tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Value") || op.equals("CursorPosition") || op.equals("Attribute") || op.matches("^Select.*[^s]$") || op.equals("Text")) { middle = XlateSeleneseArgument(tokens[2]) + ", selenium.get" + op + "(" + XlateSeleneseArgument(tokens[1]) + ")"; } else if (op.equals("Alert") || op.equals("Prompt")) { middle = XlateSeleneseArgument(tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Expression")) { middle = XlateSeleneseArgument(tokens[1]) + ", " + XlateSeleneseArgument(tokens[2]); } else if (op.equals("ErrorOnNext") || op.equals("FailureOnNext")) { String t = "these line-spanning ops should be handled by the caller: " + oldLine; if (dontThrowOnTranslationDifficulties ) { return "// " + t; } throw new RuntimeException(t); } - else if (op.equals("ValueRepeated")) { + else if (op.equals("ValueRepeated") + || op.equals("modalDialogTest")) { return "// skipped undocumented " + oldLine; } else if (op.matches("^Select.*s$")) { String tmpArrayVarName = newTmpName(); beginning = BOL + declareAndInitArray(tmpArrayVarName, tokens[2]) + "\n" + beginning; middle = tmpArrayVarName + ", selenium.get" + op + "(" + XlateSeleneseArgument(tokens[1]) + ")"; } else if (op.equals("Table")) { middle = XlateSeleneseArgument(tokens[2]) + ", selenium.get" + op + "(" + XlateSeleneseArgument(tokens[1]) + ")"; } else if (op.equals("ElementIndex")) { middle = XlateSeleneseArgument(tokens[2]) + ", selenium.get" + op + "(" + XlateSeleneseArgument(tokens[1]) + ")"; } else if (op.matches("^All.*s$")) { middle = XlateSeleneseArgument(tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Cookie")) { middle = XlateSeleneseArgument(tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Ordered")) { middle = true + ", selenium.is" + op + "(" + XlateSeleneseArgument(tokens[1]) + ", " + XlateSeleneseArgument(tokens[2]) + ")"; } else { String possibleInversion = ""; if (op.indexOf("Not")!=-1) { possibleInversion = "!"; op = op.replaceFirst("Not", ""); } return commentedSelenese + "assertTrue(" + possibleInversion + "selenium.is" + op + "());"; } return beginning + middle + ending; } if (op.equals("pause")) { return beginning + op + "(" + tokens[1] + ")" + ending; } - if (op.equals("ValueRepeated")) { + if (op.equals("modalDialogTest") + || op.equals("ValueRepeated") + ) { return "// skipped undocumented, unsupported op in " + oldLine; } if (op.equals("open")) { recordFirstDomain(tokens[1]); tokens[1] = possiblyAdjustOpenURL(tokens[1]); } return beginning + XlateSeleneseStatementDefault(funcArgCounts.get(op), "selenium", tokens) + ending; } private static String possiblyAdjustOpenURL(String url) { if (url.startsWith("../tests/") && packageName.equals("com.thoughtworks.selenium.corebased")) { System.out.println("Switching to absolute URLs for selenium core-based tests so as to avoid breaking proxy injection mode"); url = url.replaceFirst("^../", "/selenium-server/"); } return url; } private static String getSelectOptionLocatorValue(String optionLocator) { return optionLocator.replaceFirst(".*=", ""); } private static String getSelectGetterFlavor(String optionLocator) { String selectGetterFlavor; selectGetterFlavor = optionLocator.replaceFirst("=.*", ""); selectGetterFlavor = selectGetterFlavor.replaceFirst("^(.)", selectGetterFlavor.substring(0, 1).toUpperCase()); if (!selectGetterFlavor.equals("Index") && !selectGetterFlavor.equals("Label") && !selectGetterFlavor.equals("Value") && !selectGetterFlavor.equals("Id")) { selectGetterFlavor = "Label"; } return selectGetterFlavor; } private static void recordFirstDomain(String urlToOpen) { if (domain!=null) { return; // first domain already recorded, apparently } if (urlToOpen.indexOf("//")==-1) { return; // apparently no protocol, so I'm not sure how to find the domain } domain = urlToOpen.replaceFirst("://", ":::") // get those slashes out of the way, so I don't need to use (<?/)/[^/] .replaceFirst("/.*", "") .replaceFirst("\\?.*", "") .replaceFirst(":::", "://"); // put the slashes back } private static String declareAndInitArray(String name, String commaSeparatedValue) { String DIVIDER = ">>>>>>>><<<<<>>>>>>"; commaSeparatedValue = commaSeparatedValue.replaceAll("([^\\\\]),", "$1" + DIVIDER); // run twice because the pattern can overlap commaSeparatedValue = commaSeparatedValue.replaceAll("([^\\\\])\\\\\\\\,", "$1,"); commaSeparatedValue = commaSeparatedValue.replaceAll("([^\\\\])\\\\\\\\,", "$1,"); boolean trailingEmptyValue = false; String BOGUS_EXTRA_VALUE_SO_SPLIT_WILL_ALLOCATE_FINAL_ENTRY = "dummy"; if (commaSeparatedValue.lastIndexOf(DIVIDER) == commaSeparatedValue.length() - DIVIDER.length()) { trailingEmptyValue = true; commaSeparatedValue += BOGUS_EXTRA_VALUE_SO_SPLIT_WILL_ALLOCATE_FINAL_ENTRY; } String vals[] = commaSeparatedValue.split(DIVIDER); if (trailingEmptyValue) { vals[vals.length - 1] = ""; } String declaration = "String[] " + name + " = {"; for (int j = 0; j < vals.length; j++) { if (j > 0) { declaration += ", "; } declaration += "\"" + vals[j] + "\""; } declaration += "};"; return declaration; } private static String newTmpName() { return "tmp" + varNameSeed ++; } private static String invertAssertion(String s) { if (s.indexOf("Equals") != -1) { return s.replaceFirst("Equals", "NotEquals"); } //assert s.indexOf("True") != -1; return s.replaceFirst("True", "False"); } private static String[] getValuesOrBlankStrings(String[] splitTokens) { String[] valuesOrBlankStrings = { "", "", "" }; valuesOrBlankStrings[0] = splitTokens[0]; valuesOrBlankStrings[1] = splitTokens.length > 1 ? splitTokens[1] : ""; valuesOrBlankStrings[2] = splitTokens.length > 2 ? splitTokens[2] : ""; return valuesOrBlankStrings; } protected static String quote(String value) { return "\"" + value.replaceAll("\"", "\\\"") + "\""; } private static String XlateSeleneseStatementDefault(int expectedArgCount, String objName, String[] tokens) { StringBuffer sb = new StringBuffer(objName); sb.append(".") .append(tokens[0]) .append("(") .append(XlateSeleneseArguments(expectedArgCount, tokens)) .append(")"); return sb.toString(); } private static String XlateSeleneseArguments(int expectedArgCount, String[] tokens) { StringBuffer sb = new StringBuffer(); for (int j = 1; j < tokens.length && j <= expectedArgCount; j++) { if (j > 1) { sb.append(", "); } sb.append(XlateSeleneseArgument(tokens[j])); } return sb.toString(); } private static String XlateSeleneseArgument(String oldArg) { String arg = oldArg.replaceAll("\"", "\\\\\""); arg = arg.replaceFirst("^", "\""); arg = arg.replaceFirst("$", "\""); if (arg.startsWith("\"javascript{")) { arg = arg.replaceFirst("^\"javascript\\{(.*)\\}\"$", "$1"); arg = arg.replaceAll("storedVars\\['(.*?)'\\]", "\" + $1 + \""); arg = "selenium.getEval(\"" + arg + "\")"; } arg = arg.replaceAll("\\$\\{(.*?)}", "\" + $1 + \""); arg = arg.replaceAll(" \\+ \"\"", ""); arg = arg.replaceAll("\"\" \\+ ", ""); return //"\n/*" + oldArg + "*/" + arg; } private static String ReadFileContents(File f) throws IOException { FileReader input = new FileReader(f); StringBuffer sb = new StringBuffer(); while (true) { int c = input.read(); if (c==-1) { break; } sb.append((char)c); } return sb.toString(); } private static File openFile(String fileName) { File f = new File(fileName); return f; } private static void Usage(String errorMessage) { System.err.println(errorMessage + "\nUsage: XlateHtmlSeleneseToJava [-suite] [-silent] [seleneseJavaFileNameDirectory] [-package seleneseJavaPackage] [-dir seleneseHtmlDirName] [seleneseHtmlFileName1 seleneseHtmlFileName2 ...] \n" + "e.g., XlateHtmlSeleneseToJava a/b/c x/y/z/seleneseTestCase.html" + "will take x/y/z/seleneseTestCase.html as its input and produce as its output an equivalent Java" + "class at a/b/c/seleneseTestCase.java."); System.exit(-1); } }
false
true
private static String XlateSeleneseStatementTokens(String op, String[] tokens, String oldLine) { boolean isBoolean = isBoolean(op); String commentedSelenese = "\t\t\t// " + oldLine .replaceFirst(BEGIN_SELENESE, "") .replaceFirst(END_SELENESE, "") .replaceAll(SELENESE_TOKEN_DIVIDER, "|") + EOL; String beginning = commentedSelenese; String ending = ";"; if (op.equals("echo")) { return beginning.replaceFirst("\n", "") + ": op not meaningful from rc client"; } if (op.endsWith("AndWait")) { ending += EOL + "selenium.waitForPageToLoad(\"" + timeOut + "\");"; op = op.replaceFirst("AndWait", ""); tokens[0] = tokens[0].replaceFirst("AndWait", ""); } if (op.equals("storeText")) { return beginning + "String " + tokens[2] + " = selenium.getText(" + quote(tokens[1]) + ");"; } if (op.equals("storeTextLength")) { return beginning + "Integer " + tokens[2] + " = new Integer(selenium.getText(" + quote(tokens[1]) + ").length());"; } if (op.equals("store")) { return beginning + possiblyDeclare(isBoolean, tokens[2]) + " = " + XlateSeleneseArgument(tokens[1]) + ";"; } if (op.equals("storeAttribute")) { return beginning + possiblyDeclare(false, tokens[2]) + " = selenium.getAttribute(" + XlateSeleneseArgument(tokens[1]) + ");"; } if (op.equals("storeBodyText")) { return beginning + possiblyDeclare(false, tokens[1]) + " = this.getText();"; } if (op.equals("storeValue")) { if (tokens[2].equals("")) { return beginning + possiblyDeclare(false, tokens[1]) + " = this.getText();"; } return beginning + possiblyDeclare(false, tokens[2]) + " = selenium.getValue(" + XlateSeleneseArgument(tokens[1]) + ");"; } if (op.startsWith("store")) { return beginning + possiblyDeclare(isBoolean, tokens[1]) + " = " + (op.endsWith("NotPresent") ? "!" : "") + "selenium." + (isBoolean ? "is" : "get") + op.replaceFirst("store", "") + "();"; } if (op.startsWith("verify") || op.startsWith("assert")) { String middle; if (op.startsWith("verify")) { beginning += "verifyEquals("; } else { beginning += "assertEquals("; } ending = ")" + ending; op = op.replaceFirst("assert|verify", ""); if (op.equals("ElementPresent") || op.equals("ElementNotPresent") || op.equals("TextPresent") || op.equals("TextNotPresent") || op.equals("Checked") || op.equals("NotChecked") || op.equals("Selected") || op.equals("NotSelected") || op.equals("Editable") || op.equals("NotEditable") || op.equals("Visible") || op.equals("NotVisible")) { String possibleInversion = ""; if (op.indexOf("Not")!=-1) { possibleInversion = "!"; op = op.replaceFirst("Not", ""); } if (op.equals("Selected")) { if (tokens[2].equals("")) { return commentedSelenese + "fail(\"No option selected\");"; } return "\t\t\tassertEquals(" + XlateSeleneseArgument(getSelectOptionLocatorValue(tokens[2])) + ", selenium.getSelected" + getSelectGetterFlavor(tokens[2]) + "(" + XlateSeleneseArgument(tokens[1]) + "));"; } return "\t\t\tassertTrue(" + possibleInversion + "selenium.is" + op + "(" + XlateSeleneseArgument(tokens[1]) + "));"; } if (op.equals("SomethingSelected")) { return commentedSelenese + "assertTrue(selenium.getSelectedIndexes(" + XlateSeleneseArgument(tokens[1]) + ").length != 0);"; } if (op.equals("NotSomethingSelected")) { return commentedSelenese + "try {selenium.getSelectedIndexes(" + XlateSeleneseArgument(tokens[1]) + ");} catch(Throwable e) {}"; } if (op.startsWith("Not")) { beginning = invertAssertion(beginning); op = op.replaceFirst("Not", ""); } if (op.equals("TextLength")) { middle = XlateSeleneseArgument(tokens[2]) + ", \"\" + selenium.getText(" + XlateSeleneseArgument(tokens[1]) + ").length()"; } else if (op.equals("Confirmation") || op.equals("HtmlSource") || op.equals("Location")) { middle = XlateSeleneseArgument(tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Title")) { middle = XlateSeleneseArgument("*" + tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Value") || op.equals("CursorPosition") || op.equals("Attribute") || op.matches("^Select.*[^s]$") || op.equals("Text")) { middle = XlateSeleneseArgument(tokens[2]) + ", selenium.get" + op + "(" + XlateSeleneseArgument(tokens[1]) + ")"; } else if (op.equals("Alert") || op.equals("Prompt")) { middle = XlateSeleneseArgument(tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Expression")) { middle = XlateSeleneseArgument(tokens[1]) + ", " + XlateSeleneseArgument(tokens[2]); } else if (op.equals("ErrorOnNext") || op.equals("FailureOnNext")) { String t = "these line-spanning ops should be handled by the caller: " + oldLine; if (dontThrowOnTranslationDifficulties ) { return "// " + t; } throw new RuntimeException(t); } else if (op.equals("ValueRepeated")) { return "// skipped undocumented " + oldLine; } else if (op.matches("^Select.*s$")) { String tmpArrayVarName = newTmpName(); beginning = BOL + declareAndInitArray(tmpArrayVarName, tokens[2]) + "\n" + beginning; middle = tmpArrayVarName + ", selenium.get" + op + "(" + XlateSeleneseArgument(tokens[1]) + ")"; } else if (op.equals("Table")) { middle = XlateSeleneseArgument(tokens[2]) + ", selenium.get" + op + "(" + XlateSeleneseArgument(tokens[1]) + ")"; } else if (op.equals("ElementIndex")) { middle = XlateSeleneseArgument(tokens[2]) + ", selenium.get" + op + "(" + XlateSeleneseArgument(tokens[1]) + ")"; } else if (op.matches("^All.*s$")) { middle = XlateSeleneseArgument(tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Cookie")) { middle = XlateSeleneseArgument(tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Ordered")) { middle = true + ", selenium.is" + op + "(" + XlateSeleneseArgument(tokens[1]) + ", " + XlateSeleneseArgument(tokens[2]) + ")"; } else { String possibleInversion = ""; if (op.indexOf("Not")!=-1) { possibleInversion = "!"; op = op.replaceFirst("Not", ""); } return commentedSelenese + "assertTrue(" + possibleInversion + "selenium.is" + op + "());"; } return beginning + middle + ending; } if (op.equals("pause")) { return beginning + op + "(" + tokens[1] + ")" + ending; } if (op.equals("ValueRepeated")) { return "// skipped undocumented, unsupported op in " + oldLine; } if (op.equals("open")) { recordFirstDomain(tokens[1]); tokens[1] = possiblyAdjustOpenURL(tokens[1]); } return beginning + XlateSeleneseStatementDefault(funcArgCounts.get(op), "selenium", tokens) + ending; }
private static String XlateSeleneseStatementTokens(String op, String[] tokens, String oldLine) { boolean isBoolean = isBoolean(op); String commentedSelenese = "\t\t\t// " + oldLine .replaceFirst(BEGIN_SELENESE, "") .replaceFirst(END_SELENESE, "") .replaceAll(SELENESE_TOKEN_DIVIDER, "|") + EOL; String beginning = commentedSelenese; String ending = ";"; if (op.equals("echo")) { return beginning.replaceFirst("\n", "") + ": op not meaningful from rc client"; } if (op.endsWith("AndWait")) { ending += EOL + "selenium.waitForPageToLoad(\"" + timeOut + "\");"; op = op.replaceFirst("AndWait", ""); tokens[0] = tokens[0].replaceFirst("AndWait", ""); } if (op.equals("storeText")) { return beginning + "String " + tokens[2] + " = selenium.getText(" + quote(tokens[1]) + ");"; } if (op.equals("storeTextLength")) { return beginning + "Integer " + tokens[2] + " = new Integer(selenium.getText(" + quote(tokens[1]) + ").length());"; } if (op.equals("store")) { return beginning + possiblyDeclare(isBoolean, tokens[2]) + " = " + XlateSeleneseArgument(tokens[1]) + ";"; } if (op.equals("storeAttribute")) { return beginning + possiblyDeclare(false, tokens[2]) + " = selenium.getAttribute(" + XlateSeleneseArgument(tokens[1]) + ");"; } if (op.equals("storeBodyText")) { return beginning + possiblyDeclare(false, tokens[1]) + " = this.getText();"; } if (op.equals("storeValue")) { if (tokens[2].equals("")) { return beginning + possiblyDeclare(false, tokens[1]) + " = this.getText();"; } return beginning + possiblyDeclare(false, tokens[2]) + " = selenium.getValue(" + XlateSeleneseArgument(tokens[1]) + ");"; } if (op.startsWith("store")) { return beginning + possiblyDeclare(isBoolean, tokens[1]) + " = " + (op.endsWith("NotPresent") ? "!" : "") + "selenium." + (isBoolean ? "is" : "get") + op.replaceFirst("store", "") + "();"; } if (op.startsWith("verify") || op.startsWith("assert")) { String middle; if (op.startsWith("verify")) { beginning += "verifyEquals("; } else { beginning += "assertEquals("; } ending = ")" + ending; op = op.replaceFirst("assert|verify", ""); if (op.equals("ElementPresent") || op.equals("ElementNotPresent") || op.equals("TextPresent") || op.equals("TextNotPresent") || op.equals("Checked") || op.equals("NotChecked") || op.equals("Selected") || op.equals("NotSelected") || op.equals("Editable") || op.equals("NotEditable") || op.equals("Visible") || op.equals("NotVisible")) { String possibleInversion = ""; if (op.indexOf("Not")!=-1) { possibleInversion = "!"; op = op.replaceFirst("Not", ""); } if (op.equals("Selected")) { if (tokens[2].equals("")) { return commentedSelenese + "fail(\"No option selected\");"; } return "\t\t\tassertEquals(" + XlateSeleneseArgument(getSelectOptionLocatorValue(tokens[2])) + ", selenium.getSelected" + getSelectGetterFlavor(tokens[2]) + "(" + XlateSeleneseArgument(tokens[1]) + "));"; } return "\t\t\tassertTrue(" + possibleInversion + "selenium.is" + op + "(" + XlateSeleneseArgument(tokens[1]) + "));"; } if (op.equals("SomethingSelected")) { return commentedSelenese + "assertTrue(selenium.getSelectedIndexes(" + XlateSeleneseArgument(tokens[1]) + ").length != 0);"; } if (op.equals("NotSomethingSelected")) { return commentedSelenese + "try {selenium.getSelectedIndexes(" + XlateSeleneseArgument(tokens[1]) + ");} catch(Throwable e) {}"; } if (op.startsWith("Not")) { beginning = invertAssertion(beginning); op = op.replaceFirst("Not", ""); } if (op.equals("TextLength")) { middle = XlateSeleneseArgument(tokens[2]) + ", \"\" + selenium.getText(" + XlateSeleneseArgument(tokens[1]) + ").length()"; } else if (op.equals("Confirmation") || op.equals("HtmlSource") || op.equals("Location")) { middle = XlateSeleneseArgument(tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Title")) { middle = XlateSeleneseArgument("*" + tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Value") || op.equals("CursorPosition") || op.equals("Attribute") || op.matches("^Select.*[^s]$") || op.equals("Text")) { middle = XlateSeleneseArgument(tokens[2]) + ", selenium.get" + op + "(" + XlateSeleneseArgument(tokens[1]) + ")"; } else if (op.equals("Alert") || op.equals("Prompt")) { middle = XlateSeleneseArgument(tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Expression")) { middle = XlateSeleneseArgument(tokens[1]) + ", " + XlateSeleneseArgument(tokens[2]); } else if (op.equals("ErrorOnNext") || op.equals("FailureOnNext")) { String t = "these line-spanning ops should be handled by the caller: " + oldLine; if (dontThrowOnTranslationDifficulties ) { return "// " + t; } throw new RuntimeException(t); } else if (op.equals("ValueRepeated") || op.equals("modalDialogTest")) { return "// skipped undocumented " + oldLine; } else if (op.matches("^Select.*s$")) { String tmpArrayVarName = newTmpName(); beginning = BOL + declareAndInitArray(tmpArrayVarName, tokens[2]) + "\n" + beginning; middle = tmpArrayVarName + ", selenium.get" + op + "(" + XlateSeleneseArgument(tokens[1]) + ")"; } else if (op.equals("Table")) { middle = XlateSeleneseArgument(tokens[2]) + ", selenium.get" + op + "(" + XlateSeleneseArgument(tokens[1]) + ")"; } else if (op.equals("ElementIndex")) { middle = XlateSeleneseArgument(tokens[2]) + ", selenium.get" + op + "(" + XlateSeleneseArgument(tokens[1]) + ")"; } else if (op.matches("^All.*s$")) { middle = XlateSeleneseArgument(tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Cookie")) { middle = XlateSeleneseArgument(tokens[1]) + ", selenium.get" + op + "()"; } else if (op.equals("Ordered")) { middle = true + ", selenium.is" + op + "(" + XlateSeleneseArgument(tokens[1]) + ", " + XlateSeleneseArgument(tokens[2]) + ")"; } else { String possibleInversion = ""; if (op.indexOf("Not")!=-1) { possibleInversion = "!"; op = op.replaceFirst("Not", ""); } return commentedSelenese + "assertTrue(" + possibleInversion + "selenium.is" + op + "());"; } return beginning + middle + ending; } if (op.equals("pause")) { return beginning + op + "(" + tokens[1] + ")" + ending; } if (op.equals("modalDialogTest") || op.equals("ValueRepeated") ) { return "// skipped undocumented, unsupported op in " + oldLine; } if (op.equals("open")) { recordFirstDomain(tokens[1]); tokens[1] = possiblyAdjustOpenURL(tokens[1]); } return beginning + XlateSeleneseStatementDefault(funcArgCounts.get(op), "selenium", tokens) + ending; }
diff --git a/PartManager.java b/PartManager.java index 4d38134..c2a22de 100644 --- a/PartManager.java +++ b/PartManager.java @@ -1,210 +1,210 @@ import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class PartManager extends JPanel { private PartsClient myClient; private JLabel pName; private JLabel pNumber; private JLabel pInfo; private JLabel pEdit; private JLabel pEdit2; private JTextField tName; private JTextField tNumber; private JTextField tInfo; private JTextField tEdit; private JButton create; private JButton change; private JButton delete; private JScrollPane scroll; private JPanel parts; private JLabel msg; public PartManager( PartsClient pc ){ myClient = pc; pName = new JLabel("Part Name: "); pNumber = new JLabel("Part Number: "); pInfo = new JLabel("Part Info: "); pEdit = new JLabel("Number of part to be changed/deleted: "); pEdit2 = new JLabel("Part will be changed to new part above"); tName = new JTextField(10); tNumber = new JTextField(10); tInfo = new JTextField(10); tEdit = new JTextField(10); create = new JButton("Create"); change = new JButton("Change"); delete = new JButton("Delete"); msg = new JLabel(""); //jscrollpane for list of parts parts = new JPanel(); parts.setLayout( new BoxLayout( parts, BoxLayout.Y_AXIS ) ); scroll = new JScrollPane(parts); //layout GUI setLayout( new GridBagLayout() ); GridBagConstraints c = new GridBagConstraints(); //parts scroll pane c.fill = c.BOTH; c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 0; c.gridwidth = 2; c.gridheight = 10; add( scroll, c ); //adding parts c.fill = c.HORIZONTAL; c.insets = new Insets(20,10,0,0); c.gridx = 2; c.gridy = 0; c.weightx = 0; c.gridwidth = 1; c.gridheight = 1; add( pName, c ); c.gridx = 2; c.gridy = 1; add( pNumber, c ); c.gridx = 2; c.gridy = 2; add( pInfo, c ); c.gridx = 3; c.gridy = 0; add( tName, c ); c.gridx = 3; c.gridy = 1; add( tNumber, c ); c.gridx = 3; c.gridy = 2; add( tInfo, c ); c.gridx = 4; c.gridy = 1; add( create, c ); //changing/deleting parts c.gridx = 2; c.gridy = 4; add( pEdit, c ); c.gridx = 3; c.gridy = 3; add( pEdit2, c ); c.gridx = 3; c.gridy = 4; add( tEdit, c ); c.gridheight = 1; c.gridx = 4; c.gridy = 3; add( change, c ); c.gridx = 4; c.gridy = 4; add( delete, c ); //messages c.gridx = 2; c.gridy = 5; c.gridwidth = 3; add( msg, c ); //action listeners for buttons create.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tName.getText().equals("") && !tInfo.getText().equals("") && !tNumber.getText().equals("") ) { try{ //add part to server myClient.getCom().write( new NewPartMsg( new Part( tName.getText(), tInfo.getText(), (int)Integer.parseInt( tNumber.getText() ) ) ) ); //display parts list requestParts(); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for Part Number" ); } } else { msg.setText( "Please enter all part information" ); } } }); change.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tName.getText().equals("") && !tInfo.getText().equals("") && !tNumber.getText().equals("") && !tEdit.getText().equals("") ) { try{ //replace part number X with new part - myClient.getCom().write( new ChangePartMsg( (int)Integer.parseInt( tEdit.getText() ), new Part( tName.getText(), tInfo.getText(), Integer.parseInt( tNumber.getText() ) ) ) ); + myClient.getCom().write( new ChangePartMsg( (int)Integer.parseInt( tEdit.getText() ), new Part( tName.getText(), tInfo.getText(), (int)Integer.parseInt( tNumber.getText() ) ) ) ); //display parts list requestParts(); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for part to be changed" ); } } else if( tEdit.getText().equals("") ) { msg.setText( "Please enter part number of part to be changed." ); } else { msg.setText( "Please enter all part information" ); } } }); delete.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tEdit.getText().equals("") ) { try { //delete the part on the server - myClient.getCom().write( new DeletePartMsg( Integer.parseInt( tEdit.getText() ) ) ); + myClient.getCom().write( new DeletePartMsg( (int)Integer.parseInt( tEdit.getText() ) ) ); //display parts list requestParts(); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for part to be deleted" ); } } else { msg.setText( "Please enter part number of part to be deleted." ); } } }); } public void requestParts(){ //get updated parts list myClient.getCom().write( new PartListMsg() ); } public void displayParts(){ //remove current list from the panel parts.removeAll(); //add new list to panel ArrayList<Part> temp = myClient.getParts(); for( Part p : temp ){ //maybe use string builder in future? parts.add( new JLabel( p.getNumber() + " - " + p.getName() + " - " + p.getDescription() ) ); } validate(); repaint(); } public void setMsg( String s ){ msg.setText(s); } }
false
true
public PartManager( PartsClient pc ){ myClient = pc; pName = new JLabel("Part Name: "); pNumber = new JLabel("Part Number: "); pInfo = new JLabel("Part Info: "); pEdit = new JLabel("Number of part to be changed/deleted: "); pEdit2 = new JLabel("Part will be changed to new part above"); tName = new JTextField(10); tNumber = new JTextField(10); tInfo = new JTextField(10); tEdit = new JTextField(10); create = new JButton("Create"); change = new JButton("Change"); delete = new JButton("Delete"); msg = new JLabel(""); //jscrollpane for list of parts parts = new JPanel(); parts.setLayout( new BoxLayout( parts, BoxLayout.Y_AXIS ) ); scroll = new JScrollPane(parts); //layout GUI setLayout( new GridBagLayout() ); GridBagConstraints c = new GridBagConstraints(); //parts scroll pane c.fill = c.BOTH; c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 0; c.gridwidth = 2; c.gridheight = 10; add( scroll, c ); //adding parts c.fill = c.HORIZONTAL; c.insets = new Insets(20,10,0,0); c.gridx = 2; c.gridy = 0; c.weightx = 0; c.gridwidth = 1; c.gridheight = 1; add( pName, c ); c.gridx = 2; c.gridy = 1; add( pNumber, c ); c.gridx = 2; c.gridy = 2; add( pInfo, c ); c.gridx = 3; c.gridy = 0; add( tName, c ); c.gridx = 3; c.gridy = 1; add( tNumber, c ); c.gridx = 3; c.gridy = 2; add( tInfo, c ); c.gridx = 4; c.gridy = 1; add( create, c ); //changing/deleting parts c.gridx = 2; c.gridy = 4; add( pEdit, c ); c.gridx = 3; c.gridy = 3; add( pEdit2, c ); c.gridx = 3; c.gridy = 4; add( tEdit, c ); c.gridheight = 1; c.gridx = 4; c.gridy = 3; add( change, c ); c.gridx = 4; c.gridy = 4; add( delete, c ); //messages c.gridx = 2; c.gridy = 5; c.gridwidth = 3; add( msg, c ); //action listeners for buttons create.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tName.getText().equals("") && !tInfo.getText().equals("") && !tNumber.getText().equals("") ) { try{ //add part to server myClient.getCom().write( new NewPartMsg( new Part( tName.getText(), tInfo.getText(), (int)Integer.parseInt( tNumber.getText() ) ) ) ); //display parts list requestParts(); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for Part Number" ); } } else { msg.setText( "Please enter all part information" ); } } }); change.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tName.getText().equals("") && !tInfo.getText().equals("") && !tNumber.getText().equals("") && !tEdit.getText().equals("") ) { try{ //replace part number X with new part myClient.getCom().write( new ChangePartMsg( (int)Integer.parseInt( tEdit.getText() ), new Part( tName.getText(), tInfo.getText(), Integer.parseInt( tNumber.getText() ) ) ) ); //display parts list requestParts(); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for part to be changed" ); } } else if( tEdit.getText().equals("") ) { msg.setText( "Please enter part number of part to be changed." ); } else { msg.setText( "Please enter all part information" ); } } }); delete.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tEdit.getText().equals("") ) { try { //delete the part on the server myClient.getCom().write( new DeletePartMsg( Integer.parseInt( tEdit.getText() ) ) ); //display parts list requestParts(); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for part to be deleted" ); } } else { msg.setText( "Please enter part number of part to be deleted." ); } } }); }
public PartManager( PartsClient pc ){ myClient = pc; pName = new JLabel("Part Name: "); pNumber = new JLabel("Part Number: "); pInfo = new JLabel("Part Info: "); pEdit = new JLabel("Number of part to be changed/deleted: "); pEdit2 = new JLabel("Part will be changed to new part above"); tName = new JTextField(10); tNumber = new JTextField(10); tInfo = new JTextField(10); tEdit = new JTextField(10); create = new JButton("Create"); change = new JButton("Change"); delete = new JButton("Delete"); msg = new JLabel(""); //jscrollpane for list of parts parts = new JPanel(); parts.setLayout( new BoxLayout( parts, BoxLayout.Y_AXIS ) ); scroll = new JScrollPane(parts); //layout GUI setLayout( new GridBagLayout() ); GridBagConstraints c = new GridBagConstraints(); //parts scroll pane c.fill = c.BOTH; c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 0; c.gridwidth = 2; c.gridheight = 10; add( scroll, c ); //adding parts c.fill = c.HORIZONTAL; c.insets = new Insets(20,10,0,0); c.gridx = 2; c.gridy = 0; c.weightx = 0; c.gridwidth = 1; c.gridheight = 1; add( pName, c ); c.gridx = 2; c.gridy = 1; add( pNumber, c ); c.gridx = 2; c.gridy = 2; add( pInfo, c ); c.gridx = 3; c.gridy = 0; add( tName, c ); c.gridx = 3; c.gridy = 1; add( tNumber, c ); c.gridx = 3; c.gridy = 2; add( tInfo, c ); c.gridx = 4; c.gridy = 1; add( create, c ); //changing/deleting parts c.gridx = 2; c.gridy = 4; add( pEdit, c ); c.gridx = 3; c.gridy = 3; add( pEdit2, c ); c.gridx = 3; c.gridy = 4; add( tEdit, c ); c.gridheight = 1; c.gridx = 4; c.gridy = 3; add( change, c ); c.gridx = 4; c.gridy = 4; add( delete, c ); //messages c.gridx = 2; c.gridy = 5; c.gridwidth = 3; add( msg, c ); //action listeners for buttons create.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tName.getText().equals("") && !tInfo.getText().equals("") && !tNumber.getText().equals("") ) { try{ //add part to server myClient.getCom().write( new NewPartMsg( new Part( tName.getText(), tInfo.getText(), (int)Integer.parseInt( tNumber.getText() ) ) ) ); //display parts list requestParts(); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for Part Number" ); } } else { msg.setText( "Please enter all part information" ); } } }); change.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tName.getText().equals("") && !tInfo.getText().equals("") && !tNumber.getText().equals("") && !tEdit.getText().equals("") ) { try{ //replace part number X with new part myClient.getCom().write( new ChangePartMsg( (int)Integer.parseInt( tEdit.getText() ), new Part( tName.getText(), tInfo.getText(), (int)Integer.parseInt( tNumber.getText() ) ) ) ); //display parts list requestParts(); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for part to be changed" ); } } else if( tEdit.getText().equals("") ) { msg.setText( "Please enter part number of part to be changed." ); } else { msg.setText( "Please enter all part information" ); } } }); delete.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tEdit.getText().equals("") ) { try { //delete the part on the server myClient.getCom().write( new DeletePartMsg( (int)Integer.parseInt( tEdit.getText() ) ) ); //display parts list requestParts(); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for part to be deleted" ); } } else { msg.setText( "Please enter part number of part to be deleted." ); } } }); }
diff --git a/taskmodel/taskmodel-core-view/src/de/thorstenberger/taskmodel/view/CommitAction.java b/taskmodel/taskmodel-core-view/src/de/thorstenberger/taskmodel/view/CommitAction.java index 5ca5de6..c537678 100644 --- a/taskmodel/taskmodel-core-view/src/de/thorstenberger/taskmodel/view/CommitAction.java +++ b/taskmodel/taskmodel-core-view/src/de/thorstenberger/taskmodel/view/CommitAction.java @@ -1,134 +1,134 @@ /* Copyright (C) 2006 Thorsten Berger This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** * */ package de.thorstenberger.taskmodel.view; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import de.thorstenberger.taskmodel.TaskApiException; import de.thorstenberger.taskmodel.TaskModelViewDelegate; import de.thorstenberger.taskmodel.TaskModelViewDelegateObject; import de.thorstenberger.taskmodel.complex.ComplexTasklet; import de.thorstenberger.taskmodel.complex.TaskDef_Complex; /** * @author Thorsten Berger * */ public class CommitAction extends Action { Log log = LogFactory.getLog( CommitAction.class ); /* (non-Javadoc) * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages msgs = new ActionMessages(); ActionMessages errors = new ActionMessages(); int page; long id; try { id = Long.parseLong( request.getParameter( "id" ) ); page = Integer.parseInt( request.getParameter("page")==null ? "1" : request.getParameter("page") ); } catch (NumberFormatException e) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "invalid.parameter" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } TaskModelViewDelegateObject delegateObject = TaskModelViewDelegate.getDelegateObject( request.getSession().getId(), id ); if( delegateObject == null ){ errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "no.session" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } request.setAttribute( "ReturnURL", delegateObject.getReturnURL() ); TaskDef_Complex taskDef; try { taskDef = (TaskDef_Complex) delegateObject.getTaskDef(); } catch (ClassCastException e2) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "only.complexTasks.supported" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } catch (TaskApiException e3) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "misc.error", e3.getMessage() ) ); saveErrors( request, errors ); log.error( e3 ); return mapping.findForward( "error" ); } ComplexTasklet ct; try { ct = (ComplexTasklet) delegateObject.getTasklet(); } catch (ClassCastException e1) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "only.complexTasks.supported" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } catch (TaskApiException e3) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "misc.error", e3.getMessage() ) ); saveErrors( request, errors ); log.error( e3 ); return mapping.findForward( "error" ); } if( !taskDef.isActive() ){ errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "task.inactive" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } - SavePageAction.logPostData( request ); + SavePageAction.logPostData( request, ct ); // finally, commit the whole Task try { ct.submit(); } catch (IllegalStateException e) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( e.getMessage() ) ); saveErrors( request, errors ); log.info( e ); return mapping.findForward( "error" ); } return mapping.findForward( "success" ); } }
true
true
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages msgs = new ActionMessages(); ActionMessages errors = new ActionMessages(); int page; long id; try { id = Long.parseLong( request.getParameter( "id" ) ); page = Integer.parseInt( request.getParameter("page")==null ? "1" : request.getParameter("page") ); } catch (NumberFormatException e) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "invalid.parameter" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } TaskModelViewDelegateObject delegateObject = TaskModelViewDelegate.getDelegateObject( request.getSession().getId(), id ); if( delegateObject == null ){ errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "no.session" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } request.setAttribute( "ReturnURL", delegateObject.getReturnURL() ); TaskDef_Complex taskDef; try { taskDef = (TaskDef_Complex) delegateObject.getTaskDef(); } catch (ClassCastException e2) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "only.complexTasks.supported" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } catch (TaskApiException e3) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "misc.error", e3.getMessage() ) ); saveErrors( request, errors ); log.error( e3 ); return mapping.findForward( "error" ); } ComplexTasklet ct; try { ct = (ComplexTasklet) delegateObject.getTasklet(); } catch (ClassCastException e1) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "only.complexTasks.supported" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } catch (TaskApiException e3) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "misc.error", e3.getMessage() ) ); saveErrors( request, errors ); log.error( e3 ); return mapping.findForward( "error" ); } if( !taskDef.isActive() ){ errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "task.inactive" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } SavePageAction.logPostData( request ); // finally, commit the whole Task try { ct.submit(); } catch (IllegalStateException e) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( e.getMessage() ) ); saveErrors( request, errors ); log.info( e ); return mapping.findForward( "error" ); } return mapping.findForward( "success" ); }
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages msgs = new ActionMessages(); ActionMessages errors = new ActionMessages(); int page; long id; try { id = Long.parseLong( request.getParameter( "id" ) ); page = Integer.parseInt( request.getParameter("page")==null ? "1" : request.getParameter("page") ); } catch (NumberFormatException e) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "invalid.parameter" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } TaskModelViewDelegateObject delegateObject = TaskModelViewDelegate.getDelegateObject( request.getSession().getId(), id ); if( delegateObject == null ){ errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "no.session" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } request.setAttribute( "ReturnURL", delegateObject.getReturnURL() ); TaskDef_Complex taskDef; try { taskDef = (TaskDef_Complex) delegateObject.getTaskDef(); } catch (ClassCastException e2) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "only.complexTasks.supported" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } catch (TaskApiException e3) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "misc.error", e3.getMessage() ) ); saveErrors( request, errors ); log.error( e3 ); return mapping.findForward( "error" ); } ComplexTasklet ct; try { ct = (ComplexTasklet) delegateObject.getTasklet(); } catch (ClassCastException e1) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "only.complexTasks.supported" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } catch (TaskApiException e3) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "misc.error", e3.getMessage() ) ); saveErrors( request, errors ); log.error( e3 ); return mapping.findForward( "error" ); } if( !taskDef.isActive() ){ errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "task.inactive" ) ); saveErrors( request, errors ); return mapping.findForward( "error" ); } SavePageAction.logPostData( request, ct ); // finally, commit the whole Task try { ct.submit(); } catch (IllegalStateException e) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( e.getMessage() ) ); saveErrors( request, errors ); log.info( e ); return mapping.findForward( "error" ); } return mapping.findForward( "success" ); }
diff --git a/src/nerd/tuxmobil/fahrplan/congress/EventDetailFragment.java b/src/nerd/tuxmobil/fahrplan/congress/EventDetailFragment.java index 5f7440f..c7754e1 100644 --- a/src/nerd/tuxmobil/fahrplan/congress/EventDetailFragment.java +++ b/src/nerd/tuxmobil/fahrplan/congress/EventDetailFragment.java @@ -1,288 +1,289 @@ package nerd.tuxmobil.fahrplan.congress; import java.util.Locale; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Typeface; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; interface OnCloseDetailListener { public void closeDetailView(); } public class EventDetailFragment extends SherlockFragment { private final String LOG_TAG = "Detail"; private String event_id; private String title; private static String feedbackURL = "https://cccv.pentabarf.org/feedback/30C3/event/"; // + 4302.en.html private Locale locale; private Typeface boldCondensed; private Typeface black; private Typeface light; private Typeface regular; private Typeface bold; private Lecture lecture; private int day; private String subtitle; private String spkr; private String abstractt; private String descr; private String links; private Boolean sidePane = false; private boolean hasArguments = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); MyApp.LogDebug(LOG_TAG, "onCreate"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (sidePane) { return inflater.inflate(R.layout.detail_narrow, container, false); } else { return inflater.inflate(R.layout.detail, container, false); } } @Override public void setArguments(Bundle args) { super.setArguments(args); day = args.getInt("day", 0); event_id = args.getString("eventid"); title = args.getString("title"); subtitle = args.getString("subtitle"); spkr = args.getString("spkr"); abstractt = args.getString("abstract"); descr = args.getString("descr"); links = args.getString("links"); sidePane = args.getBoolean("sidepane", false); hasArguments = true; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (hasArguments) { boldCondensed = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-BoldCondensed.ttf"); black = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-Black.ttf"); light = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-Light.ttf"); regular = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-Regular.ttf"); bold = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-Bold.ttf"); locale = getResources().getConfiguration().locale; FahrplanFragment.loadLectureList(getSherlockActivity(), day, false); lecture = eventid2Lecture(event_id); TextView t = (TextView)view.findViewById(R.id.title); t.setTypeface(boldCondensed); t.setText(title); t = (TextView)view.findViewById(R.id.subtitle); t.setText(subtitle); t.setTypeface(light); if (subtitle.length() == 0) t.setVisibility(View.GONE); t = (TextView)view.findViewById(R.id.speakers); t.setTypeface(black); t.setText(spkr); t = (TextView)view.findViewById(R.id.abstractt); t.setTypeface(bold); abstractt = abstractt.replaceAll("\\[(.*?)\\]\\(([^ \\)]+).*?\\)", "<a href=\"$2\">$1</a>"); t.setText(Html.fromHtml(abstractt), TextView.BufferType.SPANNABLE); t.setMovementMethod(new LinkMovementMethod()); t = (TextView)view.findViewById(R.id.description); t.setTypeface(regular); descr = descr.replaceAll("\\[(.*?)\\]\\(([^ \\)]+).*?\\)", "<a href=\"$2\">$1</a>"); t.setText(Html.fromHtml(descr), TextView.BufferType.SPANNABLE); t.setMovementMethod(new LinkMovementMethod()); TextView l = (TextView)view.findViewById(R.id.linksSection); l.setTypeface(bold); t = (TextView)view.findViewById(R.id.links); t.setTypeface(regular); if (links.length() > 0) { MyApp.LogDebug(LOG_TAG, "show links"); l.setVisibility(View.VISIBLE); t.setVisibility(View.VISIBLE); links = links.replaceAll("\\),", ")<br>"); links = links.replaceAll("\\[(.*?)\\]\\(([^ \\)]+).*?\\)", "<a href=\"$2\">$1</a>"); t.setText(Html.fromHtml(links), TextView.BufferType.SPANNABLE); t.setMovementMethod(new LinkMovementMethod()); } else { l.setVisibility(View.GONE); t.setVisibility(View.GONE); } + getSherlockActivity().supportInvalidateOptionsMenu(); } getSherlockActivity().setResult(SherlockFragmentActivity.RESULT_CANCELED); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.detailmenu, menu); MenuItem item; if (Build.VERSION.SDK_INT < 14) { item = menu.findItem(R.id.item_add_to_calendar); if (item != null) item.setVisible(false); } if (lecture != null) { if (lecture.highlight) { item = menu.findItem(R.id.item_fav); if (item != null) item.setVisible(false); item = menu.findItem(R.id.item_unfav); if (item != null) item.setVisible(true); } if (lecture.has_alarm) { item = menu.findItem(R.id.item_set_alarm); if (item != null) item.setVisible(false); item = menu.findItem(R.id.item_clear_alarm); if (item != null) item.setVisible(true); } } if (sidePane) { item = menu.findItem(R.id.item_close); if (item != null) item.setVisible(true); } } private Lecture eventid2Lecture(String event_id) { if (MyApp.lectureList == null) return null; for (Lecture lecture : MyApp.lectureList) { if (lecture.lecture_id.equals(event_id)) { return lecture; } } return null; } void setAlarmDialog(final Lecture lecture) { LayoutInflater inflater = (LayoutInflater) getSherlockActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.reminder_dialog, (ViewGroup) getView().findViewById(R.id.layout_root)); final Spinner spinner = (Spinner) layout.findViewById(R.id.spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter .createFromResource(getSherlockActivity(), R.array.alarm_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); TextView msg = (TextView)layout.findViewById(R.id.message); msg.setText(R.string.choose_alarm_time); new AlertDialog.Builder(getSherlockActivity()).setTitle(R.string.setup_alarm).setView(layout) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { int alarm = spinner.getSelectedItemPosition(); MyApp.LogDebug(LOG_TAG, "alarm chosen: "+alarm); FahrplanMisc.addAlarm(getSherlockActivity(), lecture, alarm); getSherlockActivity().supportInvalidateOptionsMenu(); getSherlockActivity().setResult(SherlockFragmentActivity.RESULT_OK); refreshEventMarkers(); } }).setNegativeButton(android.R.string.cancel, null) .create().show(); } public void refreshEventMarkers() { SherlockFragmentActivity activity = getSherlockActivity(); if ((activity != null) && (activity instanceof OnRefreshEventMarers)) { ((OnRefreshEventMarers)activity).refreshEventMarkers(); } } public boolean onOptionsItemSelected(MenuItem item) { Lecture l; switch (item.getItemId()) { case R.id.item_feedback: StringBuilder sb = new StringBuilder(); sb.append(feedbackURL); sb.append(event_id).append("."); if (locale.getLanguage().equals("de")) { sb.append("de"); } else { sb.append("en"); } sb.append(".html"); Uri uri = Uri.parse(sb.toString()); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); return true; case R.id.item_share: l = eventid2Lecture(event_id); if (l != null) FahrplanMisc.share(getSherlockActivity(), l); return true; case R.id.item_add_to_calendar: l = eventid2Lecture(event_id); if (l != null) FahrplanMisc.addToCalender(getSherlockActivity(), l); return true; case R.id.item_fav: lecture.highlight = true; if (lecture != null) FahrplanMisc.writeHighlight(getSherlockActivity(), lecture); getSherlockActivity().supportInvalidateOptionsMenu(); getSherlockActivity().setResult(SherlockFragmentActivity.RESULT_OK); refreshEventMarkers(); return true; case R.id.item_unfav: lecture.highlight = false; if (lecture != null) FahrplanMisc.writeHighlight(getSherlockActivity(), lecture); getSherlockActivity().supportInvalidateOptionsMenu(); getSherlockActivity().setResult(SherlockFragmentActivity.RESULT_OK); refreshEventMarkers(); return true; case R.id.item_set_alarm: setAlarmDialog(lecture); return true; case R.id.item_clear_alarm: if (lecture != null) FahrplanMisc.deleteAlarm(getSherlockActivity(), lecture); getSherlockActivity().supportInvalidateOptionsMenu(); getSherlockActivity().setResult(SherlockFragmentActivity.RESULT_OK); refreshEventMarkers(); return true; case R.id.item_close: SherlockFragmentActivity activity = getSherlockActivity(); if ((activity != null) && (activity instanceof OnCloseDetailListener)) { ((OnCloseDetailListener)activity).closeDetailView(); } return true; } return super.onOptionsItemSelected(item); } @Override public void onDestroy() { super.onDestroy(); MyApp.LogDebug(LOG_TAG, "onDestroy"); } }
true
true
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (hasArguments) { boldCondensed = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-BoldCondensed.ttf"); black = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-Black.ttf"); light = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-Light.ttf"); regular = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-Regular.ttf"); bold = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-Bold.ttf"); locale = getResources().getConfiguration().locale; FahrplanFragment.loadLectureList(getSherlockActivity(), day, false); lecture = eventid2Lecture(event_id); TextView t = (TextView)view.findViewById(R.id.title); t.setTypeface(boldCondensed); t.setText(title); t = (TextView)view.findViewById(R.id.subtitle); t.setText(subtitle); t.setTypeface(light); if (subtitle.length() == 0) t.setVisibility(View.GONE); t = (TextView)view.findViewById(R.id.speakers); t.setTypeface(black); t.setText(spkr); t = (TextView)view.findViewById(R.id.abstractt); t.setTypeface(bold); abstractt = abstractt.replaceAll("\\[(.*?)\\]\\(([^ \\)]+).*?\\)", "<a href=\"$2\">$1</a>"); t.setText(Html.fromHtml(abstractt), TextView.BufferType.SPANNABLE); t.setMovementMethod(new LinkMovementMethod()); t = (TextView)view.findViewById(R.id.description); t.setTypeface(regular); descr = descr.replaceAll("\\[(.*?)\\]\\(([^ \\)]+).*?\\)", "<a href=\"$2\">$1</a>"); t.setText(Html.fromHtml(descr), TextView.BufferType.SPANNABLE); t.setMovementMethod(new LinkMovementMethod()); TextView l = (TextView)view.findViewById(R.id.linksSection); l.setTypeface(bold); t = (TextView)view.findViewById(R.id.links); t.setTypeface(regular); if (links.length() > 0) { MyApp.LogDebug(LOG_TAG, "show links"); l.setVisibility(View.VISIBLE); t.setVisibility(View.VISIBLE); links = links.replaceAll("\\),", ")<br>"); links = links.replaceAll("\\[(.*?)\\]\\(([^ \\)]+).*?\\)", "<a href=\"$2\">$1</a>"); t.setText(Html.fromHtml(links), TextView.BufferType.SPANNABLE); t.setMovementMethod(new LinkMovementMethod()); } else { l.setVisibility(View.GONE); t.setVisibility(View.GONE); } } getSherlockActivity().setResult(SherlockFragmentActivity.RESULT_CANCELED); }
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (hasArguments) { boldCondensed = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-BoldCondensed.ttf"); black = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-Black.ttf"); light = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-Light.ttf"); regular = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-Regular.ttf"); bold = Typeface.createFromAsset(getSherlockActivity().getAssets(), "Roboto-Bold.ttf"); locale = getResources().getConfiguration().locale; FahrplanFragment.loadLectureList(getSherlockActivity(), day, false); lecture = eventid2Lecture(event_id); TextView t = (TextView)view.findViewById(R.id.title); t.setTypeface(boldCondensed); t.setText(title); t = (TextView)view.findViewById(R.id.subtitle); t.setText(subtitle); t.setTypeface(light); if (subtitle.length() == 0) t.setVisibility(View.GONE); t = (TextView)view.findViewById(R.id.speakers); t.setTypeface(black); t.setText(spkr); t = (TextView)view.findViewById(R.id.abstractt); t.setTypeface(bold); abstractt = abstractt.replaceAll("\\[(.*?)\\]\\(([^ \\)]+).*?\\)", "<a href=\"$2\">$1</a>"); t.setText(Html.fromHtml(abstractt), TextView.BufferType.SPANNABLE); t.setMovementMethod(new LinkMovementMethod()); t = (TextView)view.findViewById(R.id.description); t.setTypeface(regular); descr = descr.replaceAll("\\[(.*?)\\]\\(([^ \\)]+).*?\\)", "<a href=\"$2\">$1</a>"); t.setText(Html.fromHtml(descr), TextView.BufferType.SPANNABLE); t.setMovementMethod(new LinkMovementMethod()); TextView l = (TextView)view.findViewById(R.id.linksSection); l.setTypeface(bold); t = (TextView)view.findViewById(R.id.links); t.setTypeface(regular); if (links.length() > 0) { MyApp.LogDebug(LOG_TAG, "show links"); l.setVisibility(View.VISIBLE); t.setVisibility(View.VISIBLE); links = links.replaceAll("\\),", ")<br>"); links = links.replaceAll("\\[(.*?)\\]\\(([^ \\)]+).*?\\)", "<a href=\"$2\">$1</a>"); t.setText(Html.fromHtml(links), TextView.BufferType.SPANNABLE); t.setMovementMethod(new LinkMovementMethod()); } else { l.setVisibility(View.GONE); t.setVisibility(View.GONE); } getSherlockActivity().supportInvalidateOptionsMenu(); } getSherlockActivity().setResult(SherlockFragmentActivity.RESULT_CANCELED); }
diff --git a/demo-application/src/main/java/com/homenet/demo/ui/CustomBaseLayout.java b/demo-application/src/main/java/com/homenet/demo/ui/CustomBaseLayout.java index 14a828a..afdf2ba 100644 --- a/demo-application/src/main/java/com/homenet/demo/ui/CustomBaseLayout.java +++ b/demo-application/src/main/java/com/homenet/demo/ui/CustomBaseLayout.java @@ -1,31 +1,31 @@ package com.homenet.demo.ui; import com.homenet.bootstrap.loader.RootLayoutFactory; import com.homenet.bootstrap.loader.UIRootLoader; import com.vaadin.ui.Button; import com.vaadin.ui.CssLayout; import com.vaadin.ui.Label; import java.io.File; import java.io.InputStream; public class CustomBaseLayout implements UIRootLoader { @Override public void getRootFactory(RootLayoutFactory factory) { factory.setCompositionPage(new Button("test")); InputStream is = getClass().getResourceAsStream("/img/logo.png"); factory.customizeLogo(is); CssLayout comp = new CssLayout(new Label("MenuItem")); comp.setStyleName("us-menu-layout"); InputStream cssSource = getClass().getResourceAsStream("/styles/styles.css"); factory.addCSSSource(cssSource); factory.customizeTopMenuCol2(comp); - factory.customizeTopMenuCol3(comp); - factory.customizeTopMenuCol4(comp); + factory.customizeTopMenuCol3(new Label("MenuItem3")); + factory.customizeTopMenuCol4(new Label("MenuItem4")); } }
true
true
public void getRootFactory(RootLayoutFactory factory) { factory.setCompositionPage(new Button("test")); InputStream is = getClass().getResourceAsStream("/img/logo.png"); factory.customizeLogo(is); CssLayout comp = new CssLayout(new Label("MenuItem")); comp.setStyleName("us-menu-layout"); InputStream cssSource = getClass().getResourceAsStream("/styles/styles.css"); factory.addCSSSource(cssSource); factory.customizeTopMenuCol2(comp); factory.customizeTopMenuCol3(comp); factory.customizeTopMenuCol4(comp); }
public void getRootFactory(RootLayoutFactory factory) { factory.setCompositionPage(new Button("test")); InputStream is = getClass().getResourceAsStream("/img/logo.png"); factory.customizeLogo(is); CssLayout comp = new CssLayout(new Label("MenuItem")); comp.setStyleName("us-menu-layout"); InputStream cssSource = getClass().getResourceAsStream("/styles/styles.css"); factory.addCSSSource(cssSource); factory.customizeTopMenuCol2(comp); factory.customizeTopMenuCol3(new Label("MenuItem3")); factory.customizeTopMenuCol4(new Label("MenuItem4")); }
diff --git a/jabox-standalone/src/main/java/org/jabox/standalone/Start.java b/jabox-standalone/src/main/java/org/jabox/standalone/Start.java index 8fdba70b..12bb2674 100644 --- a/jabox-standalone/src/main/java/org/jabox/standalone/Start.java +++ b/jabox-standalone/src/main/java/org/jabox/standalone/Start.java @@ -1,182 +1,183 @@ /* * Jabox Open Source Version * Copyright (C) 2009-2010 Dimitris Kapanidis * * This file is part of Jabox * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package org.jabox.standalone; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import org.codehaus.cargo.container.ContainerType; import org.codehaus.cargo.container.InstalledLocalContainer; import org.codehaus.cargo.container.configuration.ConfigurationType; import org.codehaus.cargo.container.configuration.LocalConfiguration; import org.codehaus.cargo.container.deployable.WAR; import org.codehaus.cargo.container.installer.Installer; import org.codehaus.cargo.container.installer.ZipURLInstaller; import org.codehaus.cargo.generic.DefaultContainerFactory; import org.codehaus.cargo.generic.configuration.DefaultConfigurationFactory; import org.jabox.apis.embedded.EmbeddedServer; import org.jabox.environment.Environment; import org.jabox.utils.MavenSettingsManager; import org.jabox.utils.WebappManager; import org.mortbay.jetty.Connector; import org.mortbay.jetty.Server; import org.mortbay.jetty.bio.SocketConnector; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.resource.Resource; public class Start { private static final String PACKAGE = "/jabox-webapp/"; public Start() { try { startEmbeddedJetty(false); } catch (MalformedURLException e) { e.printStackTrace(); } } /** * @param args * @throws Exception */ public static void main(final String[] args) throws Exception { System.out.println(getJaboxWebapp()); System.out.println("Jabox home directory: " + Environment.getBaseDir()); Environment.configureEnvironmentVariables(); startEmbeddedJetty(true); } private static String getJaboxWebapp() { Resource res = Resource.newClassPathResource(PACKAGE); if (res == null) { return "D:\\Documents\\My Developments\\Jabox\\workspace-jabox\\jabox\\jabox-webapp\\target\\jabox-webapp-0.0.6-SNAPSHOT\\"; } return res.toString(); } /** * * @param startJabox * If set to true the Jetty application is starting Jabox * Application together with the embeddedServers. * @throws MalformedURLException * @throws InstantiationException * @throws IllegalAccessException * @throws ClassNotFoundException */ public static void startEmbeddedJetty(final boolean startJabox) throws MalformedURLException { // (1) Optional step to install the container from a URL pointing to its // distribution Installer installer; installer = new ZipURLInstaller( new URL( "http://archive.apache.org/dist/tomcat/tomcat-6/v6.0.32/bin/apache-tomcat-6.0.32.zip"), new File(Environment.getBaseDir(), "cargo/installs") .getAbsolutePath()); installer.install(); // (2) Create the Cargo Container instance wrapping our physical // container LocalConfiguration configuration = (LocalConfiguration) new DefaultConfigurationFactory() .createConfiguration("tomcat6x", ContainerType.INSTALLED, ConfigurationType.STANDALONE, new File(Environment .getBaseDir(), "cargo/conf").getAbsolutePath()); InstalledLocalContainer container = (InstalledLocalContainer) new DefaultContainerFactory() .createContainer("tomcat6x", ContainerType.INSTALLED, configuration); container.setHome(installer.getHome()); container.setOutput(new File(Environment.getBaseDir(), "cargo/cargo.out").getAbsolutePath()); container.setSystemProperties(System.getProperties()); Server server = new Server(); MavenSettingsManager.writeCustomSettings(); SocketConnector connector = new SocketConnector(); // Set some timeout options to make debugging easier. connector.setMaxIdleTime(1000 * 60 * 60); connector.setSoLingerTime(-1); connector.setPort(9090); server.setConnectors(new Connector[] { connector }); try { List<String> webapps = WebappManager.getWebapps(); for (String webapp : webapps) { addEmbeddedServer(configuration, webapp); } if (startJabox) { // Adding ROOT handler. // NOTE: This should be added last on server. WebAppContext bb = new WebAppContext(); bb.setServer(server); bb.setContextPath("/"); bb.setWar(getJaboxWebapp()); File tempDir = new File(Environment.getBaseDirFile(), "server-jabox"); tempDir.mkdirs(); bb.setTempDirectory(tempDir); server.addHandler(bb); } System.out .println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP"); server.start(); BrowserStarter.openBrowser("http://localhost:9090/"); // (4) Start the container + container.setTimeout(1200000); container.start(); System.out.println(">>> Container started."); if (startJabox) { while (System.in.available() == 0) { Thread.sleep(5000); } server.stop(); server.join(); } } catch (Exception e) { e.printStackTrace(); System.exit(100); } } /** * Helper function to add an embedded Server using the className to the * running Jetty Server. * * @param configuration * The Jetty server. * @param className * The className of the EmbeddedServer. * @throws InstantiationException * @throws IllegalAccessException * @throws ClassNotFoundException */ private static void addEmbeddedServer( final LocalConfiguration configuration, final String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException { EmbeddedServer es = (EmbeddedServer) Class.forName(className) .newInstance(); configuration.addDeployable(new WAR(es.getWarPath())); } }
true
true
public static void startEmbeddedJetty(final boolean startJabox) throws MalformedURLException { // (1) Optional step to install the container from a URL pointing to its // distribution Installer installer; installer = new ZipURLInstaller( new URL( "http://archive.apache.org/dist/tomcat/tomcat-6/v6.0.32/bin/apache-tomcat-6.0.32.zip"), new File(Environment.getBaseDir(), "cargo/installs") .getAbsolutePath()); installer.install(); // (2) Create the Cargo Container instance wrapping our physical // container LocalConfiguration configuration = (LocalConfiguration) new DefaultConfigurationFactory() .createConfiguration("tomcat6x", ContainerType.INSTALLED, ConfigurationType.STANDALONE, new File(Environment .getBaseDir(), "cargo/conf").getAbsolutePath()); InstalledLocalContainer container = (InstalledLocalContainer) new DefaultContainerFactory() .createContainer("tomcat6x", ContainerType.INSTALLED, configuration); container.setHome(installer.getHome()); container.setOutput(new File(Environment.getBaseDir(), "cargo/cargo.out").getAbsolutePath()); container.setSystemProperties(System.getProperties()); Server server = new Server(); MavenSettingsManager.writeCustomSettings(); SocketConnector connector = new SocketConnector(); // Set some timeout options to make debugging easier. connector.setMaxIdleTime(1000 * 60 * 60); connector.setSoLingerTime(-1); connector.setPort(9090); server.setConnectors(new Connector[] { connector }); try { List<String> webapps = WebappManager.getWebapps(); for (String webapp : webapps) { addEmbeddedServer(configuration, webapp); } if (startJabox) { // Adding ROOT handler. // NOTE: This should be added last on server. WebAppContext bb = new WebAppContext(); bb.setServer(server); bb.setContextPath("/"); bb.setWar(getJaboxWebapp()); File tempDir = new File(Environment.getBaseDirFile(), "server-jabox"); tempDir.mkdirs(); bb.setTempDirectory(tempDir); server.addHandler(bb); } System.out .println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP"); server.start(); BrowserStarter.openBrowser("http://localhost:9090/"); // (4) Start the container container.start(); System.out.println(">>> Container started."); if (startJabox) { while (System.in.available() == 0) { Thread.sleep(5000); } server.stop(); server.join(); } } catch (Exception e) { e.printStackTrace(); System.exit(100); } }
public static void startEmbeddedJetty(final boolean startJabox) throws MalformedURLException { // (1) Optional step to install the container from a URL pointing to its // distribution Installer installer; installer = new ZipURLInstaller( new URL( "http://archive.apache.org/dist/tomcat/tomcat-6/v6.0.32/bin/apache-tomcat-6.0.32.zip"), new File(Environment.getBaseDir(), "cargo/installs") .getAbsolutePath()); installer.install(); // (2) Create the Cargo Container instance wrapping our physical // container LocalConfiguration configuration = (LocalConfiguration) new DefaultConfigurationFactory() .createConfiguration("tomcat6x", ContainerType.INSTALLED, ConfigurationType.STANDALONE, new File(Environment .getBaseDir(), "cargo/conf").getAbsolutePath()); InstalledLocalContainer container = (InstalledLocalContainer) new DefaultContainerFactory() .createContainer("tomcat6x", ContainerType.INSTALLED, configuration); container.setHome(installer.getHome()); container.setOutput(new File(Environment.getBaseDir(), "cargo/cargo.out").getAbsolutePath()); container.setSystemProperties(System.getProperties()); Server server = new Server(); MavenSettingsManager.writeCustomSettings(); SocketConnector connector = new SocketConnector(); // Set some timeout options to make debugging easier. connector.setMaxIdleTime(1000 * 60 * 60); connector.setSoLingerTime(-1); connector.setPort(9090); server.setConnectors(new Connector[] { connector }); try { List<String> webapps = WebappManager.getWebapps(); for (String webapp : webapps) { addEmbeddedServer(configuration, webapp); } if (startJabox) { // Adding ROOT handler. // NOTE: This should be added last on server. WebAppContext bb = new WebAppContext(); bb.setServer(server); bb.setContextPath("/"); bb.setWar(getJaboxWebapp()); File tempDir = new File(Environment.getBaseDirFile(), "server-jabox"); tempDir.mkdirs(); bb.setTempDirectory(tempDir); server.addHandler(bb); } System.out .println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP"); server.start(); BrowserStarter.openBrowser("http://localhost:9090/"); // (4) Start the container container.setTimeout(1200000); container.start(); System.out.println(">>> Container started."); if (startJabox) { while (System.in.available() == 0) { Thread.sleep(5000); } server.stop(); server.join(); } } catch (Exception e) { e.printStackTrace(); System.exit(100); } }
diff --git a/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/AptVerifier.java b/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/AptVerifier.java index 0eefef9..2ec2130 100644 --- a/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/AptVerifier.java +++ b/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/AptVerifier.java @@ -1,163 +1,163 @@ package org.apache.maven.doxia.siterenderer; /* * 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 com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlDivision; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlHeader2; import com.gargoylesoftware.htmlunit.html.HtmlHeader3; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlParagraph; import com.gargoylesoftware.htmlunit.html.UnknownHtmlElement; import java.util.Iterator; /** * Verifies apt transformations. * * @author ltheussl * @version $Id$ */ public class AptVerifier extends AbstractVerifier { /** {@inheritDoc} */ public void verify( String file ) throws Exception { HtmlPage page = htmlPage( file ); assertNotNull( page ); HtmlElement element = page.getHtmlElementById( "contentBox" ); assertNotNull( element ); HtmlDivision division = (HtmlDivision) element; assertNotNull( division ); Iterator elementIterator = division.getAllHtmlChildElements(); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- HtmlDivision div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); HtmlHeader2 h2 = (HtmlHeader2) elementIterator.next(); assertNotNull( h2 ); assertEquals( "Links", h2.asText().trim() ); HtmlAnchor a = (HtmlAnchor) elementIterator.next(); assertEquals( "Links", a.getAttributeValue( "name" ) ); HtmlParagraph p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Anchor", a.getAttributeValue( "name" ) ); a = (HtmlAnchor) elementIterator.next(); - assertEquals( "cdc.html", a.getAttributeValue( "name" ) ); + assertEquals( "cdc.html.internal", a.getAttributeValue( "name" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Anchor_with_space", a.getAttributeValue( "name" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor_with_space", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "http://maven.apache.org/", a.getAttributeValue( "href" ) ); assertEquals( "externalLink", a.getAttributeValue( "class" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "http://maven.apache.org/", a.getAttributeValue( "href" ) ); assertEquals( "externalLink", a.getAttributeValue( "class" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "./cdc.html", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); - assertEquals( "#cdc.html", a.getAttributeValue( "href" ) ); + assertEquals( "#cdc.html.internal", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "/index.html", a.getAttributeValue( "href" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); h2 = (HtmlHeader2) elementIterator.next(); assertNotNull( h2 ); assertEquals( "Section formatting: italic bold mono", h2.asText().trim() ); UnknownHtmlElement unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unknown.getTagName() ); assertEquals( "italic", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unknown.getTagName() ); assertEquals( "bold", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "tt", unknown.getTagName() ); assertEquals( "mono", unknown.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Section_formatting:_italic_bold_mono", a.getAttributeValue( "name" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); HtmlHeader3 h3 = (HtmlHeader3) elementIterator.next(); assertNotNull( h3 ); assertEquals( "SubSection formatting: italic bold mono", h3.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unknown.getTagName() ); assertEquals( "italic", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unknown.getTagName() ); assertEquals( "bold", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "tt", unknown.getTagName() ); assertEquals( "mono", unknown.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "SubSection_formatting:_italic_bold_mono", a.getAttributeValue( "name" ) ); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unknown.getTagName() ); assertEquals( "italic", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unknown.getTagName() ); assertEquals( "bold", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "tt", unknown.getTagName() ); assertEquals( "mono", unknown.asText().trim() ); } }
false
true
public void verify( String file ) throws Exception { HtmlPage page = htmlPage( file ); assertNotNull( page ); HtmlElement element = page.getHtmlElementById( "contentBox" ); assertNotNull( element ); HtmlDivision division = (HtmlDivision) element; assertNotNull( division ); Iterator elementIterator = division.getAllHtmlChildElements(); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- HtmlDivision div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); HtmlHeader2 h2 = (HtmlHeader2) elementIterator.next(); assertNotNull( h2 ); assertEquals( "Links", h2.asText().trim() ); HtmlAnchor a = (HtmlAnchor) elementIterator.next(); assertEquals( "Links", a.getAttributeValue( "name" ) ); HtmlParagraph p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Anchor", a.getAttributeValue( "name" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "cdc.html", a.getAttributeValue( "name" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Anchor_with_space", a.getAttributeValue( "name" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor_with_space", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "http://maven.apache.org/", a.getAttributeValue( "href" ) ); assertEquals( "externalLink", a.getAttributeValue( "class" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "http://maven.apache.org/", a.getAttributeValue( "href" ) ); assertEquals( "externalLink", a.getAttributeValue( "class" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "./cdc.html", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#cdc.html", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "/index.html", a.getAttributeValue( "href" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); h2 = (HtmlHeader2) elementIterator.next(); assertNotNull( h2 ); assertEquals( "Section formatting: italic bold mono", h2.asText().trim() ); UnknownHtmlElement unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unknown.getTagName() ); assertEquals( "italic", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unknown.getTagName() ); assertEquals( "bold", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "tt", unknown.getTagName() ); assertEquals( "mono", unknown.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Section_formatting:_italic_bold_mono", a.getAttributeValue( "name" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); HtmlHeader3 h3 = (HtmlHeader3) elementIterator.next(); assertNotNull( h3 ); assertEquals( "SubSection formatting: italic bold mono", h3.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unknown.getTagName() ); assertEquals( "italic", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unknown.getTagName() ); assertEquals( "bold", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "tt", unknown.getTagName() ); assertEquals( "mono", unknown.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "SubSection_formatting:_italic_bold_mono", a.getAttributeValue( "name" ) ); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unknown.getTagName() ); assertEquals( "italic", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unknown.getTagName() ); assertEquals( "bold", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "tt", unknown.getTagName() ); assertEquals( "mono", unknown.asText().trim() ); }
public void verify( String file ) throws Exception { HtmlPage page = htmlPage( file ); assertNotNull( page ); HtmlElement element = page.getHtmlElementById( "contentBox" ); assertNotNull( element ); HtmlDivision division = (HtmlDivision) element; assertNotNull( division ); Iterator elementIterator = division.getAllHtmlChildElements(); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- HtmlDivision div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); HtmlHeader2 h2 = (HtmlHeader2) elementIterator.next(); assertNotNull( h2 ); assertEquals( "Links", h2.asText().trim() ); HtmlAnchor a = (HtmlAnchor) elementIterator.next(); assertEquals( "Links", a.getAttributeValue( "name" ) ); HtmlParagraph p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Anchor", a.getAttributeValue( "name" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "cdc.html.internal", a.getAttributeValue( "name" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Anchor_with_space", a.getAttributeValue( "name" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#Anchor_with_space", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "http://maven.apache.org/", a.getAttributeValue( "href" ) ); assertEquals( "externalLink", a.getAttributeValue( "class" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "http://maven.apache.org/", a.getAttributeValue( "href" ) ); assertEquals( "externalLink", a.getAttributeValue( "class" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "./cdc.html", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "#cdc.html.internal", a.getAttributeValue( "href" ) ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "/index.html", a.getAttributeValue( "href" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); h2 = (HtmlHeader2) elementIterator.next(); assertNotNull( h2 ); assertEquals( "Section formatting: italic bold mono", h2.asText().trim() ); UnknownHtmlElement unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unknown.getTagName() ); assertEquals( "italic", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unknown.getTagName() ); assertEquals( "bold", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "tt", unknown.getTagName() ); assertEquals( "mono", unknown.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "Section_formatting:_italic_bold_mono", a.getAttributeValue( "name" ) ); div = (HtmlDivision) elementIterator.next(); assertEquals( "section", div.getAttributeValue( "class" ) ); HtmlHeader3 h3 = (HtmlHeader3) elementIterator.next(); assertNotNull( h3 ); assertEquals( "SubSection formatting: italic bold mono", h3.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unknown.getTagName() ); assertEquals( "italic", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unknown.getTagName() ); assertEquals( "bold", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "tt", unknown.getTagName() ); assertEquals( "mono", unknown.asText().trim() ); a = (HtmlAnchor) elementIterator.next(); assertEquals( "SubSection_formatting:_italic_bold_mono", a.getAttributeValue( "name" ) ); p = (HtmlParagraph) elementIterator.next(); assertNotNull( p ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "i", unknown.getTagName() ); assertEquals( "italic", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "b", unknown.getTagName() ); assertEquals( "bold", unknown.asText().trim() ); unknown = (UnknownHtmlElement) elementIterator.next(); assertEquals( "tt", unknown.getTagName() ); assertEquals( "mono", unknown.asText().trim() ); }
diff --git a/integration/src/main/java/com/quartercode/quarterbukkit/QuarterBukkitIntegration.java b/integration/src/main/java/com/quartercode/quarterbukkit/QuarterBukkitIntegration.java index 2fcca0c..56b0d01 100644 --- a/integration/src/main/java/com/quartercode/quarterbukkit/QuarterBukkitIntegration.java +++ b/integration/src/main/java/com/quartercode/quarterbukkit/QuarterBukkitIntegration.java @@ -1,283 +1,283 @@ /* * This file is part of QuarterBukkit-Integration. * Copyright (c) 2012 QuarterCode <http://www.quartercode.com/> * * QuarterBukkit-Integration is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QuarterBukkit-Integration is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QuarterBukkit-Integration. If not, see <http://www.gnu.org/licenses/>. */ package com.quartercode.quarterbukkit; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.InvalidDescriptionException; import org.bukkit.plugin.InvalidPluginException; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.UnknownDependencyException; /** * This class is used for integrating QuarterBukkit into a plugin. */ public class QuarterBukkitIntegration { private static final String TITLE_TAG = "title"; private static final String LINK_TAG = "link"; private static final String ITEM_TAG = "item"; private static URL feedUrl; static { try { feedUrl = new URL("http://dev.bukkit.org/server-mods/quarterbukkit/files.rss"); } catch (final MalformedURLException e) { Bukkit.getLogger().severe("Error while initalizing URL (" + e + ")"); } } /** * Call this method in onEnable() for integrating QuarterBukkit into your plugin. * It creates a config where the user has to turn a value to "Yes" for the actual installation. * The class notfies him on the console and every time an op joins to the server. * * @param plugin The {@link Plugin} which tries to integrate QuarterBukkit. */ public static boolean integrate(final Plugin plugin) { if (new File("plugins/QuarterBukkit_extract").exists()) { deleteRecursive(new File("plugins/QuarterBukkit_extract")); } final File installConfigFile = new File("plugins/QuarterBukkit", "install.yml"); try { if (!installConfigFile.exists() && !Bukkit.getPluginManager().isPluginEnabled("QuarterBukkit")) { final YamlConfiguration installConfig = new YamlConfiguration(); installConfig.set("install-QuarterBukkit", true); installConfig.save(installConfigFile); } else if (!Bukkit.getPluginManager().isPluginEnabled("QuarterBukkit")) { final YamlConfiguration installConfig = YamlConfiguration.loadConfiguration(installConfigFile); if (installConfig.isBoolean("install-QuarterBukkit") && installConfig.getBoolean("install-QuarterBukkit")) { installConfigFile.delete(); - install(new File("plugins", "QuarterBukkit.jar")); + install(new File("plugins", "QuarterBukkit-Plugin.jar")); return true; } } else { return true; } new Timer().schedule(new TimerTask() { @Override public void run() { Bukkit.broadcastMessage(ChatColor.YELLOW + "===============[ QuarterBukkit Installation ]==============="); Bukkit.broadcastMessage(ChatColor.RED + "For using " + plugin.getName() + " and get QuarterBukkit, you should " + ChatColor.DARK_AQUA + "restart" + ChatColor.RED + " the server!"); } }, 100, 3 * 1000); } catch (final UnknownHostException e) { Bukkit.getLogger().warning("Can't connect to dev.bukkit.org!"); } catch (final Exception e) { Bukkit.getLogger().severe("An error occurred while installing QuarterBukkit (" + e + ")"); e.printStackTrace(); } Bukkit.getPluginManager().disablePlugin(plugin); return false; } private static void install(final File target) throws IOException, XMLStreamException, UnknownDependencyException, InvalidPluginException, InvalidDescriptionException { Bukkit.getLogger().info("===============[ QuarterBukkit Installation ]==============="); Bukkit.getLogger().info("Installing QuarterBukkit ..."); Bukkit.getLogger().info("Downloading QuarterBukkit ..."); final File zipFile = new File(target.getParentFile(), "QuarterBukkit_download.zip"); final URL url = new URL(getFileURL(getFeedData().get("link"))); final InputStream inputStream = url.openStream(); final OutputStream outputStream = new FileOutputStream(zipFile); outputStream.flush(); final byte[] tempBuffer = new byte[4096]; int counter; while ( (counter = inputStream.read(tempBuffer)) > 0) { outputStream.write(tempBuffer, 0, counter); outputStream.flush(); } inputStream.close(); outputStream.close(); Bukkit.getLogger().info("Extracting QuarterBukkit ..."); final File unzipDir = new File(target.getParentFile(), "QuarterBukkit_extract"); unzipDir.mkdirs(); unzip(zipFile, unzipDir); copy(new File(unzipDir, "QuarterBukkit/" + target.getName()), target); zipFile.delete(); deleteRecursive(unzipDir); Bukkit.getLogger().info("Loading QuarterBukkit ..."); Bukkit.getPluginManager().enablePlugin(Bukkit.getPluginManager().loadPlugin(target)); Bukkit.getLogger().info("Successfully installed QuarterBukkit!"); Bukkit.getLogger().info("Enabling other plugins ..."); } private static void unzip(final File zip, final File destination) throws ZipException, IOException { final ZipFile zipFile = new ZipFile(zip); for (final ZipEntry zipEntry : Collections.list(zipFile.entries())) { final File file = new File(destination, zipEntry.getName()); final byte[] BUFFER = new byte[0xFFFF]; if (zipEntry.isDirectory()) { file.mkdirs(); } else { new File(file.getParent()).mkdirs(); final InputStream inputStream = zipFile.getInputStream(zipEntry); final OutputStream outputStream = new FileOutputStream(file); for (int lenght; (lenght = inputStream.read(BUFFER)) != -1;) { outputStream.write(BUFFER, 0, lenght); } if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } } zipFile.close(); } private static void copy(final File source, final File destination) throws FileNotFoundException, IOException { if (source.isDirectory()) { destination.mkdirs(); for (final File entry : source.listFiles()) { copy(new File(source, entry.getName()), new File(destination, entry.getName())); } } else { final byte[] buffer = new byte[32768]; final InputStream inputStream = new FileInputStream(source); final OutputStream outputStream = new FileOutputStream(destination); int numberOfBytes; while ( (numberOfBytes = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, numberOfBytes); } inputStream.close(); outputStream.close(); } } private static void deleteRecursive(final File file) { if (file.isDirectory()) { for (final File entry : file.listFiles()) { deleteRecursive(entry); } } file.delete(); } private static String getFileURL(final String link) throws IOException { final URL url = new URL(link); URLConnection connection = url.openConnection(); final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ( (line = reader.readLine()) != null) { if (line.contains("<li class=\"user-action user-action-download\">")) { return line.split("<a href=\"")[1].split("\">Download</a>")[0]; } } connection = null; reader.close(); return null; } private static Map<String, String> getFeedData() throws IOException, XMLStreamException { final Map<String, String> returnMap = new HashMap<String, String>(); String title = null; String link = null; final XMLInputFactory inputFactory = XMLInputFactory.newInstance(); final InputStream inputStream = feedUrl.openStream(); final XMLEventReader eventReader = inputFactory.createXMLEventReader(inputStream); while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement()) { if (event.asStartElement().getName().getLocalPart().equals(TITLE_TAG)) { event = eventReader.nextEvent(); title = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart().equals(LINK_TAG)) { event = eventReader.nextEvent(); link = event.asCharacters().getData(); continue; } } else if (event.isEndElement()) { if (event.asEndElement().getName().getLocalPart().equals(ITEM_TAG)) { returnMap.put("title", title); returnMap.put("link", link); return returnMap; } } } return returnMap; } }
true
true
public static boolean integrate(final Plugin plugin) { if (new File("plugins/QuarterBukkit_extract").exists()) { deleteRecursive(new File("plugins/QuarterBukkit_extract")); } final File installConfigFile = new File("plugins/QuarterBukkit", "install.yml"); try { if (!installConfigFile.exists() && !Bukkit.getPluginManager().isPluginEnabled("QuarterBukkit")) { final YamlConfiguration installConfig = new YamlConfiguration(); installConfig.set("install-QuarterBukkit", true); installConfig.save(installConfigFile); } else if (!Bukkit.getPluginManager().isPluginEnabled("QuarterBukkit")) { final YamlConfiguration installConfig = YamlConfiguration.loadConfiguration(installConfigFile); if (installConfig.isBoolean("install-QuarterBukkit") && installConfig.getBoolean("install-QuarterBukkit")) { installConfigFile.delete(); install(new File("plugins", "QuarterBukkit.jar")); return true; } } else { return true; } new Timer().schedule(new TimerTask() { @Override public void run() { Bukkit.broadcastMessage(ChatColor.YELLOW + "===============[ QuarterBukkit Installation ]==============="); Bukkit.broadcastMessage(ChatColor.RED + "For using " + plugin.getName() + " and get QuarterBukkit, you should " + ChatColor.DARK_AQUA + "restart" + ChatColor.RED + " the server!"); } }, 100, 3 * 1000); } catch (final UnknownHostException e) { Bukkit.getLogger().warning("Can't connect to dev.bukkit.org!"); } catch (final Exception e) { Bukkit.getLogger().severe("An error occurred while installing QuarterBukkit (" + e + ")"); e.printStackTrace(); } Bukkit.getPluginManager().disablePlugin(plugin); return false; }
public static boolean integrate(final Plugin plugin) { if (new File("plugins/QuarterBukkit_extract").exists()) { deleteRecursive(new File("plugins/QuarterBukkit_extract")); } final File installConfigFile = new File("plugins/QuarterBukkit", "install.yml"); try { if (!installConfigFile.exists() && !Bukkit.getPluginManager().isPluginEnabled("QuarterBukkit")) { final YamlConfiguration installConfig = new YamlConfiguration(); installConfig.set("install-QuarterBukkit", true); installConfig.save(installConfigFile); } else if (!Bukkit.getPluginManager().isPluginEnabled("QuarterBukkit")) { final YamlConfiguration installConfig = YamlConfiguration.loadConfiguration(installConfigFile); if (installConfig.isBoolean("install-QuarterBukkit") && installConfig.getBoolean("install-QuarterBukkit")) { installConfigFile.delete(); install(new File("plugins", "QuarterBukkit-Plugin.jar")); return true; } } else { return true; } new Timer().schedule(new TimerTask() { @Override public void run() { Bukkit.broadcastMessage(ChatColor.YELLOW + "===============[ QuarterBukkit Installation ]==============="); Bukkit.broadcastMessage(ChatColor.RED + "For using " + plugin.getName() + " and get QuarterBukkit, you should " + ChatColor.DARK_AQUA + "restart" + ChatColor.RED + " the server!"); } }, 100, 3 * 1000); } catch (final UnknownHostException e) { Bukkit.getLogger().warning("Can't connect to dev.bukkit.org!"); } catch (final Exception e) { Bukkit.getLogger().severe("An error occurred while installing QuarterBukkit (" + e + ")"); e.printStackTrace(); } Bukkit.getPluginManager().disablePlugin(plugin); return false; }
diff --git a/overthere/src/main/java/com/xebialabs/overthere/cifs/winrm/connector/JdkHttpConnector.java b/overthere/src/main/java/com/xebialabs/overthere/cifs/winrm/connector/JdkHttpConnector.java index 5bbdd17..e48b1cf 100644 --- a/overthere/src/main/java/com/xebialabs/overthere/cifs/winrm/connector/JdkHttpConnector.java +++ b/overthere/src/main/java/com/xebialabs/overthere/cifs/winrm/connector/JdkHttpConnector.java @@ -1,135 +1,135 @@ /* * This file is part of WinRM. * * WinRM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WinRM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with WinRM. If not, see <http://www.gnu.org/licenses/>. */ package com.xebialabs.overthere.cifs.winrm.connector; import com.google.common.io.Closeables; import com.xebialabs.overthere.cifs.winrm.HttpConnector; import com.xebialabs.overthere.cifs.winrm.SoapAction; import com.xebialabs.overthere.cifs.winrm.TokenGenerator; import com.xebialabs.overthere.cifs.winrm.exception.BlankValueRuntimeException; import com.xebialabs.overthere.cifs.winrm.exception.InvalidFilePathRuntimeException; import com.xebialabs.overthere.cifs.winrm.exception.WinRMRuntimeIOException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; /** */ public class JdkHttpConnector implements HttpConnector { private final URL targetURL; private final TokenGenerator tokenGenerator; public JdkHttpConnector(URL targetURL, TokenGenerator tokenGenerator) { this.targetURL = targetURL; this.tokenGenerator = tokenGenerator; } @Override public Document sendMessage(Document requestDocument, SoapAction soapAction) { Document responseDocument = null; try { final URLConnection urlConnection = targetURL.openConnection(); HttpURLConnection con = (HttpURLConnection) urlConnection; con.setDoInput(true); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); final String authToken = tokenGenerator.generateToken(); if (authToken != null) con.addRequestProperty("Authorization", authToken); if (soapAction != null) { con.setRequestProperty("SOAPAction", soapAction.getValue()); } final String requestDocAsString = toString(requestDocument); logger.debug("send message to {}:request {}", targetURL, requestDocAsString); BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( con.getOutputStream())); bw.write(requestDocAsString, 0, requestDocAsString.length()); bw.flush(); bw.close(); InputStream is; if (con.getResponseCode() >= 400) { /* Read error response */ - is = httpConn.getErrorStream(); + is = con.getErrorStream(); } else { - is = httpConn.getInputStream(); + is = con.getInputStream(); } Writer writer = new StringWriter(); try { int n; char[] buffer = new char[1024]; Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { Closeables.closeQuietly(is); } if (logger.isDebugEnabled()) { for (int i = 0; i < con.getHeaderFields().size(); i++) { logger.debug("Header {} --> {}", con.getHeaderFieldKey(i), con.getHeaderField(i)); } } final String text = writer.toString(); logger.debug("send message:response {}", text); responseDocument = DocumentHelper.parseText(text); return responseDocument; } catch (BlankValueRuntimeException bvrte) { throw bvrte; } catch (InvalidFilePathRuntimeException ifprte) { throw ifprte; } catch (Exception e) { throw new WinRMRuntimeIOException("send message on " + targetURL + " error ", requestDocument, responseDocument, e); } } private String toString(Document doc) { StringWriter stringWriter = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(stringWriter, OutputFormat.createPrettyPrint()); try { xmlWriter.write(doc); xmlWriter.close(); } catch (IOException e) { throw new WinRMRuntimeIOException("error ", e); } return stringWriter.toString(); } private static Logger logger = LoggerFactory.getLogger(JdkHttpConnector.class); }
false
true
public Document sendMessage(Document requestDocument, SoapAction soapAction) { Document responseDocument = null; try { final URLConnection urlConnection = targetURL.openConnection(); HttpURLConnection con = (HttpURLConnection) urlConnection; con.setDoInput(true); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); final String authToken = tokenGenerator.generateToken(); if (authToken != null) con.addRequestProperty("Authorization", authToken); if (soapAction != null) { con.setRequestProperty("SOAPAction", soapAction.getValue()); } final String requestDocAsString = toString(requestDocument); logger.debug("send message to {}:request {}", targetURL, requestDocAsString); BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( con.getOutputStream())); bw.write(requestDocAsString, 0, requestDocAsString.length()); bw.flush(); bw.close(); InputStream is; if (con.getResponseCode() >= 400) { /* Read error response */ is = httpConn.getErrorStream(); } else { is = httpConn.getInputStream(); } Writer writer = new StringWriter(); try { int n; char[] buffer = new char[1024]; Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { Closeables.closeQuietly(is); } if (logger.isDebugEnabled()) { for (int i = 0; i < con.getHeaderFields().size(); i++) { logger.debug("Header {} --> {}", con.getHeaderFieldKey(i), con.getHeaderField(i)); } } final String text = writer.toString(); logger.debug("send message:response {}", text); responseDocument = DocumentHelper.parseText(text); return responseDocument; } catch (BlankValueRuntimeException bvrte) { throw bvrte; } catch (InvalidFilePathRuntimeException ifprte) { throw ifprte; } catch (Exception e) { throw new WinRMRuntimeIOException("send message on " + targetURL + " error ", requestDocument, responseDocument, e); } }
public Document sendMessage(Document requestDocument, SoapAction soapAction) { Document responseDocument = null; try { final URLConnection urlConnection = targetURL.openConnection(); HttpURLConnection con = (HttpURLConnection) urlConnection; con.setDoInput(true); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); final String authToken = tokenGenerator.generateToken(); if (authToken != null) con.addRequestProperty("Authorization", authToken); if (soapAction != null) { con.setRequestProperty("SOAPAction", soapAction.getValue()); } final String requestDocAsString = toString(requestDocument); logger.debug("send message to {}:request {}", targetURL, requestDocAsString); BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( con.getOutputStream())); bw.write(requestDocAsString, 0, requestDocAsString.length()); bw.flush(); bw.close(); InputStream is; if (con.getResponseCode() >= 400) { /* Read error response */ is = con.getErrorStream(); } else { is = con.getInputStream(); } Writer writer = new StringWriter(); try { int n; char[] buffer = new char[1024]; Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { Closeables.closeQuietly(is); } if (logger.isDebugEnabled()) { for (int i = 0; i < con.getHeaderFields().size(); i++) { logger.debug("Header {} --> {}", con.getHeaderFieldKey(i), con.getHeaderField(i)); } } final String text = writer.toString(); logger.debug("send message:response {}", text); responseDocument = DocumentHelper.parseText(text); return responseDocument; } catch (BlankValueRuntimeException bvrte) { throw bvrte; } catch (InvalidFilePathRuntimeException ifprte) { throw ifprte; } catch (Exception e) { throw new WinRMRuntimeIOException("send message on " + targetURL + " error ", requestDocument, responseDocument, e); } }
diff --git a/eclipse/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/views/ViolationRuleNameField.java b/eclipse/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/views/ViolationRuleNameField.java index d06f729..cbf6030 100644 --- a/eclipse/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/views/ViolationRuleNameField.java +++ b/eclipse/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/views/ViolationRuleNameField.java @@ -1,33 +1,36 @@ /* * Copyright (C) 2010 Evgeny Mandrikov * * Sonar-IDE is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar-IDE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar-IDE; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.ide.eclipse.views; import org.eclipse.ui.views.markers.MarkerField; import org.eclipse.ui.views.markers.MarkerItem; /** * @author Jérémie Lagarde */ public class ViolationRuleNameField extends MarkerField { @Override public String getValue(MarkerItem item) { + if (item == null || item.getMarker() == null) { + return null; + } return item.getMarker().getAttribute("rulename", ""); } }
true
true
public String getValue(MarkerItem item) { return item.getMarker().getAttribute("rulename", ""); }
public String getValue(MarkerItem item) { if (item == null || item.getMarker() == null) { return null; } return item.getMarker().getAttribute("rulename", ""); }
diff --git a/plugins/org.bigraph.model/src/org/bigraph/model/loaders/EditXMLLoader.java b/plugins/org.bigraph.model/src/org/bigraph/model/loaders/EditXMLLoader.java index 58c787e3..9bea25b2 100644 --- a/plugins/org.bigraph.model/src/org/bigraph/model/loaders/EditXMLLoader.java +++ b/plugins/org.bigraph.model/src/org/bigraph/model/loaders/EditXMLLoader.java @@ -1,116 +1,118 @@ package org.bigraph.model.loaders; import org.bigraph.model.Edit; import org.bigraph.model.Edit.ChangeDescriptorAddDescriptor; import org.bigraph.model.assistants.FileData; import org.bigraph.model.changes.descriptors.BoundDescriptor; import org.bigraph.model.changes.descriptors.IChangeDescriptor; import org.bigraph.model.process.IParticipant; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import static org.bigraph.model.loaders.RedNamespaceConstants.EDIT; import static org.bigraph.model.utilities.ArrayIterable.forNodeList; public class EditXMLLoader extends XMLLoader { public interface Participant extends IParticipant { IChangeDescriptor getDescriptor(Element descriptor); IChangeDescriptor getRenameDescriptor(Element id, String name); } { addParticipant(new BigraphEditLoader()); } public EditXMLLoader() { } public EditXMLLoader(Loader parent) { super(parent); } @Override public Edit importObject() throws LoadFailedException { try { Document d = validate(parse(getInputStream()), Schemas.getEditSchema()); Edit ed = makeObject(d.getDocumentElement()); FileData.setFile(ed, getFile()); return ed; } catch (LoadFailedException e) { throw e; } catch (Exception e) { throw new LoadFailedException(e); } } private final Participant bigraphEditHandler = new BigraphEditLoader(); private IChangeDescriptor makeDescriptor(Element el) { IChangeDescriptor cd = null; if ((cd = bigraphEditHandler.getDescriptor(el)) != null) return cd; for (Participant p : getParticipants(Participant.class)) { cd = p.getDescriptor(el); if (cd != null) break; } return cd; } private IChangeDescriptor makeRename(Element el) { Node id_ = el.getFirstChild(); if (!(id_ instanceof Element)) return null; Element id = (Element)id_; String name = getAttributeNS(el, EDIT, "name"); IChangeDescriptor cd = null; if ((cd = bigraphEditHandler.getRenameDescriptor(id, name)) != null) return cd; for (Participant p : getParticipants(Participant.class)) { cd = p.getRenameDescriptor(id, name); if (cd != null) break; } return cd; } @Override public Edit makeObject(Element el) throws LoadFailedException { cycleCheck(); String replacement = getAttributeNS(el, EDIT, "src"); if (replacement != null) return loadRelative(replacement, Edit.class, new EditXMLLoader(this)); Edit ed = new Edit(); int index = 0; for (Element i : forNodeList(el.getChildNodes()).filter(Element.class)) { String localName = i.getLocalName(), namespaceURI = i.getNamespaceURI(); IChangeDescriptor cd = null; if (EDIT.equals(namespaceURI)) { if ("edit".equals(localName)) { cd = new EditXMLLoader(this).makeObject(i); } else if ("rename".equals(localName)) { cd = makeRename(i); } } else cd = makeDescriptor(i); - if (cd != null) + if (cd != null) { addChange(new BoundDescriptor(ed, new ChangeDescriptorAddDescriptor( new Edit.Identifier(), index++, cd))); + } else throw new LoadFailedException( + "Couldn't create a change descriptor from element " + i); } executeUndecorators(ed, el); executeChanges(ed); return ed; } }
false
true
public Edit makeObject(Element el) throws LoadFailedException { cycleCheck(); String replacement = getAttributeNS(el, EDIT, "src"); if (replacement != null) return loadRelative(replacement, Edit.class, new EditXMLLoader(this)); Edit ed = new Edit(); int index = 0; for (Element i : forNodeList(el.getChildNodes()).filter(Element.class)) { String localName = i.getLocalName(), namespaceURI = i.getNamespaceURI(); IChangeDescriptor cd = null; if (EDIT.equals(namespaceURI)) { if ("edit".equals(localName)) { cd = new EditXMLLoader(this).makeObject(i); } else if ("rename".equals(localName)) { cd = makeRename(i); } } else cd = makeDescriptor(i); if (cd != null) addChange(new BoundDescriptor(ed, new ChangeDescriptorAddDescriptor( new Edit.Identifier(), index++, cd))); } executeUndecorators(ed, el); executeChanges(ed); return ed; }
public Edit makeObject(Element el) throws LoadFailedException { cycleCheck(); String replacement = getAttributeNS(el, EDIT, "src"); if (replacement != null) return loadRelative(replacement, Edit.class, new EditXMLLoader(this)); Edit ed = new Edit(); int index = 0; for (Element i : forNodeList(el.getChildNodes()).filter(Element.class)) { String localName = i.getLocalName(), namespaceURI = i.getNamespaceURI(); IChangeDescriptor cd = null; if (EDIT.equals(namespaceURI)) { if ("edit".equals(localName)) { cd = new EditXMLLoader(this).makeObject(i); } else if ("rename".equals(localName)) { cd = makeRename(i); } } else cd = makeDescriptor(i); if (cd != null) { addChange(new BoundDescriptor(ed, new ChangeDescriptorAddDescriptor( new Edit.Identifier(), index++, cd))); } else throw new LoadFailedException( "Couldn't create a change descriptor from element " + i); } executeUndecorators(ed, el); executeChanges(ed); return ed; }
diff --git a/src/Extensions/org/objectweb/proactive/extensions/masterworker/core/AOWorkerManager.java b/src/Extensions/org/objectweb/proactive/extensions/masterworker/core/AOWorkerManager.java index 5777d84eb..ddb1d8129 100644 --- a/src/Extensions/org/objectweb/proactive/extensions/masterworker/core/AOWorkerManager.java +++ b/src/Extensions/org/objectweb/proactive/extensions/masterworker/core/AOWorkerManager.java @@ -1,385 +1,386 @@ /* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis * Contact: proactive@objectweb.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.extensions.masterworker.core; import java.io.Serializable; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import org.objectweb.proactive.ActiveObjectCreationException; import org.objectweb.proactive.Body; import org.objectweb.proactive.InitActive; import org.objectweb.proactive.api.ProActiveObject; import org.objectweb.proactive.api.ProDeployment; import org.objectweb.proactive.api.ProFuture; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.body.exceptions.SendRequestCommunicationException; import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor; import org.objectweb.proactive.core.descriptor.data.VirtualNode; import org.objectweb.proactive.core.descriptor.data.VirtualNodeImpl; import org.objectweb.proactive.core.event.NodeCreationEvent; import org.objectweb.proactive.core.event.NodeCreationEventListener; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.core.util.wrapper.BooleanWrapper; import org.objectweb.proactive.extensions.masterworker.interfaces.internal.TaskProvider; import org.objectweb.proactive.extensions.masterworker.interfaces.internal.Worker; import org.objectweb.proactive.extensions.masterworker.interfaces.internal.WorkerManager; /** * <i><font size="-1" color="#FF0000">**For internal use only** </font></i><br> * The Worker Manager Active Object is responsible for the deployment of Workers :<br> * <ul> * <li> Through a ProActive deployment descriptor</li> * <li> Using an existing VirtualNode object</li> * <li> Using a collection of Nodes</li> * </ul> * * @author fviale * */ public class AOWorkerManager implements WorkerManager, NodeCreationEventListener, InitActive, Serializable { /** * */ private static final long serialVersionUID = -1488970573456417472L; /** * log4j logger for the worker manager */ protected static Logger logger = ProActiveLogger.getLogger(Loggers.MASTERWORKER_WORKERMANAGER); /** * stub on this active object */ protected Object stubOnThis; /** * how many workers have been created */ protected long workerNameCounter; /** * holds the virtual nodes, only used to kill the nodes when the worker manager is terminated */ protected Vector<VirtualNode> vnlist; /** * a thread pool used for worker creation */ protected ExecutorService threadPool; /** * true when the worker manager is terminated */ protected boolean isTerminated; /** * the entity which will provide tasks to the workers */ protected TaskProvider<Serializable> provider; /** * Initial memory of the workers */ protected Map<String, Object> initialMemory; /** * workers deployed so far */ protected Map<String, Worker> workers; /** * ProActive no arg constructor */ public AOWorkerManager() { } /** * Creates a task manager with the given task provider * @param provider the entity that will give tasks to the workers created * @param initialMemory the initial memory of the workers */ public AOWorkerManager(final TaskProvider<Serializable> provider, final Map<String, Object> initialMemory) { this.provider = provider; this.initialMemory = initialMemory; } /** * {@inheritDoc} */ public void addResources(final Collection<Node> nodes) { if (!isTerminated) { for (Node node : nodes) { threadPool.execute(new WorkerCreationHandler(node)); } } } /** * {@inheritDoc} */ public void addResources(final URL descriptorURL) { if (!isTerminated) { try { ProActiveDescriptor pad = ProDeployment.getProactiveDescriptor(descriptorURL.toExternalForm()); for (VirtualNode vn : pad.getVirtualNodes()) { addResources(vn); } } catch (ProActiveException e) { logger.error("Couldn't add the specified resources."); e.printStackTrace(); } } } /** * {@inheritDoc} */ public void addResources(final URL descriptorURL, final String virtualNodeName) { if (!isTerminated) { try { ProActiveDescriptor pad = ProDeployment.getProactiveDescriptor(descriptorURL.toExternalForm()); addResources(pad.getVirtualNode(virtualNodeName)); } catch (ProActiveException e) { logger.error("Couldn't add the specified resources."); e.printStackTrace(); } } } /** * {@inheritDoc} */ public void addResources(final VirtualNode virtualnode) { if (!isTerminated) { if (!virtualnode.isActivated()) { logger.warn("vn is not activated"); ((VirtualNodeImpl) virtualnode).addNodeCreationEventListener(this); virtualnode.activate(); } else { logger.warn("vn is activated"); try { Node[] nodes = virtualnode.getNodes(); addResources(Arrays.asList(nodes)); } catch (NodeException e) { e.printStackTrace(); } } vnlist.add(virtualnode); if (logger.isDebugEnabled()) { logger.debug("Virtual Node " + virtualnode.getName() + " added to worker manager"); } } } /** * Creates a worker object inside the given node * @param node the node on which a worker will be created */ protected void createWorker(final Node node) { if (!isTerminated) { try { if (logger.isDebugEnabled()) { logger.debug("Creating worker on " + node.getNodeInformation().getName()); } String workername = node.getVMInformation().getHostName() + "_" + workerNameCounter++; // Creates the worker which will automatically connect to the master workers.put(workername, (Worker) ProActiveObject.newActive( AOWorker.class.getName(), new Object[] { workername, provider, initialMemory }, node)); if (logger.isDebugEnabled()) { logger.debug("Worker " + workername + " created on " + node.getNodeInformation().getName()); } } catch (ActiveObjectCreationException e) { e.printStackTrace(); // bad node } catch (NodeException e) { e.printStackTrace(); // bad node } } } /** * {@inheritDoc} */ public void initActivity(final Body body) { stubOnThis = ProActiveObject.getStubOnThis(); workerNameCounter = 0; workers = new HashMap<String, Worker>(); vnlist = new Vector<VirtualNode>(); isTerminated = false; if (logger.isDebugEnabled()) { logger.debug("Resource Manager Initialized"); } threadPool = Executors.newCachedThreadPool(); } /** * {@inheritDoc} */ public void nodeCreated(final NodeCreationEvent event) { // get the node logger.warn("nodeCreated " + event.getNode()); Node node = event.getNode(); try { threadPool.execute(new WorkerCreationHandler(node)); } catch (java.util.concurrent.RejectedExecutionException e) { } } /** * {@inheritDoc} */ public BooleanWrapper terminate(final boolean freeResources) { isTerminated = true; if (logger.isDebugEnabled()) { logger.debug("Terminating WorkerManager..."); } try { // we shutdown the thread pool, no new thread will be accepted threadPool.shutdown(); for (int i = 0; i < vnlist.size(); i++) { // we wait for every node creation, in case some nodes were not already deployed try { if (vnlist.get(i).getNbMappedNodes() > vnlist.get(i) .getNumberOfCurrentlyCreatedNodes()) { // implicit wait of created nodes vnlist.get(i).getNodes(); } } catch (org.objectweb.proactive.core.node.NodeException e) { // do nothing, we ignore node creation exceptions } } // we wait that all threads creating active objects finish threadPool.awaitTermination(120, TimeUnit.SECONDS); // we send the terminate message to every thread for (Entry<String, Worker> worker : workers.entrySet()) { try { BooleanWrapper term = worker.getValue().terminate(); - ProFuture.waitFor(term); + // as it is a termination algorithm we wait a bit, but not forever + ProFuture.waitFor(term, 3 * 1000); if (logger.isDebugEnabled()) { logger.debug(worker.getKey() + " freed."); } } catch (SendRequestCommunicationException exp) { if (logger.isDebugEnabled()) { logger.debug(worker.getKey() + " is already freed."); } } } for (int i = 0; i < vnlist.size(); i++) { // if the user asked it, we also release the resources, by killing all JVMs if (freeResources) { if (logger.isDebugEnabled()) { logger.debug("Killing all active objects..."); } try { ((VirtualNodeImpl) vnlist.get(i)).killAll(false); } catch (Exception e) { // ignore exceptions when killing } } } // finally we terminate this active object ProActiveObject.terminateActiveObject(true); // success if (logger.isDebugEnabled()) { logger.debug("WorkerManager terminated..."); } return new BooleanWrapper(true); } catch (Exception e) { logger.error("Couldn't Terminate the Resource manager"); e.printStackTrace(); return new BooleanWrapper(false); } } /** * Internal class which creates workers on top of nodes * @author fviale * */ protected class WorkerCreationHandler implements Runnable { /** * node on which workers will be created */ private Node node = null; /** * Creates a worker on a given node * @param node */ public WorkerCreationHandler(final Node node) { this.node = node; } /** * {@inheritDoc} */ public void run() { createWorker(node); } } }
true
true
public BooleanWrapper terminate(final boolean freeResources) { isTerminated = true; if (logger.isDebugEnabled()) { logger.debug("Terminating WorkerManager..."); } try { // we shutdown the thread pool, no new thread will be accepted threadPool.shutdown(); for (int i = 0; i < vnlist.size(); i++) { // we wait for every node creation, in case some nodes were not already deployed try { if (vnlist.get(i).getNbMappedNodes() > vnlist.get(i) .getNumberOfCurrentlyCreatedNodes()) { // implicit wait of created nodes vnlist.get(i).getNodes(); } } catch (org.objectweb.proactive.core.node.NodeException e) { // do nothing, we ignore node creation exceptions } } // we wait that all threads creating active objects finish threadPool.awaitTermination(120, TimeUnit.SECONDS); // we send the terminate message to every thread for (Entry<String, Worker> worker : workers.entrySet()) { try { BooleanWrapper term = worker.getValue().terminate(); ProFuture.waitFor(term); if (logger.isDebugEnabled()) { logger.debug(worker.getKey() + " freed."); } } catch (SendRequestCommunicationException exp) { if (logger.isDebugEnabled()) { logger.debug(worker.getKey() + " is already freed."); } } } for (int i = 0; i < vnlist.size(); i++) { // if the user asked it, we also release the resources, by killing all JVMs if (freeResources) { if (logger.isDebugEnabled()) { logger.debug("Killing all active objects..."); } try { ((VirtualNodeImpl) vnlist.get(i)).killAll(false); } catch (Exception e) { // ignore exceptions when killing } } } // finally we terminate this active object ProActiveObject.terminateActiveObject(true); // success if (logger.isDebugEnabled()) { logger.debug("WorkerManager terminated..."); } return new BooleanWrapper(true); } catch (Exception e) { logger.error("Couldn't Terminate the Resource manager"); e.printStackTrace(); return new BooleanWrapper(false); } }
public BooleanWrapper terminate(final boolean freeResources) { isTerminated = true; if (logger.isDebugEnabled()) { logger.debug("Terminating WorkerManager..."); } try { // we shutdown the thread pool, no new thread will be accepted threadPool.shutdown(); for (int i = 0; i < vnlist.size(); i++) { // we wait for every node creation, in case some nodes were not already deployed try { if (vnlist.get(i).getNbMappedNodes() > vnlist.get(i) .getNumberOfCurrentlyCreatedNodes()) { // implicit wait of created nodes vnlist.get(i).getNodes(); } } catch (org.objectweb.proactive.core.node.NodeException e) { // do nothing, we ignore node creation exceptions } } // we wait that all threads creating active objects finish threadPool.awaitTermination(120, TimeUnit.SECONDS); // we send the terminate message to every thread for (Entry<String, Worker> worker : workers.entrySet()) { try { BooleanWrapper term = worker.getValue().terminate(); // as it is a termination algorithm we wait a bit, but not forever ProFuture.waitFor(term, 3 * 1000); if (logger.isDebugEnabled()) { logger.debug(worker.getKey() + " freed."); } } catch (SendRequestCommunicationException exp) { if (logger.isDebugEnabled()) { logger.debug(worker.getKey() + " is already freed."); } } } for (int i = 0; i < vnlist.size(); i++) { // if the user asked it, we also release the resources, by killing all JVMs if (freeResources) { if (logger.isDebugEnabled()) { logger.debug("Killing all active objects..."); } try { ((VirtualNodeImpl) vnlist.get(i)).killAll(false); } catch (Exception e) { // ignore exceptions when killing } } } // finally we terminate this active object ProActiveObject.terminateActiveObject(true); // success if (logger.isDebugEnabled()) { logger.debug("WorkerManager terminated..."); } return new BooleanWrapper(true); } catch (Exception e) { logger.error("Couldn't Terminate the Resource manager"); e.printStackTrace(); return new BooleanWrapper(false); } }
diff --git a/src/org/ssgwt/client/ui/form/ComplexInputForm.java b/src/org/ssgwt/client/ui/form/ComplexInputForm.java index b4c7966..6190f54 100644 --- a/src/org/ssgwt/client/ui/form/ComplexInputForm.java +++ b/src/org/ssgwt/client/ui/form/ComplexInputForm.java @@ -1,583 +1,583 @@ package org.ssgwt.client.ui.form; import java.util.ArrayList; import java.util.List; import org.ssgwt.client.ui.form.event.ComplexInputFormAddEvent; import org.ssgwt.client.ui.form.event.ComplexInputFormCancelEvent; import org.ssgwt.client.ui.form.event.ComplexInputFormConfirmationEvent; import org.ssgwt.client.ui.form.event.ComplexInputFormConfirmationEvent.ComplexInputFormConfirmationHandler; import org.ssgwt.client.ui.form.event.ComplexInputFormFieldAddEvent; import org.ssgwt.client.ui.form.event.ComplexInputFormFieldAddEvent.ComplexInputFormFieldAddHandler; import org.ssgwt.client.ui.form.event.ComplexInputFormRemoveEvent; import com.google.gwt.core.client.GWT; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.Widget; /** * Complex input form that allows more complex fields to be added like an array of DynamicForm * * Constructor need the OutterVO, InnerVO, TheField and the class literal of the TheField class * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param <OutterVO> The object type of super form that the ComplexInputForm vo(InnerVO) is mapped to. * @param <InnerVO> The object type the inner form uses to get values from updates the value of the fields on * @param <TheField> The type of input field. */ public abstract class ComplexInputForm<OutterVO, InnerVO, TheField extends ComplexInput<InnerVO>, T> extends Composite implements HasValue<List<InnerVO>>, InputField<OutterVO, List>, ComplexInputFormAddEvent.ComplexInputFormAddHandler, ComplexInputFormRemoveEvent.ComplexInputFormRemoveHandler, ComplexInputFormConfirmationEvent.ComplexInputFormConfirmationHasHandlers, ComplexInputFormCancelEvent.ComplexInputFormCancelHandler, ComplexInputFormFieldAddEvent.ComplexInputFormFieldAddHasHandlers, ComplexInputFormFieldAddEvent.ComplexInputFormFieldAddHandler { /** * Contain the list of the embedded Vos */ private List<InnerVO> innerVOs = new ArrayList<InnerVO>(); /** * Array list contains the fields */ private final ArrayList<TheField> fields = new ArrayList<TheField>(); /** * Used to apply the gray row style */ private static String STYLE_GRAY_ROW = "ssGWT-displayGrayRow"; /** * Used to apply the first row style */ private static String STYLE_FIRST_ROW = "ssGWT-DynamicInputFirstRow"; /** * Main panel */ private final FlowPanel complexInputForm = new FlowPanel(); /** * The class Literal of the type of field on the form */ private Class<?> classLiteral; /** * Injectioned object */ private T object; /** * Flag for if the field is required */ private boolean isRequired = false; /** * Flag for if the field is ReadOnly */ private boolean isReadOnly = false; /** * Creator used to create the InputFields */ private InputFieldCreator inputFieldCreator; /** * Complex Input Form Remove Event */ private ComplexInputFormRemoveEvent complexInputFormRemoveEvent; /** * Class constructor * * Build the form and fields based on the field class literal * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param classLiteral - Class Literal of the type of field on the form */ public ComplexInputForm(Class<?> classLiteral) { this((InputFieldCreator)GWT.create(InputFieldCreator.class), classLiteral); } /** * Class constructor * * Build the form and fields based on the field class literal * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param inputFieldCreator - input Field Creator * @param classLiteral - Class Literal of the type of field on the form */ public ComplexInputForm(InputFieldCreator inputFieldCreator, Class<?> classLiteral) { initWidget(complexInputForm); this.classLiteral = classLiteral; this.inputFieldCreator = inputFieldCreator; } /** * Set an embedded Object on the the fields created * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param object - The object to set */ public void setEmbeddedObject(T object) { this.object = object; } /** * Return the type of the return type by the input field * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @return the List class literal */ @Override public Class<List> getReturnType() { return List.class; } /** * Return the field as Widget * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @return the form as a Widget */ @Override public Widget getInputFieldWidget() { return this.asWidget(); } /** * Get the values from the fields and add it to the Vo * * Populate the inner list of VOs with the data in the fields * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @return a list of the innerVO */ @Override public List<InnerVO> getValue() { int counter = 0; if (innerVOs != null) { innerVOs.clear(); } for (TheField field : fields) { if (counter == 0) { counter++; continue; } innerVOs.add(field.getValue()); } return innerVOs; } /** * Adds the a new field. * * This is a function that is called from the addField event that adds a * new field on the form after the data from the field in index is saved * in the array of VOs. * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 */ public void addField() { // Add the value in the current field at index 0 to the list of VO's // Index 0 is always the add field and the is the only field that can be in add state. if (innerVOs == null) { innerVOs = new ArrayList<InnerVO>(); } innerVOs.add(fields.get(0).getValue()); // After the values in the field is added to the array innerVO set the field to view state fields.get(0).setViewState(); // Create a new add field TheField field = createField(); // Add the required handlers addComplexInputFormHandlers(field); // Add the new add field at index 0. // The field at index 0 is always the add field fields.add(0, field); // The field needs to be re-added to the main panel because the added // field needs to be at the top and cannot be added on a panel at index 0. // The index of the field in the array can be re-added to the main panel // in the correct order but it first needs to be cleared from the main panel. complexInputForm.clear(); for (TheField inputField : fields) { if (!inputField.dynamicFormPanel.isVisible()) { inputField.addStyleName(STYLE_GRAY_ROW); } inputField.removeStyleName(STYLE_FIRST_ROW); complexInputForm.add(inputField); } field.removeStyleName(STYLE_GRAY_ROW); field.addStyleName(STYLE_FIRST_ROW); } /** * Add the required handlers to the field so that once the add button or removed button is * clicked on the field the form can handle the event. * - ComplexInputFormRemoveHandler * - ComplexInputFormAddHandler * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param field - The field to add the handlers to */ public void addComplexInputFormHandlers(TheField field) { field.addComplexInputFormRemoveHandler(this); field.addComplexInputFormAddHandler(this); field.addComplexInputFormCancelHandler(this); field.addComplexInputFormFieldAddHandler(this); } /** * This function is called on the remove event the remove the field from the * form, field list and the field value form the list of inner VOs. * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param removeVO - The Vo to remove from the inner VO list * @param removeField - The field to remove from the form */ public void removeField(InnerVO removeVO, TheField removeField) { innerVOs.remove(removeVO); fields.remove(removeField); complexInputForm.remove(removeField); } /** * Set the values on the fields within the form. * The fields is auto generated for each VO in the list. * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param value - The list of the inner VO to add to the form */ @Override public void setValue(List<InnerVO> value) { this.innerVOs = value; // Clear the field list fields.clear(); if (value != null) { for (InnerVO property : this.innerVOs) { generateField(property); } } this.render(); } /** * Generate the field based on the VO passed * and set the data on the field. * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param value - The innerVo that contains the data to set on the field */ private void generateField(InnerVO value) { // Create the field based on the class literal TheField field = createField(); // Set the value on the field field.setValue(value); // Add the handlers addComplexInputFormHandlers(field); // Set the field to view state field.setViewState(); // Add the fields to fields list that will be used by the render function to add the fields on the form fields.add(field); } /** * Add the field on the form it self. * This is only called on create and on setValue * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 */ private void render() { // Clear all the fields on the form complexInputForm.clear(); // Create the add field and add it at index 0. TheField addField = createField(); addComplexInputFormHandlers(addField); fields.add(0, addField); // Loop through the field list and add to the form for (TheField field : fields) { field.addStyleName(STYLE_GRAY_ROW); complexInputForm.add(field); } addField.removeStyleName(STYLE_GRAY_ROW); addField.addStyleName(STYLE_FIRST_ROW); } /** * Handler for the ComplexInputFormRemove that is catch from the the event fired on the remove button * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param event - The event object that was fired */ @Override public void onComplexInputFormRemove(ComplexInputFormRemoveEvent event) { complexInputFormRemoveEvent = event; ComplexInputFormConfirmationEvent.fire(true, this, new AsyncCallback<T>() { /** * The onfailure method that will not do anything * * @author Ashwin Arendse <ashwin.arendse@a24group.com> * @since 03 December 2012 * * @param caught - The exception that were caught */ @Override public void onFailure(Throwable caught) { } /** * The on success if a user discards his changes * * @author Ashwin Arendse <ashwin.arendse@a24group.com> * @since 03 December 2012 * * @param result - the result of tpe T */ @Override public void onSuccess(T result) { // Remove a field removeField( - (InnerVO) complexInputFormRemoveEvent.getRemoveObjectVO(), - (TheField) complexInputFormRemoveEvent.getRemoveObjectField() - ); + (InnerVO) complexInputFormRemoveEvent.getRemoveObjectVO(), + (TheField) complexInputFormRemoveEvent.getRemoveObjectField() + ); } }); } /** * Function for when a ComplexInputFormConfirmationHandler needed to be added * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param handler - The handler that can re added */ @Override public HandlerRegistration addComplexInputFormConfirmationHandler(ComplexInputFormConfirmationHandler handler) { return this.addHandler(handler, ComplexInputFormConfirmationEvent.TYPE); } /** * Adds a ComplexInputFormFieldAddHandler that listen for the ComplexInputFormFieldAddEvent to * fire on each time a new field is added * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 1 March 2013 * * @return {@link HandlerRegistration} */ @Override public HandlerRegistration addComplexInputFormFieldAddHandler(ComplexInputFormFieldAddHandler handler) { return this.addHandler(handler, ComplexInputFormFieldAddEvent.TYPE); } /** * Handler for the ComplexInputFormRemove that is catch from the the event fired on the remove button * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param event - The event object that was fired */ @Override public void onComplexInputFormCancel(ComplexInputFormCancelEvent event) { ComplexInputFormConfirmationEvent.fire(false, this, event.getCallback()); } /** * Function that listen for the ComplexInputFormFieldAddEvent each time a recored have been added * in one of the nesting complex input forms and re-fire the event with the place where the event * originated form as the source. * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 1 March 2013 * * @param handler - The handler that can re added */ @Override public void onComplexInputFormFieldAdd(ComplexInputFormFieldAddEvent event) { fireEvent(event); } /** * Handler for the ComplexInputFormAdd that is catch from the the event fired on the add button * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param event - The event object that was fired */ @Override public void onComplexInputFormAdd(ComplexInputFormAddEvent event) { // Add a new field addField(); ComplexInputFormFieldAddEvent.fire(this); } /** * Function that create a field and inject the an object * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 */ public TheField createField() { TheField addField = (TheField) inputFieldCreator.createItem(classLiteral); addField.setInjectedObject(object); addField.constructor(); return addField; } /** * Set the values and could fire an event * * NOTE : This function is not fully implemented * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param value - The values to set. * @param fireEvents - Flag for the firing of events */ @Override public void setValue(List<InnerVO> value, boolean fireEvents) { setValue(value); } /** * Function for when a ValueChangeHandler needed to be added * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param handler - The handler that can re added */ @Override public HandlerRegistration addValueChangeHandler(ValueChangeHandler<List<InnerVO>> handler) { return null; } /** * This function is forced implemented but does not have a use in the form * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @return false */ @Override public boolean isRequired() { return this.isRequired; } /** * Set the fields to Required or not * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param required - If the field is required */ @Override public void setRequired(boolean required) { this.isRequired = required; for (TheField field : fields) { field.setRequired(required); } } /** * To set the fields to read only or not * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @param readOnly - If the field is readOnly */ @Override public void setReadOnly(boolean readOnly) { this.isReadOnly = readOnly; for (TheField field : fields) { field.setReadOnly(readOnly); } } /** * Getter for the fields added to the compexInputForm input form. * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 01 March 2013 * * @return the lsit og fields */ public List<TheField> getFields() { return this.fields; } /** * Retrun the boolean if the the field is ReadOnly or not * * @author Alec Erasmus<alec.erasmus@a24group.com> * @since 22 November 2012 * * @return if the field is Read Only */ @Override public boolean isReadOnly() { return this.isReadOnly; } /** * This function will determine whether there is unsaved data on a complex input * * @author Ruan Naude <ruan.naude@a24group.com> * @since 10 Dec 2012 */ public boolean hasUnsavedData() { for (TheField field : fields) { if (field.hasUnsavedData()) { return true; } } return false; } }
true
true
public void onComplexInputFormRemove(ComplexInputFormRemoveEvent event) { complexInputFormRemoveEvent = event; ComplexInputFormConfirmationEvent.fire(true, this, new AsyncCallback<T>() { /** * The onfailure method that will not do anything * * @author Ashwin Arendse <ashwin.arendse@a24group.com> * @since 03 December 2012 * * @param caught - The exception that were caught */ @Override public void onFailure(Throwable caught) { } /** * The on success if a user discards his changes * * @author Ashwin Arendse <ashwin.arendse@a24group.com> * @since 03 December 2012 * * @param result - the result of tpe T */ @Override public void onSuccess(T result) { // Remove a field removeField( (InnerVO) complexInputFormRemoveEvent.getRemoveObjectVO(), (TheField) complexInputFormRemoveEvent.getRemoveObjectField() ); } }); }
public void onComplexInputFormRemove(ComplexInputFormRemoveEvent event) { complexInputFormRemoveEvent = event; ComplexInputFormConfirmationEvent.fire(true, this, new AsyncCallback<T>() { /** * The onfailure method that will not do anything * * @author Ashwin Arendse <ashwin.arendse@a24group.com> * @since 03 December 2012 * * @param caught - The exception that were caught */ @Override public void onFailure(Throwable caught) { } /** * The on success if a user discards his changes * * @author Ashwin Arendse <ashwin.arendse@a24group.com> * @since 03 December 2012 * * @param result - the result of tpe T */ @Override public void onSuccess(T result) { // Remove a field removeField( (InnerVO) complexInputFormRemoveEvent.getRemoveObjectVO(), (TheField) complexInputFormRemoveEvent.getRemoveObjectField() ); } }); }
diff --git a/trunk/crux-dev/src/main/java/org/cruxframework/crux/core/rebind/rest/JSonSerializerProxyCreator.java b/trunk/crux-dev/src/main/java/org/cruxframework/crux/core/rebind/rest/JSonSerializerProxyCreator.java index 4a9ab92bb..4f2905c1c 100644 --- a/trunk/crux-dev/src/main/java/org/cruxframework/crux/core/rebind/rest/JSonSerializerProxyCreator.java +++ b/trunk/crux-dev/src/main/java/org/cruxframework/crux/core/rebind/rest/JSonSerializerProxyCreator.java @@ -1,709 +1,709 @@ /* * Copyright 2013 cruxframework.org. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.cruxframework.crux.core.rebind.rest; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.cruxframework.crux.core.client.bean.JsonEncoder; import org.cruxframework.crux.core.client.collection.FastList; import org.cruxframework.crux.core.client.collection.FastMap; import org.cruxframework.crux.core.client.utils.EscapeUtils; import org.cruxframework.crux.core.client.utils.JsUtils; import org.cruxframework.crux.core.client.utils.StringUtils; import org.cruxframework.crux.core.rebind.AbstractProxyCreator; import org.cruxframework.crux.core.rebind.CruxGeneratorException; import org.cruxframework.crux.core.shared.json.annotations.JsonIgnore; import org.cruxframework.crux.core.shared.json.annotations.JsonProperty; import org.cruxframework.crux.core.shared.json.annotations.JsonSubTypes; import org.cruxframework.crux.core.shared.json.annotations.JsonSubTypes.Type; import org.cruxframework.crux.core.utils.JClassUtils; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.ext.GeneratorContext; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.typeinfo.JArrayType; import com.google.gwt.core.ext.typeinfo.JClassType; import com.google.gwt.core.ext.typeinfo.JMethod; import com.google.gwt.core.ext.typeinfo.JPrimitiveType; import com.google.gwt.core.ext.typeinfo.JType; import com.google.gwt.core.ext.typeinfo.NotFoundException; import com.google.gwt.dev.generator.NameFactory; import com.google.gwt.json.client.JSONArray; import com.google.gwt.json.client.JSONBoolean; import com.google.gwt.json.client.JSONNull; import com.google.gwt.json.client.JSONNumber; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.gwt.json.client.JSONString; import com.google.gwt.json.client.JSONValue; import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; /** * @author Thiago da Rosa de Bustamante * */ public class JSonSerializerProxyCreator extends AbstractProxyCreator { private final JType targetObjectType; private JClassType jsonEncoderType; private JClassType listType; private JClassType setType; private JClassType mapType; private JClassType javascriptObjectType; private JClassType exceptionType; private JClassType stringType; private Set<String> referencedTypes = new HashSet<String>(); private static NameFactory nameFactory = new NameFactory(); public JSonSerializerProxyCreator(GeneratorContext context, TreeLogger logger, JType targetObjectType) { this(context, logger, targetObjectType, new HashSet<String>()); } public JSonSerializerProxyCreator(GeneratorContext context, TreeLogger logger, JType targetObjectType, Set<String> referencedTypes) { super(logger, context, true); registerReferencedType(targetObjectType, referencedTypes); jsonEncoderType = context.getTypeOracle().findType(JsonEncoder.class.getCanonicalName()); exceptionType = context.getTypeOracle().findType(Exception.class.getCanonicalName()); listType = context.getTypeOracle().findType(List.class.getCanonicalName()); setType = context.getTypeOracle().findType(Set.class.getCanonicalName()); mapType = context.getTypeOracle().findType(Map.class.getCanonicalName()); javascriptObjectType = context.getTypeOracle().findType(JavaScriptObject.class.getCanonicalName()); stringType = context.getTypeOracle().findType(String.class.getCanonicalName()); this.targetObjectType = targetObjectType; } private void registerReferencedType(JType targetObjectType, Set<String> referencedTypes) { if(targetObjectType.isClassOrInterface() != null && !JClassUtils.isSimpleType(targetObjectType)) { referencedTypes.add(targetObjectType.getQualifiedSourceName()); } this.referencedTypes = referencedTypes; } @Override protected void generateProxyMethods(SourcePrinter srcWriter) throws CruxGeneratorException { generateEncodeMethod(srcWriter); generateDecodeMethod(srcWriter); } @Override public String getProxyQualifiedName() { return jsonEncoderType.getPackage().getName()+"."+getProxySimpleName(); } @Override public String getProxySimpleName() { String typeName = targetObjectType.getParameterizedQualifiedSourceName().replaceAll("\\W", "_"); return typeName+"_JsonEncoder"; } @Override protected SourcePrinter getSourcePrinter() { String packageName = jsonEncoderType.getPackage().getName(); PrintWriter printWriter = context.tryCreate(logger, packageName, getProxySimpleName()); if (printWriter == null) { return null; } ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, getProxySimpleName()); String[] imports = getImports(); for (String imp : imports) { composerFactory.addImport(imp); } return new SourcePrinter(composerFactory.createSourceWriter(context, printWriter), logger); } /** * @return */ protected String[] getImports() { String[] imports = new String[] { JSONParser.class.getCanonicalName(), JSONValue.class.getCanonicalName(), JSONObject.class.getCanonicalName(), JSONArray.class.getCanonicalName(), JSONNull.class.getCanonicalName(), JSONNumber.class.getCanonicalName(), JSONBoolean.class.getCanonicalName(), JSONString.class.getCanonicalName(), JsUtils.class.getCanonicalName(), GWT.class.getCanonicalName() }; return imports; } private void generateEncodeMethod(SourcePrinter srcWriter) { srcWriter.println("public JSONValue encode(" + targetObjectType.getParameterizedQualifiedSourceName() + " object){"); String encoded = generateEncodeObject(srcWriter, targetObjectType, "object"); srcWriter.println("return "+encoded+";"); srcWriter.println("}"); } private void generateDecodeMethod(SourcePrinter srcWriter) { srcWriter.println("public " + targetObjectType.getParameterizedQualifiedSourceName() + " decode(JSONValue json){"); String decodedString = generateDecodeJsonValue(srcWriter, targetObjectType, "json"); srcWriter.println("return "+decodedString+";"); srcWriter.println("}"); } private String generateDecodeJsonValue(SourcePrinter srcWriter, JType objectType, String jsonValueVar) { String resultObjectVar = nameFactory.createName("o"); String resultSourceName = objectType.getParameterizedQualifiedSourceName(); srcWriter.println(resultSourceName + " "+resultObjectVar + " = " + JClassUtils.getEmptyValueForType(objectType) +";"); srcWriter.println("if ("+jsonValueVar+" != null && "+jsonValueVar+".isNull() == null){"); JArrayType objectArrayType = objectType.isArray(); if (objectArrayType != null) { generateDecodeStringForArrayType(srcWriter, objectArrayType, jsonValueVar, resultObjectVar, resultSourceName); } else if(objectType.getQualifiedSourceName().equals(Void.class.getCanonicalName())) { srcWriter.println("return null;"); } else if (JClassUtils.isSimpleType(objectType)) { generateDecodeStringForJsonFriendlyType(srcWriter, objectType, jsonValueVar, resultObjectVar); } else { JClassType objectClassType = objectType.isClassOrInterface(); if (objectClassType == null) { throw new CruxGeneratorException("Type ["+objectType.getParameterizedQualifiedSourceName()+"] can not be deserialized by JsonEncoder. "); } if (objectClassType.isAssignableTo(javascriptObjectType)) { srcWriter.println(resultObjectVar+" = ("+resultSourceName+")JsUtils.fromJSONValue("+jsonValueVar+");"); } else if (isCollection(objectClassType)) { generateDecodeStringForCollectionType(srcWriter, objectClassType, jsonValueVar, resultObjectVar, resultSourceName); } else { generateDecodeStringForCustomType(srcWriter, objectClassType, jsonValueVar, resultObjectVar, resultSourceName); } } srcWriter.println("}"); return resultObjectVar; } private void generateDecodeStringForArrayType(SourcePrinter srcWriter, JArrayType objectArrayType, String jsonValueVar, String resultObjectVar, String resultSourceName) { JType targetObjectType = objectArrayType.getComponentType(); String jsonCollectionVar = generateJSONValueCollectionForDecode(srcWriter, jsonValueVar, true); srcWriter.println(resultObjectVar+" = new "+targetObjectType.getParameterizedQualifiedSourceName()+"["+jsonCollectionVar+".size()];"); String loopIndexVar = nameFactory.createName("i"); String loopJsonVar = nameFactory.createName("loopJsonVar"); srcWriter.println("for (int "+loopIndexVar+"=0; "+loopIndexVar+" < "+jsonCollectionVar+".size(); "+loopIndexVar+"++){"); srcWriter.println("JSONValue "+loopJsonVar+"="+jsonCollectionVar + ".get("+loopIndexVar+");"); String decodedJsonValue = generateDecodeJsonValue(srcWriter, targetObjectType, loopJsonVar); srcWriter.println(resultObjectVar+"["+loopIndexVar+"] = "+decodedJsonValue+";"); srcWriter.println("}"); } private String generateEncodeObject(SourcePrinter srcWriter, JType objectType, String objectVar) { String resultJSONValueVar = nameFactory.createName("json"); srcWriter.println("JSONValue "+resultJSONValueVar + " = JSONNull.getInstance();"); boolean isPrimitive = objectType.isPrimitive() != null; if (!isPrimitive) { srcWriter.println("if ("+objectVar+" != null){"); } JArrayType objectArrayType = objectType.isArray(); if (objectArrayType != null) { generateEncodeStringForArrayType(srcWriter, objectArrayType, objectVar, resultJSONValueVar); } else if (JClassUtils.isSimpleType(objectType)) { generateEncodeStringForJsonFriendlyType(srcWriter, objectType, objectVar, resultJSONValueVar); } else { JClassType objectClassType = objectType.isClassOrInterface(); if (objectClassType == null) { throw new CruxGeneratorException("Type ["+objectType.getParameterizedQualifiedSourceName()+"] can not be serialized by JsonEncoder. "); } if (objectClassType.isAssignableTo(javascriptObjectType)) { srcWriter.println(resultJSONValueVar+" = JsUtils.toJSONValue("+objectVar+");"); } else if (isCollection(objectClassType)) { generateEncodeStringForCollectionType(srcWriter, objectClassType, objectVar, resultJSONValueVar); } else { generateEncodeStringForCustomType(srcWriter, objectClassType, objectVar, resultJSONValueVar); } } if (!isPrimitive) { srcWriter.println("}"); } return resultJSONValueVar; } private void generateEncodeStringForArrayType(SourcePrinter srcWriter, JArrayType objectArrayType, String objectVar, String resultJSONValueVar) { JType targetObjectType = objectArrayType.getComponentType(); generateJSONValueCollectionForEncode(srcWriter, resultJSONValueVar, true); String loopObjVar = nameFactory.createName("loopObjVar"); srcWriter.println("for ("+targetObjectType.getParameterizedQualifiedSourceName()+" "+loopObjVar+": "+objectVar+"){"); String encodedObjectVar = generateEncodeObject(srcWriter, targetObjectType, loopObjVar); srcWriter.println(resultJSONValueVar+".isArray().set("+resultJSONValueVar+".isArray().size(), "+encodedObjectVar+");"); srcWriter.println("}"); } private boolean isCollection(JClassType objectType) { if ((objectType.isAssignableTo(listType)) || (objectType.isAssignableTo(setType)) || (objectType.isAssignableTo(mapType)) || (objectType.getQualifiedSourceName().equals(FastMap.class.getCanonicalName())) || (objectType.getQualifiedSourceName().equals(FastList.class.getCanonicalName()))) { return true; } return false; } private void generateDecodeStringForJsonFriendlyType(SourcePrinter srcWriter, JType objectType, String jsonValueVar, String resultObjectVar) { try { if (objectType.getQualifiedSourceName().equals("java.lang.String") || objectType.isEnum() != null) { srcWriter.println(resultObjectVar + " = " + JClassUtils.getParsingExpressionForSimpleType(jsonValueVar+".isString().stringValue()", objectType) + ";"); } else if (objectType.getQualifiedSourceName().equals("java.sql.Date")) { logger.log(TreeLogger.Type.WARN, "We recommend to avoid type ["+objectType.getParameterizedQualifiedSourceName()+"]: " + "there are some known issues with respect to Jackson timezone handling, partly due to design of this class."); srcWriter.println(resultObjectVar + " = " + JClassUtils.getParsingExpressionForSimpleType(jsonValueVar+".isString().stringValue().replace(\"/\",\"-\")", objectType) + ";"); } else { srcWriter.println(resultObjectVar + " = " + JClassUtils.getParsingExpressionForSimpleType(jsonValueVar+".toString()", objectType) + ";"); } } catch (NotFoundException e) { throw new CruxGeneratorException("Type ["+objectType.getParameterizedQualifiedSourceName()+"] can not be deserialized by JsonEncoder. " + "Error Interpreting object type.", e); } } private void generateEncodeStringForJsonFriendlyType(SourcePrinter srcWriter, JType objectType, String objectVar, String resultJSONValueVar) { if (objectType.getQualifiedSourceName().equals(String.class.getCanonicalName())) { srcWriter.println(resultJSONValueVar + " = new JSONString(" + objectVar + ");"); } else if ((objectType == JPrimitiveType.BYTE) || (objectType.getQualifiedSourceName().equals(Byte.class.getCanonicalName())) ||(objectType == JPrimitiveType.SHORT) || (objectType.getQualifiedSourceName().equals(Short.class.getCanonicalName())) ||(objectType == JPrimitiveType.INT) || (objectType.getQualifiedSourceName().equals(Integer.class.getCanonicalName())) ||(objectType == JPrimitiveType.LONG) || (objectType.getQualifiedSourceName().equals(Long.class.getCanonicalName())) ||(objectType == JPrimitiveType.FLOAT) || (objectType.getQualifiedSourceName().equals(Float.class.getCanonicalName())) ||(objectType == JPrimitiveType.DOUBLE) || (objectType.getQualifiedSourceName().equals(Double.class.getCanonicalName()))) { srcWriter.println(resultJSONValueVar + " = new JSONNumber(" + objectVar + ");"); } else if (objectType.getQualifiedSourceName().equals(Date.class.getCanonicalName())) { srcWriter.println(resultJSONValueVar + " = new JSONNumber(" + objectVar + ".getTime());"); } else if (objectType.getQualifiedSourceName().equals(java.sql.Date.class.getCanonicalName())) { srcWriter.println(resultJSONValueVar + " = new JSONNumber(" + objectVar + ".getTime());"); } else if ((objectType == JPrimitiveType.BOOLEAN) || (objectType.getQualifiedSourceName().equals(Boolean.class.getCanonicalName()))) { srcWriter.println(resultJSONValueVar + " = JSONBoolean.getInstance(" + objectVar + ");"); } else if ((objectType == JPrimitiveType.CHAR) || (objectType.getQualifiedSourceName().equals(Character.class.getCanonicalName()))) { srcWriter.println(resultJSONValueVar + " = new JSONString(\"\"+" + objectVar + ");"); } else if (objectType.isEnum() != null) { srcWriter.println(resultJSONValueVar + " = new JSONString(" + objectVar + ".toString());"); } else if (objectType.getQualifiedSourceName().equals(BigInteger.class.getCanonicalName()) || objectType.getQualifiedSourceName().equals(BigDecimal.class.getCanonicalName())) { srcWriter.println(resultJSONValueVar + " = new JSONString(" + objectVar + ".toString());"); } else { throw new CruxGeneratorException("Type ["+objectType.getParameterizedQualifiedSourceName()+"] can not be serialized by JsonEncoder. " + "Error Interpreting object type."); } } private void generateDecodeStringForCollectionType(SourcePrinter srcWriter, JClassType objectType, String jsonValueVar, String resultObjectVar, String resultSourceName) { boolean isList = (!objectType.isAssignableTo(mapType)) && (!objectType.getQualifiedSourceName().equals(FastMap.class.getCanonicalName())); String jsonCollectionVar = generateJSONValueCollectionForDecode(srcWriter, jsonValueVar, isList); JClassType targetObjectType = getCollectionTargetType(objectType); generateCollectionInstantiation(srcWriter, objectType, resultObjectVar, resultSourceName, targetObjectType); String serializerName = new JSonSerializerProxyCreator(context, logger, targetObjectType, new HashSet<String>(referencedTypes)).create(); String serializerVar = nameFactory.createName("serializer"); srcWriter.println(serializerName+" "+serializerVar+" = new "+serializerName+"();"); if (isList) { srcWriter.println("for (int i=0; i < "+jsonCollectionVar+".size(); i++){"); srcWriter.println(resultObjectVar+".add("+serializerVar+".decode("+jsonCollectionVar + ".get(i)));"); srcWriter.println("}"); } else { srcWriter.println("for (String key : "+jsonCollectionVar+".keySet()){"); srcWriter.println(resultObjectVar+".put(key, "+serializerVar+".decode("+jsonCollectionVar + ".get(key)));"); srcWriter.println("}"); } } private void generateCollectionInstantiation(SourcePrinter srcWriter, JClassType objectType, String resultObjectVar, String resultSourceName, JClassType targetObjectType) { if (objectType.getQualifiedSourceName().equals(FastList.class.getCanonicalName()) || objectType.getQualifiedSourceName().equals(FastMap.class.getCanonicalName()) || objectType.isInterface() == null) { srcWriter.println(resultObjectVar+" = new "+resultSourceName+"();"); } else { if (objectType.isAssignableTo(listType)) { srcWriter.println(resultObjectVar+" = new "+ArrayList.class.getCanonicalName()+"<"+targetObjectType.getParameterizedQualifiedSourceName()+">();"); } else if (objectType.isAssignableTo(setType)) { srcWriter.println(resultObjectVar+" = new "+HashSet.class.getCanonicalName()+"<"+targetObjectType.getParameterizedQualifiedSourceName()+">();"); } else if (objectType.isAssignableTo(mapType)) { JClassType keyObjectType = objectType.isParameterized().getTypeArgs()[0]; if (!keyObjectType.getQualifiedSourceName().equals("java.lang.String")) { throw new CruxGeneratorException("Type ["+objectType.getParameterizedQualifiedSourceName()+"] can not be deserialized by JsonEncoder. " + "Map Key is invalid. Only Strings are accepted."); } srcWriter.println(resultObjectVar+" = new "+HashMap.class.getCanonicalName()+"<"+ keyObjectType.getParameterizedQualifiedSourceName()+","+targetObjectType.getParameterizedQualifiedSourceName()+">();"); } else { throw new CruxGeneratorException("Type ["+objectType.getParameterizedQualifiedSourceName()+"] can not be deserialized by JsonEncoder. " + "Invalid collection type."); } } } private String generateJSONValueCollectionForDecode(SourcePrinter srcWriter, String jsonValueVar, boolean isList) { String jsonCollectionVar; if (isList) { jsonCollectionVar = nameFactory.createName("jsonArray"); srcWriter.println("JSONArray "+jsonCollectionVar+" = "+jsonValueVar+".isArray();"); } else { jsonCollectionVar = nameFactory.createName("jsonMap"); srcWriter.println("JSONObject "+jsonCollectionVar+" = "+jsonValueVar+".isObject();"); } return jsonCollectionVar; } private void generateEncodeStringForCollectionType(SourcePrinter srcWriter, JClassType objectType, String objectVar, String resultJSONValueVar) { boolean isList = (!objectType.isAssignableTo(mapType)) && (!objectType.getQualifiedSourceName().equals(FastMap.class.getCanonicalName())); JClassType targetObjectType = getCollectionTargetType(objectType); generateJSONValueCollectionForEncode(srcWriter, resultJSONValueVar, isList); String serializerName = new JSonSerializerProxyCreator(context, logger, targetObjectType, new HashSet<String>(referencedTypes)).create(); String serializerVar = nameFactory.createName("serializer"); srcWriter.println(serializerName+" "+serializerVar+" = new "+serializerName+"();"); if (isList) { srcWriter.println("for ("+targetObjectType.getParameterizedQualifiedSourceName()+" obj: "+objectVar+"){"); srcWriter.println(resultJSONValueVar+".isArray().set("+resultJSONValueVar+".isArray().size(), "+serializerVar+".encode(obj));"); srcWriter.println("}"); } else { srcWriter.println("for (String key : "+objectVar+".keySet()){"); srcWriter.println(resultJSONValueVar+".isObject().put(key, "+serializerVar+".encode("+objectVar+".get(key)));"); srcWriter.println("}"); } } private void generateJSONValueCollectionForEncode(SourcePrinter srcWriter, String resultJSONValueVar, boolean isList) { if (isList) { srcWriter.println(resultJSONValueVar+" = new JSONArray();"); } else { srcWriter.println(resultJSONValueVar+" = new JSONObject();"); } } private JClassType getCollectionTargetType(JClassType objectType) { JClassType targetObjectType; if (objectType.getQualifiedSourceName().equals(FastList.class.getCanonicalName()) || objectType.getQualifiedSourceName().equals(FastMap.class.getCanonicalName()) || (objectType.isAssignableTo(listType)) || (objectType.isAssignableTo(setType))) { targetObjectType = objectType.isParameterized().getTypeArgs()[0]; } else if (objectType.isAssignableTo(mapType)) { JClassType keyObjectType = objectType.isParameterized().getTypeArgs()[0]; if (!keyObjectType.getQualifiedSourceName().equals("java.lang.String")) { throw new CruxGeneratorException("Type ["+objectType.getParameterizedQualifiedSourceName()+"] can not be serialized by JsonEncoder. " + "Map Key is invalid. Only Strings are accepted."); } targetObjectType = objectType.isParameterized().getTypeArgs()[1]; } else { throw new CruxGeneratorException("Type ["+objectType.getParameterizedQualifiedSourceName()+"] can not be serialized by JsonEncoder. " + "Invalid collection type."); } return targetObjectType; } private void generateDecodeStringForCustomType(SourcePrinter srcWriter, JClassType objectType, String jsonValueVar, String resultObjectVar, String resultSourceName) { JsonSubTypes jsonSubTypesClass = objectType.getAnnotation(JsonSubTypes.class); boolean hasJsonSubTypes = jsonSubTypesClass != null && jsonSubTypesClass.value() != null; if (hasJsonSubTypes) { boolean first = true; for(Type innerObject : jsonSubTypesClass.value()) { if (!first) { srcWriter.println("else "); } first = false; srcWriter.println("if ("+StringUtils.class.getCanonicalName()+".unsafeEquals("+jsonValueVar+".isObject().get("+ EscapeUtils.quote(JsonSubTypes.SUB_TYPE_SELECTOR)+").isString().stringValue(),"+ EscapeUtils.quote(innerObject.value().getName())+")){"); JClassType innerClass = context.getTypeOracle().findType(innerObject.value().getCanonicalName()); String serializerName = getSerializerForType(innerClass); srcWriter.println(resultObjectVar+" = new "+serializerName+"().decode("+jsonValueVar+");"); srcWriter.println("}"); } if (!first) { srcWriter.println("else "); } srcWriter.println("if ("+StringUtils.class.getCanonicalName()+".unsafeEquals("+jsonValueVar+".isObject().get("+ EscapeUtils.quote(JsonSubTypes.SUB_TYPE_SELECTOR)+").isString().stringValue(),"+ EscapeUtils.quote(objectType.getQualifiedSourceName())+")){"); - srcWriter.println(resultObjectVar+" = GWT.create("+objectType.getParameterizedQualifiedSourceName()+".class);"); + srcWriter.println(resultObjectVar+" = GWT.create("+objectType.getQualifiedSourceName()+".class);"); } String jsonObjectVar = nameFactory.createName("jsonObject"); srcWriter.println("JSONObject "+jsonObjectVar+" = "+jsonValueVar+".isObject();"); if (objectType.isAssignableTo(exceptionType) && objectType.findConstructor(new JType[]{stringType}) != null) { srcWriter.println("if ("+jsonObjectVar+".containsKey(\"message\")){"); srcWriter.println(resultObjectVar+" = new "+resultSourceName+"(("+jsonObjectVar+".get(\"message\") != null && "+jsonObjectVar+".get(\"message\").isString() != null) ? "+jsonObjectVar+".get(\"message\").isString().stringValue() : \"\");"); srcWriter.println("} else {"); - srcWriter.println(resultObjectVar+" = GWT.create("+resultSourceName+".class);"); + srcWriter.println(resultObjectVar+" = GWT.create("+objectType.getQualifiedSourceName()+".class);"); srcWriter.println("}"); } else { if(!hasJsonSubTypes) { - srcWriter.println(resultObjectVar+" = GWT.create("+resultSourceName+".class);"); + srcWriter.println(resultObjectVar+" = GWT.create("+objectType.getQualifiedSourceName()+".class);"); } } List<JMethod> setterMethods = JClassUtils.getSetterMethods(objectType); srcWriter.println("if ("+jsonObjectVar+" != null) {"); for (JMethod method : setterMethods) { if (method.getAnnotation(JsonIgnore.class) == null) { String property = null; JsonProperty jsonProperty = method.getAnnotation(JsonProperty.class); if (jsonProperty != null) { property = jsonProperty.value(); } else { property = JClassUtils.getPropertyForGetterOrSetterMethod(method); } JType paramType = method.getParameterTypes()[0]; String serializerName = getSerializerForType(paramType); srcWriter.println(resultObjectVar+"."+method.getName()+"(new "+serializerName+"().decode("+jsonObjectVar+".get("+EscapeUtils.quote(property)+")));"); } } if (hasJsonSubTypes) { srcWriter.println("}"); } srcWriter.println("}"); } private String getSerializerForType(JType paramType) { HashSet<String> referencedTypesBackup = new HashSet<String>(referencedTypes); //check cyclic reference and clear user types after the recursive call. if(referencedTypes.contains(paramType.getQualifiedSourceName())) { logger.log(TreeLogger.Type.WARN, "Recursive reference found: " + referencedTypes.toString() + "-> please check for cyclic references in order to avoid infinite loops."); } //run nested evaluation. String serializerName = new JSonSerializerProxyCreator(context, logger, paramType, referencedTypes).create(); //revert processed list this.referencedTypes = referencedTypesBackup; return serializerName; } private void generateEncodeStringForCustomType(SourcePrinter srcWriter, JClassType objectType, String objectVar, String resultJSONValueVar) { JsonSubTypes jsonSubTypesClass = objectType.getAnnotation(JsonSubTypes.class); boolean hasJsonSubTypes = jsonSubTypesClass != null && jsonSubTypesClass.value() != null; if (hasJsonSubTypes) { boolean first = true; for(Type innerObject : jsonSubTypesClass.value()) { if (!first) { srcWriter.print("else "); } first = false; srcWriter.println("if ("+StringUtils.class.getCanonicalName()+".unsafeEquals("+objectVar+".getClass().getName(),"+EscapeUtils.quote(innerObject.value().getName())+")){"); JClassType innerClass = context.getTypeOracle().findType(innerObject.value().getCanonicalName()); String serializerName = getSerializerForType(innerClass); srcWriter.println(resultJSONValueVar+" = new "+serializerName+"().encode(("+innerClass.getQualifiedSourceName()+")"+objectVar+");"); srcWriter.println("}"); } if (!first) { srcWriter.print("else "); } srcWriter.println("if ("+StringUtils.class.getCanonicalName()+".unsafeEquals("+objectVar+".getClass().getName(),"+EscapeUtils.quote(objectType.getQualifiedSourceName())+")){"); srcWriter.println(resultJSONValueVar+" = new JSONObject();"); srcWriter.println("}"); srcWriter.println("if ("+resultJSONValueVar+" != null && !JSONNull.getInstance().equals("+resultJSONValueVar+")){"); srcWriter.println(resultJSONValueVar+".isObject().put("+EscapeUtils.quote(JsonSubTypes.SUB_TYPE_SELECTOR)+", new JSONString("+objectVar+".getClass().getName()));"); srcWriter.println("}"); } if(!hasJsonSubTypes) { srcWriter.println(resultJSONValueVar+" = new JSONObject();"); } srcWriter.println("if ("+resultJSONValueVar+" != null && !JSONNull.getInstance().equals("+resultJSONValueVar+")){"); generateEncodeStringForCustomTypeInnerProperties(srcWriter, objectType, objectVar, resultJSONValueVar); srcWriter.println("}"); } private void generateEncodeStringForCustomTypeInnerProperties(SourcePrinter srcWriter, JClassType objectType, String objectVar, String resultJSONValueVar) { List<JMethod> getterMethods = JClassUtils.getGetterMethods(objectType); for (JMethod method : getterMethods) { if (method.getAnnotation(JsonIgnore.class) == null) { String property = null; JsonProperty jsonProperty = method.getAnnotation(JsonProperty.class); if (jsonProperty != null) { property = jsonProperty.value(); } else { property = JClassUtils.getPropertyForGetterOrSetterMethod(method); } JType returnType = method.getReturnType(); String serializerName = getSerializerForType(returnType); boolean primitive = returnType.isPrimitive() != null; if (!primitive) { srcWriter.println("if ("+objectVar+"."+method.getName()+"() != null){"); } srcWriter.println(resultJSONValueVar+".isObject().put("+EscapeUtils.quote(property)+", new "+serializerName+"().encode("+objectVar+"."+method.getName()+"()));"); if (!primitive) { srcWriter.println("}"); } } } } }
false
true
private void generateDecodeStringForCustomType(SourcePrinter srcWriter, JClassType objectType, String jsonValueVar, String resultObjectVar, String resultSourceName) { JsonSubTypes jsonSubTypesClass = objectType.getAnnotation(JsonSubTypes.class); boolean hasJsonSubTypes = jsonSubTypesClass != null && jsonSubTypesClass.value() != null; if (hasJsonSubTypes) { boolean first = true; for(Type innerObject : jsonSubTypesClass.value()) { if (!first) { srcWriter.println("else "); } first = false; srcWriter.println("if ("+StringUtils.class.getCanonicalName()+".unsafeEquals("+jsonValueVar+".isObject().get("+ EscapeUtils.quote(JsonSubTypes.SUB_TYPE_SELECTOR)+").isString().stringValue(),"+ EscapeUtils.quote(innerObject.value().getName())+")){"); JClassType innerClass = context.getTypeOracle().findType(innerObject.value().getCanonicalName()); String serializerName = getSerializerForType(innerClass); srcWriter.println(resultObjectVar+" = new "+serializerName+"().decode("+jsonValueVar+");"); srcWriter.println("}"); } if (!first) { srcWriter.println("else "); } srcWriter.println("if ("+StringUtils.class.getCanonicalName()+".unsafeEquals("+jsonValueVar+".isObject().get("+ EscapeUtils.quote(JsonSubTypes.SUB_TYPE_SELECTOR)+").isString().stringValue(),"+ EscapeUtils.quote(objectType.getQualifiedSourceName())+")){"); srcWriter.println(resultObjectVar+" = GWT.create("+objectType.getParameterizedQualifiedSourceName()+".class);"); } String jsonObjectVar = nameFactory.createName("jsonObject"); srcWriter.println("JSONObject "+jsonObjectVar+" = "+jsonValueVar+".isObject();"); if (objectType.isAssignableTo(exceptionType) && objectType.findConstructor(new JType[]{stringType}) != null) { srcWriter.println("if ("+jsonObjectVar+".containsKey(\"message\")){"); srcWriter.println(resultObjectVar+" = new "+resultSourceName+"(("+jsonObjectVar+".get(\"message\") != null && "+jsonObjectVar+".get(\"message\").isString() != null) ? "+jsonObjectVar+".get(\"message\").isString().stringValue() : \"\");"); srcWriter.println("} else {"); srcWriter.println(resultObjectVar+" = GWT.create("+resultSourceName+".class);"); srcWriter.println("}"); } else { if(!hasJsonSubTypes) { srcWriter.println(resultObjectVar+" = GWT.create("+resultSourceName+".class);"); } } List<JMethod> setterMethods = JClassUtils.getSetterMethods(objectType); srcWriter.println("if ("+jsonObjectVar+" != null) {"); for (JMethod method : setterMethods) { if (method.getAnnotation(JsonIgnore.class) == null) { String property = null; JsonProperty jsonProperty = method.getAnnotation(JsonProperty.class); if (jsonProperty != null) { property = jsonProperty.value(); } else { property = JClassUtils.getPropertyForGetterOrSetterMethod(method); } JType paramType = method.getParameterTypes()[0]; String serializerName = getSerializerForType(paramType); srcWriter.println(resultObjectVar+"."+method.getName()+"(new "+serializerName+"().decode("+jsonObjectVar+".get("+EscapeUtils.quote(property)+")));"); } } if (hasJsonSubTypes) { srcWriter.println("}"); } srcWriter.println("}"); }
private void generateDecodeStringForCustomType(SourcePrinter srcWriter, JClassType objectType, String jsonValueVar, String resultObjectVar, String resultSourceName) { JsonSubTypes jsonSubTypesClass = objectType.getAnnotation(JsonSubTypes.class); boolean hasJsonSubTypes = jsonSubTypesClass != null && jsonSubTypesClass.value() != null; if (hasJsonSubTypes) { boolean first = true; for(Type innerObject : jsonSubTypesClass.value()) { if (!first) { srcWriter.println("else "); } first = false; srcWriter.println("if ("+StringUtils.class.getCanonicalName()+".unsafeEquals("+jsonValueVar+".isObject().get("+ EscapeUtils.quote(JsonSubTypes.SUB_TYPE_SELECTOR)+").isString().stringValue(),"+ EscapeUtils.quote(innerObject.value().getName())+")){"); JClassType innerClass = context.getTypeOracle().findType(innerObject.value().getCanonicalName()); String serializerName = getSerializerForType(innerClass); srcWriter.println(resultObjectVar+" = new "+serializerName+"().decode("+jsonValueVar+");"); srcWriter.println("}"); } if (!first) { srcWriter.println("else "); } srcWriter.println("if ("+StringUtils.class.getCanonicalName()+".unsafeEquals("+jsonValueVar+".isObject().get("+ EscapeUtils.quote(JsonSubTypes.SUB_TYPE_SELECTOR)+").isString().stringValue(),"+ EscapeUtils.quote(objectType.getQualifiedSourceName())+")){"); srcWriter.println(resultObjectVar+" = GWT.create("+objectType.getQualifiedSourceName()+".class);"); } String jsonObjectVar = nameFactory.createName("jsonObject"); srcWriter.println("JSONObject "+jsonObjectVar+" = "+jsonValueVar+".isObject();"); if (objectType.isAssignableTo(exceptionType) && objectType.findConstructor(new JType[]{stringType}) != null) { srcWriter.println("if ("+jsonObjectVar+".containsKey(\"message\")){"); srcWriter.println(resultObjectVar+" = new "+resultSourceName+"(("+jsonObjectVar+".get(\"message\") != null && "+jsonObjectVar+".get(\"message\").isString() != null) ? "+jsonObjectVar+".get(\"message\").isString().stringValue() : \"\");"); srcWriter.println("} else {"); srcWriter.println(resultObjectVar+" = GWT.create("+objectType.getQualifiedSourceName()+".class);"); srcWriter.println("}"); } else { if(!hasJsonSubTypes) { srcWriter.println(resultObjectVar+" = GWT.create("+objectType.getQualifiedSourceName()+".class);"); } } List<JMethod> setterMethods = JClassUtils.getSetterMethods(objectType); srcWriter.println("if ("+jsonObjectVar+" != null) {"); for (JMethod method : setterMethods) { if (method.getAnnotation(JsonIgnore.class) == null) { String property = null; JsonProperty jsonProperty = method.getAnnotation(JsonProperty.class); if (jsonProperty != null) { property = jsonProperty.value(); } else { property = JClassUtils.getPropertyForGetterOrSetterMethod(method); } JType paramType = method.getParameterTypes()[0]; String serializerName = getSerializerForType(paramType); srcWriter.println(resultObjectVar+"."+method.getName()+"(new "+serializerName+"().decode("+jsonObjectVar+".get("+EscapeUtils.quote(property)+")));"); } } if (hasJsonSubTypes) { srcWriter.println("}"); } srcWriter.println("}"); }
diff --git a/src/main/java/net/pms/encoders/VLCVideo.java b/src/main/java/net/pms/encoders/VLCVideo.java index 8a090dab4..c450b474e 100644 --- a/src/main/java/net/pms/encoders/VLCVideo.java +++ b/src/main/java/net/pms/encoders/VLCVideo.java @@ -1,512 +1,512 @@ /* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2008 A.Brochard * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.pms.encoders; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.factories.Borders; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import com.sun.jna.Platform; import java.awt.ComponentOrientation; import java.awt.Font; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.IOException; import java.util.*; import javax.swing.*; import net.pms.Messages; import net.pms.configuration.PmsConfiguration; import net.pms.configuration.RendererConfiguration; import net.pms.dlna.DLNAMediaAudio; import net.pms.dlna.DLNAMediaInfo; import net.pms.dlna.DLNAMediaSubtitle; import net.pms.dlna.DLNAResource; import net.pms.formats.Format; import net.pms.io.OutputParams; import net.pms.io.PipeProcess; import net.pms.io.ProcessWrapper; import net.pms.io.ProcessWrapperImpl; import net.pms.network.HTTPResource; import net.pms.util.FormLayoutUtil; import net.pms.util.PlayerUtil; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Use VLC as a backend transcoder. Note that 0.x and 1.x versions are * unsupported (and probably will crash). Only the latest version will be * supported * * @author Leon Blakey <lord.quackstar@gmail.com> */ public class VLCVideo extends Player { private static final Logger LOGGER = LoggerFactory.getLogger(VLCVideo.class); private static final String COL_SPEC = "left:pref, 3dlu, p, 3dlu, 0:grow"; private static final String ROW_SPEC = "p, 3dlu, p, 3dlu, p, 9dlu, p, 3dlu, p, 3dlu, p"; protected final PmsConfiguration configuration; public static final String ID = "vlctranscoder"; protected JTextField audioPri; protected JTextField subtitlePri; protected JTextField scale; protected JCheckBox experimentalCodecs; protected JCheckBox audioSyncEnabled; protected JTextField sampleRate; protected JCheckBox sampleRateOverride; protected JTextField extraParams; protected boolean videoRemux; public VLCVideo(PmsConfiguration configuration) { this.configuration = configuration; } @Override public int purpose() { return VIDEO_SIMPLEFILE_PLAYER; } @Override public String id() { return ID; } @Override public boolean isTimeSeekable() { return true; } @Override public boolean avisynth() { return false; } @Override public String[] args() { return new String[]{}; } @Override public String name() { return "VLC"; } @Override public int type() { return Format.VIDEO; } @Override public String mimeType() { // I think? return HTTPResource.VIDEO_TRANSCODE; } @Override public String executable() { return configuration.getVlcPath(); } /** * Pick codecs for VLC based on formats the renderer supports; * * @param renderer The {@link RendererConfiguration}. * @return The codec configuration */ protected CodecConfig genConfig(RendererConfiguration renderer) { CodecConfig config = new CodecConfig(); if (renderer.isTranscodeToWMV()) { // Assume WMV = XBox = all media renderers with this flag LOGGER.debug("Using XBox WMV codecs"); config.videoCodec = "wmv2"; config.audioCodec = "wma"; config.container = "asf"; } else if (renderer.isTranscodeToMPEGTSAC3()) { // Default codecs for DLNA standard LOGGER.debug("Using DLNA standard codecs with ts container"); config.videoCodec = "mp2v"; config.audioCodec = "mp2a"; // NOTE: a52 sometimes causes audio to stop after ~5 mins config.container = "ts"; } else if (renderer.isTranscodeToH264TSAC3()) { LOGGER.debug("Using H.264 and AC-3 with ts container"); config.videoCodec = "h264"; config.audioCodec = "mp2a"; // NOTE: a52 sometimes causes audio to stop after ~5 mins config.container = "ts"; videoRemux = true; } else { // Default codecs for DLNA standard LOGGER.debug("Using DLNA standard codecs with ps (default) container"); config.videoCodec = "mp2v"; config.audioCodec = "mp2a"; // NOTE: a52 sometimes causes audio to stop after ~5 mins config.container = "ps"; } LOGGER.trace("Using " + config.videoCodec + ", " + config.audioCodec + ", " + config.container); /** // Audio sample rate handling if (sampleRateOverride.isSelected()) { config.sampleRate = Integer.valueOf(sampleRate.getText()); } */ // This has caused garbled audio, so only enable when told to if (audioSyncEnabled.isSelected()) { config.extraTrans.put("audio-sync", ""); } return config; } protected static class CodecConfig { String videoCodec; String audioCodec; String container; String extraParams; HashMap<String, Object> extraTrans = new HashMap<>(); int sampleRate; } protected Map<String, Object> getEncodingArgs(CodecConfig config, OutputParams params) { // See: http://www.videolan.org/doc/streaming-howto/en/ch03.html // See: http://wiki.videolan.org/Codec Map<String, Object> args = new HashMap<>(); // Codecs to use args.put("vcodec", config.videoCodec); args.put("acodec", config.audioCodec); // Bitrate in kbit/s if (!videoRemux) { args.put("vb", "4096"); } args.put("ab", configuration.getAudioBitrate()); // Video scaling args.put("scale", "1.0"); // Audio Channels int channels = 2; /** * Uncomment this block when we use a52 instead of mp2a if (params.aid.getAudioProperties().getNumberOfChannels() > 2 && configuration.getAudioChannelCount() == 6) { channels = 6; } */ args.put("channels", channels); // Static sample rate // TODO: Does WMA still need a sample rate of 41000 for Xbox compatibility? args.put("samplerate", "48000"); // Recommended on VLC DVD encoding page args.put("keyint", 16); // Recommended on VLC DVD encoding page args.put("strict-rc", ""); // Stream subtitles to client // args.add("scodec=dvbs"); // args.add("senc=dvbsub"); // Hardcode subtitles into video args.put("soverlay", ""); // Add extra args args.putAll(config.extraTrans); return args; } @Override public ProcessWrapper launchTranscode(String fileName, DLNAResource dlna, DLNAMediaInfo media, OutputParams params) throws IOException { boolean isWindows = Platform.isWindows(); // Make sure we can play this CodecConfig config = genConfig(params.mediaRenderer); PipeProcess tsPipe = new PipeProcess("VLC" + System.currentTimeMillis() + "." + config.container); ProcessWrapper pipe_process = tsPipe.getPipeProcess(); LOGGER.trace("filename: " + fileName); LOGGER.trace("dlna: " + dlna); LOGGER.trace("media: " + media); LOGGER.trace("outputparams: " + params); // XXX it can take a long time for Windows to create a named pipe // (and mkfifo can be slow if /tmp isn't memory-mapped), so start this as early as possible pipe_process.runInNewThread(); tsPipe.deleteLater(); params.input_pipes[0] = tsPipe; params.minBufferSize = params.minFileSize; params.secondread_minsize = 100000; List<String> cmdList = new ArrayList<>(); cmdList.add(executable()); cmdList.add("-I"); cmdList.add("dummy"); // Disable hardware acceleration which is enabled by default if (!configuration.isGPUAcceleration()) { cmdList.add("--no-ffmpeg-hw"); } // Useful for the more esoteric codecs people use if (experimentalCodecs.isSelected()) { cmdList.add("--sout-ffmpeg-strict=-2"); } // Stop the DOS box from appearing on windows if (isWindows) { cmdList.add("--dummy-quiet"); } // File needs to be given before sout, otherwise vlc complains cmdList.add(fileName); // Huge fake track id that shouldn't conflict with any real subtitle or audio id. Hopefully. String disableSuffix = "track=214748361"; // Handle audio language if (params.aid != null) { // User specified language at the client, acknowledge it if (params.aid.getLang() == null || params.aid.getLang().equals("und")) { // VLC doesn't understand und, but does understand a non existant track cmdList.add("--audio-" + disableSuffix); } else { // Load by ID (better) cmdList.add("--audio-track=" + params.aid.getId()); } } else { // Not specified, use language from GUI cmdList.add("--audio-language=" + audioPri.getText()); } // Handle subtitle language if (params.sid != null) { // User specified language at the client, acknowledge it if (params.sid.getLang() == null || params.sid.getLang().equals("und")) { // VLC doesn't understand und, but does understand a non existant track cmdList.add("--sub-" + disableSuffix); } else { // Load by ID (better) cmdList.add("--sub-track=" + params.sid.getId()); } } else if (!configuration.isDisableSubtitles()) { // Not specified, use language from GUI if enabled cmdList.add("--sub-language=" + subtitlePri.getText()); } else { cmdList.add("--sub-" + disableSuffix); } // x264 options if (videoRemux) { cmdList.add("--sout-x264-preset"); cmdList.add("superfast"); cmdList.add("--sout-x264-crf"); cmdList.add("20"); } // Skip forward if nessesary if (params.timeseek != 0) { cmdList.add("--start-time"); cmdList.add(String.valueOf(params.timeseek)); } // Generate encoding args StringBuilder encodingArgsBuilder = new StringBuilder(); for (Map.Entry<String, Object> curEntry : getEncodingArgs(config, params).entrySet()) { encodingArgsBuilder.append(curEntry.getKey()).append("=").append(curEntry.getValue()).append(","); } // Add our transcode options String transcodeSpec = String.format( "#transcode{%s}:std{access=file,mux=%s,dst=\"%s%s\"}", encodingArgsBuilder.toString(), config.container, (isWindows ? "\\\\" : ""), tsPipe.getInputPipe() ); cmdList.add("--sout"); cmdList.add(transcodeSpec); - // Force VLC to die when finished - cmdList.add("vlc:// quit"); + // Force VLC to exit when finished + cmdList.add("vlc://quit"); // Add any extra parameters if (!extraParams.getText().trim().isEmpty()) { // Add each part as a new item cmdList.addAll(Arrays.asList(StringUtils.split(extraParams.getText().trim(), " "))); } // Pass to process wrapper String[] cmdArray = new String[cmdList.size()]; cmdList.toArray(cmdArray); cmdArray = finalizeTranscoderArgs(fileName, dlna, media, params, cmdArray); LOGGER.trace("Finalized args: " + StringUtils.join(cmdArray, " ")); ProcessWrapperImpl pw = new ProcessWrapperImpl(cmdArray, params); pw.attachProcess(pipe_process); // TODO: Why is this here? try { Thread.sleep(150); } catch (InterruptedException e) { } pw.runInNewThread(); return pw; } @Override public JComponent config() { // Apply the orientation for the locale Locale locale = new Locale(configuration.getLanguage()); ComponentOrientation orientation = ComponentOrientation.getOrientation(locale); String colSpec = FormLayoutUtil.getColSpec(COL_SPEC, orientation); FormLayout layout = new FormLayout(colSpec, ROW_SPEC); PanelBuilder builder = new PanelBuilder(layout); builder.setBorder(Borders.EMPTY_BORDER); builder.setOpaque(false); CellConstraints cc = new CellConstraints(); JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), FormLayoutUtil.flip(cc.xyw(1, 1, 5), colSpec, orientation)); cmp = (JComponent) cmp.getComponent(0); cmp.setFont(cmp.getFont().deriveFont(Font.BOLD)); experimentalCodecs = new JCheckBox(Messages.getString("VlcTrans.3"), configuration.isVlcExperimentalCodecs()); experimentalCodecs.setContentAreaFilled(false); experimentalCodecs.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { configuration.setVlcExperimentalCodecs(e.getStateChange() == ItemEvent.SELECTED); } }); builder.add(experimentalCodecs, FormLayoutUtil.flip(cc.xy(1, 3), colSpec, orientation)); audioSyncEnabled = new JCheckBox(Messages.getString("MEncoderVideo.2"), configuration.isVlcAudioSyncEnabled()); audioSyncEnabled.setContentAreaFilled(false); audioSyncEnabled.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { configuration.setVlcAudioSyncEnabled(e.getStateChange() == ItemEvent.SELECTED); } }); builder.add(audioSyncEnabled, FormLayoutUtil.flip(cc.xy(1, 5), colSpec, orientation)); // Developer stuff. Theoretically temporary cmp = builder.addSeparator(Messages.getString("VlcTrans.10"), FormLayoutUtil.flip(cc.xyw(1, 7, 5), colSpec, orientation)); cmp = (JComponent) cmp.getComponent(0); cmp.setFont(cmp.getFont().deriveFont(Font.BOLD)); // Add scale as a subpanel because it has an awkward layout /** mainPanel.append(Messages.getString("VlcTrans.11")); FormLayout scaleLayout = new FormLayout("pref,3dlu,pref", ""); DefaultFormBuilder scalePanel = new DefaultFormBuilder(scaleLayout); double startingScale = Double.valueOf(configuration.getVlcScale()); scalePanel.append(scale = new JTextField(String.valueOf(startingScale))); final JSlider scaleSlider = new JSlider(JSlider.HORIZONTAL, 0, 10, (int) (startingScale * 10)); scalePanel.append(scaleSlider); scaleSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent ce) { String value = String.valueOf((double) scaleSlider.getValue() / 10); scale.setText(value); configuration.setVlcScale(value); } }); scale.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { String typed = scale.getText(); if (!typed.matches("\\d\\.\\d")) { return; } double value = Double.parseDouble(typed); scaleSlider.setValue((int) (value * 10)); configuration.setVlcScale(String.valueOf(value)); } }); mainPanel.append(scalePanel.getPanel(), 3); // Audio sample rate FormLayout sampleRateLayout = new FormLayout("right:pref, 3dlu, right:pref, 3dlu, right:pref, 3dlu, left:pref", ""); DefaultFormBuilder sampleRatePanel = new DefaultFormBuilder(sampleRateLayout); sampleRateOverride = new JCheckBox(Messages.getString("VlcTrans.17"), configuration.getVlcSampleRateOverride()); sampleRatePanel.append(Messages.getString("VlcTrans.18"), sampleRateOverride); sampleRate = new JTextField(configuration.getVlcSampleRate(), 8); sampleRate.setEnabled(configuration.getVlcSampleRateOverride()); sampleRate.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { configuration.setVlcSampleRate(sampleRate.getText()); } }); sampleRatePanel.append(Messages.getString("VlcTrans.19"), sampleRate); sampleRateOverride.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { boolean checked = e.getStateChange() == ItemEvent.SELECTED; configuration.setVlcSampleRateOverride(checked); sampleRate.setEnabled(checked); } }); mainPanel.nextLine(); mainPanel.append(sampleRatePanel.getPanel(), 7); // Extra options mainPanel.nextLine(); */ builder.addLabel(Messages.getString("VlcTrans.20"), FormLayoutUtil.flip(cc.xy(1, 9), colSpec, orientation)); extraParams = new JTextField(configuration.getFont()); extraParams.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { configuration.setFont(extraParams.getText()); } }); builder.add(extraParams, FormLayoutUtil.flip(cc.xyw(3, 9, 3), colSpec, orientation)); JPanel panel = builder.getPanel(); // Apply the orientation to the panel and all components in it panel.applyComponentOrientation(orientation); return panel; } @Override public boolean isCompatible(DLNAResource resource) { // Our implementation of VLC does not support external subtitles yet DLNAMediaSubtitle subtitle = resource.getMediaSubtitle(); if (subtitle != null && subtitle.getExternalFile() != null) { return false; } // VLC is unstable when transcoding from flac. It either crashes or sends video without audio. Confirmed with 2.0.6 DLNAMediaAudio audio = resource.getMediaAudio(); if (audio != null && audio.isFLAC() == true) { return false; } // Only handle local video - web video is handled by VLCWebVideo if (!PlayerUtil.isVideo(resource, Format.Identifier.WEB)) { return true; } return false; } }
true
true
public ProcessWrapper launchTranscode(String fileName, DLNAResource dlna, DLNAMediaInfo media, OutputParams params) throws IOException { boolean isWindows = Platform.isWindows(); // Make sure we can play this CodecConfig config = genConfig(params.mediaRenderer); PipeProcess tsPipe = new PipeProcess("VLC" + System.currentTimeMillis() + "." + config.container); ProcessWrapper pipe_process = tsPipe.getPipeProcess(); LOGGER.trace("filename: " + fileName); LOGGER.trace("dlna: " + dlna); LOGGER.trace("media: " + media); LOGGER.trace("outputparams: " + params); // XXX it can take a long time for Windows to create a named pipe // (and mkfifo can be slow if /tmp isn't memory-mapped), so start this as early as possible pipe_process.runInNewThread(); tsPipe.deleteLater(); params.input_pipes[0] = tsPipe; params.minBufferSize = params.minFileSize; params.secondread_minsize = 100000; List<String> cmdList = new ArrayList<>(); cmdList.add(executable()); cmdList.add("-I"); cmdList.add("dummy"); // Disable hardware acceleration which is enabled by default if (!configuration.isGPUAcceleration()) { cmdList.add("--no-ffmpeg-hw"); } // Useful for the more esoteric codecs people use if (experimentalCodecs.isSelected()) { cmdList.add("--sout-ffmpeg-strict=-2"); } // Stop the DOS box from appearing on windows if (isWindows) { cmdList.add("--dummy-quiet"); } // File needs to be given before sout, otherwise vlc complains cmdList.add(fileName); // Huge fake track id that shouldn't conflict with any real subtitle or audio id. Hopefully. String disableSuffix = "track=214748361"; // Handle audio language if (params.aid != null) { // User specified language at the client, acknowledge it if (params.aid.getLang() == null || params.aid.getLang().equals("und")) { // VLC doesn't understand und, but does understand a non existant track cmdList.add("--audio-" + disableSuffix); } else { // Load by ID (better) cmdList.add("--audio-track=" + params.aid.getId()); } } else { // Not specified, use language from GUI cmdList.add("--audio-language=" + audioPri.getText()); } // Handle subtitle language if (params.sid != null) { // User specified language at the client, acknowledge it if (params.sid.getLang() == null || params.sid.getLang().equals("und")) { // VLC doesn't understand und, but does understand a non existant track cmdList.add("--sub-" + disableSuffix); } else { // Load by ID (better) cmdList.add("--sub-track=" + params.sid.getId()); } } else if (!configuration.isDisableSubtitles()) { // Not specified, use language from GUI if enabled cmdList.add("--sub-language=" + subtitlePri.getText()); } else { cmdList.add("--sub-" + disableSuffix); } // x264 options if (videoRemux) { cmdList.add("--sout-x264-preset"); cmdList.add("superfast"); cmdList.add("--sout-x264-crf"); cmdList.add("20"); } // Skip forward if nessesary if (params.timeseek != 0) { cmdList.add("--start-time"); cmdList.add(String.valueOf(params.timeseek)); } // Generate encoding args StringBuilder encodingArgsBuilder = new StringBuilder(); for (Map.Entry<String, Object> curEntry : getEncodingArgs(config, params).entrySet()) { encodingArgsBuilder.append(curEntry.getKey()).append("=").append(curEntry.getValue()).append(","); } // Add our transcode options String transcodeSpec = String.format( "#transcode{%s}:std{access=file,mux=%s,dst=\"%s%s\"}", encodingArgsBuilder.toString(), config.container, (isWindows ? "\\\\" : ""), tsPipe.getInputPipe() ); cmdList.add("--sout"); cmdList.add(transcodeSpec); // Force VLC to die when finished cmdList.add("vlc:// quit"); // Add any extra parameters if (!extraParams.getText().trim().isEmpty()) { // Add each part as a new item cmdList.addAll(Arrays.asList(StringUtils.split(extraParams.getText().trim(), " "))); } // Pass to process wrapper String[] cmdArray = new String[cmdList.size()]; cmdList.toArray(cmdArray); cmdArray = finalizeTranscoderArgs(fileName, dlna, media, params, cmdArray); LOGGER.trace("Finalized args: " + StringUtils.join(cmdArray, " ")); ProcessWrapperImpl pw = new ProcessWrapperImpl(cmdArray, params); pw.attachProcess(pipe_process); // TODO: Why is this here? try { Thread.sleep(150); } catch (InterruptedException e) { } pw.runInNewThread(); return pw; }
public ProcessWrapper launchTranscode(String fileName, DLNAResource dlna, DLNAMediaInfo media, OutputParams params) throws IOException { boolean isWindows = Platform.isWindows(); // Make sure we can play this CodecConfig config = genConfig(params.mediaRenderer); PipeProcess tsPipe = new PipeProcess("VLC" + System.currentTimeMillis() + "." + config.container); ProcessWrapper pipe_process = tsPipe.getPipeProcess(); LOGGER.trace("filename: " + fileName); LOGGER.trace("dlna: " + dlna); LOGGER.trace("media: " + media); LOGGER.trace("outputparams: " + params); // XXX it can take a long time for Windows to create a named pipe // (and mkfifo can be slow if /tmp isn't memory-mapped), so start this as early as possible pipe_process.runInNewThread(); tsPipe.deleteLater(); params.input_pipes[0] = tsPipe; params.minBufferSize = params.minFileSize; params.secondread_minsize = 100000; List<String> cmdList = new ArrayList<>(); cmdList.add(executable()); cmdList.add("-I"); cmdList.add("dummy"); // Disable hardware acceleration which is enabled by default if (!configuration.isGPUAcceleration()) { cmdList.add("--no-ffmpeg-hw"); } // Useful for the more esoteric codecs people use if (experimentalCodecs.isSelected()) { cmdList.add("--sout-ffmpeg-strict=-2"); } // Stop the DOS box from appearing on windows if (isWindows) { cmdList.add("--dummy-quiet"); } // File needs to be given before sout, otherwise vlc complains cmdList.add(fileName); // Huge fake track id that shouldn't conflict with any real subtitle or audio id. Hopefully. String disableSuffix = "track=214748361"; // Handle audio language if (params.aid != null) { // User specified language at the client, acknowledge it if (params.aid.getLang() == null || params.aid.getLang().equals("und")) { // VLC doesn't understand und, but does understand a non existant track cmdList.add("--audio-" + disableSuffix); } else { // Load by ID (better) cmdList.add("--audio-track=" + params.aid.getId()); } } else { // Not specified, use language from GUI cmdList.add("--audio-language=" + audioPri.getText()); } // Handle subtitle language if (params.sid != null) { // User specified language at the client, acknowledge it if (params.sid.getLang() == null || params.sid.getLang().equals("und")) { // VLC doesn't understand und, but does understand a non existant track cmdList.add("--sub-" + disableSuffix); } else { // Load by ID (better) cmdList.add("--sub-track=" + params.sid.getId()); } } else if (!configuration.isDisableSubtitles()) { // Not specified, use language from GUI if enabled cmdList.add("--sub-language=" + subtitlePri.getText()); } else { cmdList.add("--sub-" + disableSuffix); } // x264 options if (videoRemux) { cmdList.add("--sout-x264-preset"); cmdList.add("superfast"); cmdList.add("--sout-x264-crf"); cmdList.add("20"); } // Skip forward if nessesary if (params.timeseek != 0) { cmdList.add("--start-time"); cmdList.add(String.valueOf(params.timeseek)); } // Generate encoding args StringBuilder encodingArgsBuilder = new StringBuilder(); for (Map.Entry<String, Object> curEntry : getEncodingArgs(config, params).entrySet()) { encodingArgsBuilder.append(curEntry.getKey()).append("=").append(curEntry.getValue()).append(","); } // Add our transcode options String transcodeSpec = String.format( "#transcode{%s}:std{access=file,mux=%s,dst=\"%s%s\"}", encodingArgsBuilder.toString(), config.container, (isWindows ? "\\\\" : ""), tsPipe.getInputPipe() ); cmdList.add("--sout"); cmdList.add(transcodeSpec); // Force VLC to exit when finished cmdList.add("vlc://quit"); // Add any extra parameters if (!extraParams.getText().trim().isEmpty()) { // Add each part as a new item cmdList.addAll(Arrays.asList(StringUtils.split(extraParams.getText().trim(), " "))); } // Pass to process wrapper String[] cmdArray = new String[cmdList.size()]; cmdList.toArray(cmdArray); cmdArray = finalizeTranscoderArgs(fileName, dlna, media, params, cmdArray); LOGGER.trace("Finalized args: " + StringUtils.join(cmdArray, " ")); ProcessWrapperImpl pw = new ProcessWrapperImpl(cmdArray, params); pw.attachProcess(pipe_process); // TODO: Why is this here? try { Thread.sleep(150); } catch (InterruptedException e) { } pw.runInNewThread(); return pw; }
diff --git a/src/com/gitblit/wicket/panels/TeamsPanel.java b/src/com/gitblit/wicket/panels/TeamsPanel.java index ae5a30a6..cc37c519 100644 --- a/src/com/gitblit/wicket/panels/TeamsPanel.java +++ b/src/com/gitblit/wicket/panels/TeamsPanel.java @@ -1,96 +1,96 @@ /* * Copyright 2011 gitblit.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.gitblit.wicket.panels; import java.text.MessageFormat; import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.panel.Fragment; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.DataView; import org.apache.wicket.markup.repeater.data.ListDataProvider; import com.gitblit.GitBlit; import com.gitblit.models.TeamModel; import com.gitblit.wicket.WicketUtils; import com.gitblit.wicket.pages.EditTeamPage; public class TeamsPanel extends BasePanel { private static final long serialVersionUID = 1L; public TeamsPanel(String wicketId, final boolean showAdmin) { super(wicketId); Fragment adminLinks = new Fragment("adminPanel", "adminLinks", this); adminLinks.add(new BookmarkablePageLink<Void>("newTeam", EditTeamPage.class)); - add(adminLinks.setVisible(showAdmin)); + add(adminLinks.setVisible(showAdmin && GitBlit.self().supportsTeamMembershipChanges())); final List<TeamModel> teams = GitBlit.self().getAllTeams(); DataView<TeamModel> teamsView = new DataView<TeamModel>("teamRow", new ListDataProvider<TeamModel>(teams)) { private static final long serialVersionUID = 1L; private int counter; @Override protected void onBeforeRender() { super.onBeforeRender(); counter = 0; } public void populateItem(final Item<TeamModel> item) { final TeamModel entry = item.getModelObject(); LinkPanel editLink = new LinkPanel("teamname", "list", entry.name, EditTeamPage.class, WicketUtils.newTeamnameParameter(entry.name)); WicketUtils.setHtmlTooltip(editLink, getString("gb.edit") + " " + entry.name); item.add(editLink); item.add(new Label("members", entry.users.size() > 0 ? ("" + entry.users.size()) : "")); item.add(new Label("repositories", entry.repositories.size() > 0 ? ("" + entry.repositories.size()) : "")); Fragment teamLinks = new Fragment("teamLinks", "teamAdminLinks", this); teamLinks.add(new BookmarkablePageLink<Void>("editTeam", EditTeamPage.class, WicketUtils.newTeamnameParameter(entry.name))); Link<Void> deleteLink = new Link<Void>("deleteTeam") { private static final long serialVersionUID = 1L; @Override public void onClick() { if (GitBlit.self().deleteTeam(entry.name)) { teams.remove(entry); info(MessageFormat.format("Team ''{0}'' deleted.", entry.name)); } else { error(MessageFormat .format("Failed to delete team ''{0}''!", entry.name)); } } }; deleteLink.add(new JavascriptEventConfirmation("onclick", MessageFormat.format( "Delete team \"{0}\"?", entry.name))); teamLinks.add(deleteLink); item.add(teamLinks); WicketUtils.setAlternatingBackground(item, counter); counter++; } }; add(teamsView.setVisible(showAdmin)); } }
true
true
public TeamsPanel(String wicketId, final boolean showAdmin) { super(wicketId); Fragment adminLinks = new Fragment("adminPanel", "adminLinks", this); adminLinks.add(new BookmarkablePageLink<Void>("newTeam", EditTeamPage.class)); add(adminLinks.setVisible(showAdmin)); final List<TeamModel> teams = GitBlit.self().getAllTeams(); DataView<TeamModel> teamsView = new DataView<TeamModel>("teamRow", new ListDataProvider<TeamModel>(teams)) { private static final long serialVersionUID = 1L; private int counter; @Override protected void onBeforeRender() { super.onBeforeRender(); counter = 0; } public void populateItem(final Item<TeamModel> item) { final TeamModel entry = item.getModelObject(); LinkPanel editLink = new LinkPanel("teamname", "list", entry.name, EditTeamPage.class, WicketUtils.newTeamnameParameter(entry.name)); WicketUtils.setHtmlTooltip(editLink, getString("gb.edit") + " " + entry.name); item.add(editLink); item.add(new Label("members", entry.users.size() > 0 ? ("" + entry.users.size()) : "")); item.add(new Label("repositories", entry.repositories.size() > 0 ? ("" + entry.repositories.size()) : "")); Fragment teamLinks = new Fragment("teamLinks", "teamAdminLinks", this); teamLinks.add(new BookmarkablePageLink<Void>("editTeam", EditTeamPage.class, WicketUtils.newTeamnameParameter(entry.name))); Link<Void> deleteLink = new Link<Void>("deleteTeam") { private static final long serialVersionUID = 1L; @Override public void onClick() { if (GitBlit.self().deleteTeam(entry.name)) { teams.remove(entry); info(MessageFormat.format("Team ''{0}'' deleted.", entry.name)); } else { error(MessageFormat .format("Failed to delete team ''{0}''!", entry.name)); } } }; deleteLink.add(new JavascriptEventConfirmation("onclick", MessageFormat.format( "Delete team \"{0}\"?", entry.name))); teamLinks.add(deleteLink); item.add(teamLinks); WicketUtils.setAlternatingBackground(item, counter); counter++; } }; add(teamsView.setVisible(showAdmin)); }
public TeamsPanel(String wicketId, final boolean showAdmin) { super(wicketId); Fragment adminLinks = new Fragment("adminPanel", "adminLinks", this); adminLinks.add(new BookmarkablePageLink<Void>("newTeam", EditTeamPage.class)); add(adminLinks.setVisible(showAdmin && GitBlit.self().supportsTeamMembershipChanges())); final List<TeamModel> teams = GitBlit.self().getAllTeams(); DataView<TeamModel> teamsView = new DataView<TeamModel>("teamRow", new ListDataProvider<TeamModel>(teams)) { private static final long serialVersionUID = 1L; private int counter; @Override protected void onBeforeRender() { super.onBeforeRender(); counter = 0; } public void populateItem(final Item<TeamModel> item) { final TeamModel entry = item.getModelObject(); LinkPanel editLink = new LinkPanel("teamname", "list", entry.name, EditTeamPage.class, WicketUtils.newTeamnameParameter(entry.name)); WicketUtils.setHtmlTooltip(editLink, getString("gb.edit") + " " + entry.name); item.add(editLink); item.add(new Label("members", entry.users.size() > 0 ? ("" + entry.users.size()) : "")); item.add(new Label("repositories", entry.repositories.size() > 0 ? ("" + entry.repositories.size()) : "")); Fragment teamLinks = new Fragment("teamLinks", "teamAdminLinks", this); teamLinks.add(new BookmarkablePageLink<Void>("editTeam", EditTeamPage.class, WicketUtils.newTeamnameParameter(entry.name))); Link<Void> deleteLink = new Link<Void>("deleteTeam") { private static final long serialVersionUID = 1L; @Override public void onClick() { if (GitBlit.self().deleteTeam(entry.name)) { teams.remove(entry); info(MessageFormat.format("Team ''{0}'' deleted.", entry.name)); } else { error(MessageFormat .format("Failed to delete team ''{0}''!", entry.name)); } } }; deleteLink.add(new JavascriptEventConfirmation("onclick", MessageFormat.format( "Delete team \"{0}\"?", entry.name))); teamLinks.add(deleteLink); item.add(teamLinks); WicketUtils.setAlternatingBackground(item, counter); counter++; } }; add(teamsView.setVisible(showAdmin)); }
diff --git a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGMediaPlayer.java b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGMediaPlayer.java index 2c7134a44..68914639d 100644 --- a/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGMediaPlayer.java +++ b/src/jogl/classes/jogamp/opengl/util/av/impl/FFMPEGMediaPlayer.java @@ -1,693 +1,693 @@ /** * Copyright 2012 JogAmp Community. 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. * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ package jogamp.opengl.util.av.impl; import java.io.IOException; import java.nio.Buffer; import java.nio.ByteBuffer; import javax.media.opengl.GL; import javax.media.opengl.GL2ES2; import javax.media.opengl.GLException; import java.util.Arrays; import java.util.Queue; import javax.sound.sampled.*; import com.jogamp.common.util.VersionNumber; import com.jogamp.gluegen.runtime.ProcAddressTable; import com.jogamp.opengl.util.GLPixelStorageModes; import com.jogamp.opengl.util.texture.Texture; import com.jogamp.opengl.util.texture.TextureSequence; import jogamp.opengl.GLContextImpl; import jogamp.opengl.es1.GLES1ProcAddressTable; import jogamp.opengl.es2.GLES2ProcAddressTable; import jogamp.opengl.gl4.GL4bcProcAddressTable; import jogamp.opengl.util.av.EGLMediaPlayerImpl; /*** * Implementation utilizes <a href="http://libav.org/">Libav</a> * or <a href="http://ffmpeg.org/">FFmpeg</a> which is ubiquitous * available and usually pre-installed on Unix platforms. Due to legal * reasons we cannot deploy binaries of it, which contains patented codecs. * Besides the default BSD/Linux/.. repositories and installations, * precompiled binaries can be found at the listed location below. * <p> * Implements YUV420P to RGB fragment shader conversion * and the usual packed RGB formats. * The decoded video frame is written directly into an OpenGL texture * on the GPU in it's native format. A custom fragment shader converts * the native pixelformat to a usable RGB format if required. * Hence only 1 copy is required before bloating the picture * from YUV to RGB, for example. * </p> * <p> * Utilizes a slim dynamic and native binding to the Lib_av * libraries: * <ul> * <li>libavutil</li> * <li>libavformat</li> * <li>libavcodec</li> * </ul> * </p> * <p> * http://libav.org/ * </p> * <p> * Check tag 'FIXME: Add more planar formats !' * here and in the corresponding native code * <code>jogl/src/jogl/native/ffmpeg/jogamp_opengl_util_av_impl_FFMPEGMediaPlayer.c</code> * </p> * <p> * TODO: * <ul> * <li>Audio Output</li> * <li>Off thread <i>next frame</i> processing using multiple target textures</li> * <li>better pts sync handling</li> * <li>fix seek</li> * </ul> * </p> * Pre-compiled Libav / FFmpeg packages: * <ul> * <li>Windows: http://ffmpeg.zeranoe.com/builds/</li> * <li>MacOSX: http://www.ffmpegx.com/</li> * <li>OpenIndiana/Solaris:<pre> * pkg set-publisher -p http://pkg.openindiana.org/sfe-encumbered. * pkt install pkg:/video/ffmpeg * </pre></li> * </ul> */ public class FFMPEGMediaPlayer extends EGLMediaPlayerImpl { // Count of zeroed buffers to return before switching to real sample provider private static final int TEMP_BUFFER_COUNT = 20; // AudioFormat parameters public static final int SAMPLE_RATE = 44100; private static final int SAMPLE_SIZE = 16; private static final int CHANNELS = 2; private static final boolean SIGNED = true; private static final boolean BIG_ENDIAN = false; // Chunk of audio processed at one time public static final int BUFFER_SIZE = 1000; public static final int SAMPLES_PER_BUFFER = BUFFER_SIZE / 2; // Sample time values public static final double SAMPLE_TIME_IN_SECS = 1.0 / SAMPLE_RATE; public static final double BUFFER_TIME_IN_SECS = SAMPLE_TIME_IN_SECS * SAMPLES_PER_BUFFER; // Instance data private static AudioFormat format; private static DataLine.Info info; private static SourceDataLine auline; private static int bufferCount; private static byte [] sampleData = new byte[BUFFER_SIZE]; private static int maxAvailableAudio; public static final VersionNumber avUtilVersion; public static final VersionNumber avFormatVersion; public static final VersionNumber avCodecVersion; static boolean available; static { if(FFMPEGDynamicLibraryBundleInfo.initSingleton()) { avUtilVersion = getAVVersion(getAvUtilVersion0()); avFormatVersion = getAVVersion(getAvFormatVersion0()); avCodecVersion = getAVVersion(getAvCodecVersion0()); System.err.println("LIB_AV Util : "+avUtilVersion); System.err.println("LIB_AV Format: "+avFormatVersion); System.err.println("LIB_AV Codec : "+avCodecVersion); if(initIDs0()) { // init audio // Create the audio format we wish to use format = new AudioFormat(SAMPLE_RATE, SAMPLE_SIZE, CHANNELS, SIGNED, BIG_ENDIAN); // Create dataline info object describing line format info = new DataLine.Info(SourceDataLine.class, format); // Clear buffer initially Arrays.fill(sampleData, (byte) 0); try{ // Get line to write data to auline = (SourceDataLine) AudioSystem.getLine(info); auline.open(format); auline.start(); maxAvailableAudio = auline.available(); available = true; } catch (LineUnavailableException e){ maxAvailableAudio = 0; available = false; } } } else { avUtilVersion = null; avFormatVersion = null; avCodecVersion = null; available = false; } } public static final boolean isAvailable() { return available; } private static VersionNumber getAVVersion(int vers) { return new VersionNumber( ( vers >> 16 ) & 0xFF, ( vers >> 8 ) & 0xFF, ( vers >> 0 ) & 0xFF ); } protected long moviePtr = 0; protected long procAddrGLTexSubImage2D = 0; protected EGLMediaPlayerImpl.EGLTextureFrame lastTex = null; protected GLPixelStorageModes psm; protected PixelFormat vPixelFmt = null; protected int vPlanes = 0; protected int vBitsPerPixel = 0; protected int vBytesPerPixelPerPlane = 0; protected int[] vLinesize = { 0, 0, 0 }; // per plane protected int[] vTexWidth = { 0, 0, 0 }; // per plane protected int texWidth, texHeight; // overall (stuffing planes in one texture) protected ByteBuffer texCopy; public FFMPEGMediaPlayer() { super(TextureType.GL, false); if(!available) { throw new RuntimeException("FFMPEGMediaPlayer not available"); } setTextureCount(1); moviePtr = createInstance0(true); if(0==moviePtr) { throw new GLException("Couldn't create FFMPEGInstance"); } psm = new GLPixelStorageModes(); } @Override protected TextureSequence.TextureFrame createTexImage(GL gl, int idx, int[] tex) { if(TextureType.GL == texType) { final Texture texture = super.createTexImageImpl(gl, idx, tex, texWidth, texHeight, true); lastTex = new EGLTextureFrame(null, texture, 0, 0); } else { throw new InternalError("n/a"); } return lastTex; } @Override protected void destroyTexImage(GL gl, TextureSequence.TextureFrame imgTex) { lastTex = null; super.destroyTexImage(gl, imgTex); } @Override protected void destroyImpl(GL gl) { if (moviePtr != 0) { destroyInstance0(moviePtr); moviePtr = 0; } } @Override protected void initGLStreamImpl(GL gl, int[] texNames) throws IOException { if(0==moviePtr) { throw new GLException("FFMPEG native instance null"); } final String urlS=urlConn.getURL().toExternalForm(); System.out.println("setURL: p1 "+this); setStream0(moviePtr, urlS, -1, -1); System.out.println("setURL: p2 "+this); int tf, tif=GL.GL_RGBA; // texture format and internal format switch(vBytesPerPixelPerPlane) { case 1: tf = GL2ES2.GL_ALPHA; tif=GL.GL_ALPHA; break; case 3: tf = GL2ES2.GL_RGB; tif=GL.GL_RGB; break; case 4: tf = GL2ES2.GL_RGBA; tif=GL.GL_RGBA; break; default: throw new RuntimeException("Unsupported bytes-per-pixel / plane "+vBytesPerPixelPerPlane); } setTextureFormat(tif, tf); setTextureType(GL.GL_UNSIGNED_BYTE); GLContextImpl ctx = (GLContextImpl)gl.getContext(); ProcAddressTable pt = ctx.getGLProcAddressTable(); if(pt instanceof GLES2ProcAddressTable) { procAddrGLTexSubImage2D = ((GLES2ProcAddressTable)pt)._addressof_glTexSubImage2D; } else if(pt instanceof GLES1ProcAddressTable) { procAddrGLTexSubImage2D = ((GLES1ProcAddressTable)pt)._addressof_glTexSubImage2D; } else if(pt instanceof GL4bcProcAddressTable) { procAddrGLTexSubImage2D = ((GL4bcProcAddressTable)pt)._addressof_glTexSubImage2D; } else { throw new InternalError("Unknown ProcAddressTable: "+pt.getClass().getName()+" of "+ctx.getClass().getName()); } } private class AudioFrame { final byte[] sampleData; final int data_size; final int audio_pts; AudioFrame(byte[] sampleData, int data_size, int audio_pts) { this.sampleData=sampleData; this.data_size=data_size; this.audio_pts=audio_pts; } } static final Queue<AudioFrame> audioFrameBuffer = new java.util.LinkedList<AudioFrame>(); private void updateSound(byte[] sampleData, int data_size, int audio_pts) { /* // Visualize incomming data int c=0; for(byte b: sampleData){ if(b<0) { System.out.print(" "); } else if(b<64) { System.out.print("_"); } else if(b < 128) { System.out.print("-"); } else if(b == 128) { System.out.print("="); } else if(b < 256-64) { System.out.print("\""); } else { System.out.print("'"); } c++; if(c>=40) break; } System.out.println("jA"); */ //TODO reduce GC audioFrameBuffer.add(new AudioFrame(sampleData, data_size, audio_pts)); pumpAudio(); } private void pumpAudio() { if(auline.available()==maxAvailableAudio){ System.out.println("warning: audio buffer underrun"); } while(audioFrameBuffer.peek()!=null){ AudioFrame a = audioFrameBuffer.peek(); // poor mans audio sync .. TODO: off thread final long now = System.currentTimeMillis(); final long now_d = now - lastAudioTime; final long pts_d = a.audio_pts - lastAudioPTS; final long dt = (long) ( (float) ( pts_d - now_d ) / getPlaySpeed() ) ; System.err.println("s: pts-a "+a.audio_pts+", pts-d "+pts_d+", now_d "+now_d+", dt "+dt); lastAudioTime = now; if( (dt<audio_dt_d ) && auline.available()>a.data_size ) { audioFrameBuffer.poll(); /* remove first item from the queue */ int written = 0; int len; int data_size = a.data_size; while (data_size > 0) { len = auline.write(a.sampleData, written, data_size); data_size -= len; written += len; } lastAudioPTS=a.audio_pts; } else { break; } } } private void updateAttributes2(int pixFmt, int planes, int bitsPerPixel, int bytesPerPixelPerPlane, int lSz0, int lSz1, int lSz2, int tWd0, int tWd1, int tWd2) { vPixelFmt = PixelFormat.valueOf(pixFmt); vPlanes = planes; vBitsPerPixel = bitsPerPixel; vBytesPerPixelPerPlane = bytesPerPixelPerPlane; vLinesize[0] = lSz0; vLinesize[1] = lSz1; vLinesize[2] = lSz2; vTexWidth[0] = tWd0; vTexWidth[1] = tWd1; vTexWidth[2] = tWd2; switch(vPixelFmt) { case YUV420P: // YUV420P: Adding U+V on right side of fixed height texture, // since width is already aligned by decoder. // Y=w*h, Y=w/2*h/2, U=w/2*h/2 // w*h + 2 ( w/2 * h/2 ) // w*h + w*h/2 // 2*w/2 * h texWidth = vTexWidth[0] + vTexWidth[1]; texHeight = height; break; // case PIX_FMT_YUYV422: case RGB24: case BGR24: case ARGB: case RGBA: case ABGR: case BGRA: texWidth = vTexWidth[0]; texHeight = height; break; default: // FIXME: Add more planar formats ! throw new RuntimeException("Unsupported pixelformat: "+vPixelFmt); } if(DEBUG) { System.err.println("XXX0: fmt "+vPixelFmt+", planes "+vPlanes+", bpp "+vBitsPerPixel+"/"+vBytesPerPixelPerPlane); for(int i=0; i<3; i++) { System.err.println("XXX0 "+i+": "+vTexWidth[i]+"/"+vLinesize[i]); } System.err.println("XXX0 total tex "+texWidth+"x"+texHeight); } } /** * {@inheritDoc} * * If this implementation generates a specialized shader, * it allows the user to override the default function name <code>ffmpegTexture2D</code>. * Otherwise the call is delegated to it's super class. */ @Override public String getTextureLookupFunctionName(String desiredFuncName) throws IllegalStateException { if(State.Uninitialized == state) { throw new IllegalStateException("Instance not initialized: "+this); } if(PixelFormat.YUV420P == vPixelFmt) { if(null != desiredFuncName && desiredFuncName.length()>0) { textureLookupFunctionName = desiredFuncName; } return textureLookupFunctionName; } return super.getTextureLookupFunctionName(desiredFuncName); } private String textureLookupFunctionName = "ffmpegTexture2D"; /** * {@inheritDoc} * * Depending on the pixelformat, a specific conversion shader is being created, * e.g. YUV420P to RGB. Otherwise the call is delegated to it's super class. */ @Override public String getTextureLookupFragmentShaderImpl() throws IllegalStateException { if(State.Uninitialized == state) { throw new IllegalStateException("Instance not initialized: "+this); } final float tc_w_1 = (float)getWidth() / (float)texWidth; switch(vPixelFmt) { case YUV420P: return "vec4 "+textureLookupFunctionName+"(in "+getTextureSampler2DType()+" image, in vec2 texCoord) {\n"+ " vec2 u_off = vec2("+tc_w_1+", 0.0);\n"+ " vec2 v_off = vec2("+tc_w_1+", 0.5);\n"+ " vec2 tc_half = texCoord*0.5;\n"+ " float y,u,v,r,g,b;\n"+ " y = texture2D(image, texCoord).a;\n"+ " u = texture2D(image, u_off+tc_half).a;\n"+ " v = texture2D(image, v_off+tc_half).a;\n"+ " y = 1.1643*(y-0.0625);\n"+ " u = u-0.5;\n"+ " v = v-0.5;\n"+ " r = y+1.5958*v;\n"+ " g = y-0.39173*u-0.81290*v;\n"+ " b = y+2.017*u;\n"+ " return vec4(r, g, b, 1);\n"+ "}\n" ; default: // FIXME: Add more planar formats ! return super.getTextureLookupFragmentShaderImpl(); } } @Override protected synchronized int getCurrentPositionImpl() { return 0!=moviePtr ? getVideoPTS0(moviePtr) : 0; } @Override protected synchronized boolean setPlaySpeedImpl(float rate) { return true; } @Override public synchronized boolean startImpl() { if(0==moviePtr) { return false; } return true; } /** @return time position after issuing the command */ @Override public synchronized boolean pauseImpl() { if(0==moviePtr) { return false; } return true; } /** @return time position after issuing the command */ @Override public synchronized boolean stopImpl() { if(0==moviePtr) { return false; } return true; } /** @return time position after issuing the command */ @Override protected synchronized int seekImpl(int msec) { if(0==moviePtr) { throw new GLException("FFMPEG native instance null"); } int pts0 = getVideoPTS0(moviePtr); int pts1 = seek0(moviePtr, msec); System.err.println("Seek: "+pts0+" -> "+msec+" : "+pts1); audioFrameBuffer.clear(); lastAudioPTS=pts1; lastVideoPTS=pts1; return pts1; } @Override protected TextureSequence.TextureFrame getLastTextureImpl() { return lastTex; } private long lastAudioTime = 0; private int lastAudioPTS = 0; private static final int audio_dt_d = 400; private long lastVideoTime = 0; private int lastVideoPTS = 0; private static final int video_dt_d = 9; @Override protected TextureSequence.TextureFrame getNextTextureImpl(GL gl, boolean blocking) { if(0==moviePtr) { throw new GLException("FFMPEG native instance null"); } if(null != lastTex) { psm.setUnpackAlignment(gl, 1); // RGBA ? 4 : 1 try { final Texture tex = lastTex.getTexture(); gl.glActiveTexture(GL.GL_TEXTURE0+getTextureUnit()); tex.enable(gl); tex.bind(gl); /* try decode 10 packets to find one containing video (res == 2) */ int res = 0; int retry = 10; while(res!=2 && retry >= 0) { res = readNextPacket0(moviePtr, procAddrGLTexSubImage2D, textureTarget, textureFormat, textureType); retry--; } } finally { psm.restore(gl); } final int pts = getVideoPTS0(moviePtr); // this frame if(blocking) { // poor mans video sync .. TODO: off thread 'readNextPackage0(..)' on shared GLContext and multi textures/unit! final long now = System.currentTimeMillis(); // Try sync video to audio final long now_d = now - lastAudioTime; final long pts_d = pts - lastAudioPTS - 444; /* hack 444 == play video 444ms ahead of audio */ - //final long dt = Math.min(46, Math.abs( (long) ( (float) ( pts_d - now_d ) / getPlaySpeed() ) ) ) ; - final long dt = (long) ( (float) ( pts_d - now_d ) / getPlaySpeed() ) ; + final long dt = Math.min(47, (long) ( (float) ( pts_d - now_d ) / getPlaySpeed() ) ) ; + //final long dt = (long) ( (float) ( pts_d - now_d ) / getPlaySpeed() ) ; lastVideoTime = now; System.err.println("s: pts-v "+pts+", pts-d "+pts_d+", now_d "+now_d+", dt "+dt); if(dt>video_dt_d && dt<1000 && auline.available()<maxAvailableAudio-10000) { try { Thread.sleep(dt-video_dt_d); } catch (InterruptedException e) { } } /* else if(0>pts_d) { System.err.println("s: pts-v "+pts+", pts-d "+pts_d+", now_d "+now_d+", dt "+dt); } */ } pumpAudio(); lastVideoPTS = pts; } return lastTex; } private void consumeAudio(int len) { } private static native int getAvUtilVersion0(); private static native int getAvFormatVersion0(); private static native int getAvCodecVersion0(); private static native boolean initIDs0(); private native long createInstance0(boolean verbose); private native void destroyInstance0(long moviePtr); private native void setStream0(long moviePtr, String url, int vid, int aid); private native int getVideoPTS0(long moviePtr); private native int getAudioPTS0(long moviePtr); private native Buffer getAudioBuffer0(long moviePtr, int plane); private native int readNextPacket0(long moviePtr, long procAddrGLTexSubImage2D, int texTarget, int texFmt, int texType); private native int seek0(long moviePtr, int position); public static enum PixelFormat { // NONE= -1, YUV420P, ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples) YUYV422, ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr RGB24, ///< packed RGB 8:8:8, 24bpp, RGBRGB... BGR24, ///< packed RGB 8:8:8, 24bpp, BGRBGR... YUV422P, ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples) YUV444P, ///< planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples) YUV410P, ///< planar YUV 4:1:0, 9bpp, (1 Cr & Cb sample per 4x4 Y samples) YUV411P, ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples) GRAY8, ///< Y , 8bpp MONOWHITE, ///< Y , 1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb MONOBLACK, ///< Y , 1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb PAL8, ///< 8 bit with RGB32 palette YUVJ420P, ///< planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of YUV420P and setting color_range YUVJ422P, ///< planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of YUV422P and setting color_range YUVJ444P, ///< planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of YUV444P and setting color_range XVMC_MPEG2_MC,///< XVideo Motion Acceleration via common packet passing XVMC_MPEG2_IDCT, UYVY422, ///< packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1 UYYVYY411, ///< packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3 BGR8, ///< packed RGB 3:3:2, 8bpp, (msb)2B 3G 3R(lsb) BGR4, ///< packed RGB 1:2:1 bitstream, 4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits BGR4_BYTE, ///< packed RGB 1:2:1, 8bpp, (msb)1B 2G 1R(lsb) RGB8, ///< packed RGB 3:3:2, 8bpp, (msb)2R 3G 3B(lsb) RGB4, ///< packed RGB 1:2:1 bitstream, 4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits RGB4_BYTE, ///< packed RGB 1:2:1, 8bpp, (msb)1R 2G 1B(lsb) NV12, ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V) NV21, ///< as above, but U and V bytes are swapped ARGB, ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB... RGBA, ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA... ABGR, ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR... BGRA, ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA... GRAY16BE, ///< Y , 16bpp, big-endian GRAY16LE, ///< Y , 16bpp, little-endian YUV440P, ///< planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples) YUVJ440P, ///< planar YUV 4:4:0 full scale (JPEG), deprecated in favor of YUV440P and setting color_range YUVA420P, ///< planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples) VDPAU_H264,///< H.264 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers VDPAU_MPEG1,///< MPEG-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers VDPAU_MPEG2,///< MPEG-2 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers VDPAU_WMV3,///< WMV3 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers VDPAU_VC1, ///< VC-1 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers RGB48BE, ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian RGB48LE, ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian RGB565BE, ///< packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), big-endian RGB565LE, ///< packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), little-endian RGB555BE, ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), big-endian, most significant bit to 0 RGB555LE, ///< packed RGB 5:5:5, 16bpp, (msb)1A 5R 5G 5B(lsb), little-endian, most significant bit to 0 BGR565BE, ///< packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), big-endian BGR565LE, ///< packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), little-endian BGR555BE, ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), big-endian, most significant bit to 1 BGR555LE, ///< packed BGR 5:5:5, 16bpp, (msb)1A 5B 5G 5R(lsb), little-endian, most significant bit to 1 VAAPI_MOCO, ///< HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers VAAPI_IDCT, ///< HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers VAAPI_VLD, ///< HW decoding through VA API, Picture.data[3] contains a vaapi_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers YUV420P16LE, ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian YUV420P16BE, ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian YUV422P16LE, ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian YUV422P16BE, ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian YUV444P16LE, ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian YUV444P16BE, ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian VDPAU_MPEG4, ///< MPEG4 HW decoding with VDPAU, data[0] contains a vdpau_render_state struct which contains the bitstream of the slices as well as various fields extracted from headers DXVA2_VLD, ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer RGB444LE, ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), little-endian, most significant bits to 0 RGB444BE, ///< packed RGB 4:4:4, 16bpp, (msb)4A 4R 4G 4B(lsb), big-endian, most significant bits to 0 BGR444LE, ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), little-endian, most significant bits to 1 BGR444BE, ///< packed BGR 4:4:4, 16bpp, (msb)4A 4B 4G 4R(lsb), big-endian, most significant bits to 1 Y400A, ///< 8bit gray, 8bit alpha BGR48BE, ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as big-endian BGR48LE, ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as little-endian YUV420P9BE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian YUV420P9LE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian YUV420P10BE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian YUV420P10LE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian YUV422P10BE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian YUV422P10LE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian YUV444P9BE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian YUV444P9LE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian YUV444P10BE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian YUV444P10LE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian YUV422P9BE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian YUV422P9LE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian VDA_VLD, ///< hardware decoding through VDA GBRP, ///< planar GBR 4:4:4 24bpp GBRP9BE, ///< planar GBR 4:4:4 27bpp, big endian GBRP9LE, ///< planar GBR 4:4:4 27bpp, little endian GBRP10BE, ///< planar GBR 4:4:4 30bpp, big endian GBRP10LE, ///< planar GBR 4:4:4 30bpp, little endian GBRP16BE, ///< planar GBR 4:4:4 48bpp, big endian GBRP16LE, ///< planar GBR 4:4:4 48bpp, little endian COUNT ///< number of pixel formats in this list ; public static PixelFormat valueOf(int i) { for (PixelFormat fmt : PixelFormat.values()) { if(fmt.ordinal() == i) { return fmt; } } return null; } } }
true
true
protected TextureSequence.TextureFrame getNextTextureImpl(GL gl, boolean blocking) { if(0==moviePtr) { throw new GLException("FFMPEG native instance null"); } if(null != lastTex) { psm.setUnpackAlignment(gl, 1); // RGBA ? 4 : 1 try { final Texture tex = lastTex.getTexture(); gl.glActiveTexture(GL.GL_TEXTURE0+getTextureUnit()); tex.enable(gl); tex.bind(gl); /* try decode 10 packets to find one containing video (res == 2) */ int res = 0; int retry = 10; while(res!=2 && retry >= 0) { res = readNextPacket0(moviePtr, procAddrGLTexSubImage2D, textureTarget, textureFormat, textureType); retry--; } } finally { psm.restore(gl); } final int pts = getVideoPTS0(moviePtr); // this frame if(blocking) { // poor mans video sync .. TODO: off thread 'readNextPackage0(..)' on shared GLContext and multi textures/unit! final long now = System.currentTimeMillis(); // Try sync video to audio final long now_d = now - lastAudioTime; final long pts_d = pts - lastAudioPTS - 444; /* hack 444 == play video 444ms ahead of audio */ //final long dt = Math.min(46, Math.abs( (long) ( (float) ( pts_d - now_d ) / getPlaySpeed() ) ) ) ; final long dt = (long) ( (float) ( pts_d - now_d ) / getPlaySpeed() ) ; lastVideoTime = now; System.err.println("s: pts-v "+pts+", pts-d "+pts_d+", now_d "+now_d+", dt "+dt); if(dt>video_dt_d && dt<1000 && auline.available()<maxAvailableAudio-10000) { try { Thread.sleep(dt-video_dt_d); } catch (InterruptedException e) { } } /* else if(0>pts_d) { System.err.println("s: pts-v "+pts+", pts-d "+pts_d+", now_d "+now_d+", dt "+dt); } */ } pumpAudio(); lastVideoPTS = pts; } return lastTex; }
protected TextureSequence.TextureFrame getNextTextureImpl(GL gl, boolean blocking) { if(0==moviePtr) { throw new GLException("FFMPEG native instance null"); } if(null != lastTex) { psm.setUnpackAlignment(gl, 1); // RGBA ? 4 : 1 try { final Texture tex = lastTex.getTexture(); gl.glActiveTexture(GL.GL_TEXTURE0+getTextureUnit()); tex.enable(gl); tex.bind(gl); /* try decode 10 packets to find one containing video (res == 2) */ int res = 0; int retry = 10; while(res!=2 && retry >= 0) { res = readNextPacket0(moviePtr, procAddrGLTexSubImage2D, textureTarget, textureFormat, textureType); retry--; } } finally { psm.restore(gl); } final int pts = getVideoPTS0(moviePtr); // this frame if(blocking) { // poor mans video sync .. TODO: off thread 'readNextPackage0(..)' on shared GLContext and multi textures/unit! final long now = System.currentTimeMillis(); // Try sync video to audio final long now_d = now - lastAudioTime; final long pts_d = pts - lastAudioPTS - 444; /* hack 444 == play video 444ms ahead of audio */ final long dt = Math.min(47, (long) ( (float) ( pts_d - now_d ) / getPlaySpeed() ) ) ; //final long dt = (long) ( (float) ( pts_d - now_d ) / getPlaySpeed() ) ; lastVideoTime = now; System.err.println("s: pts-v "+pts+", pts-d "+pts_d+", now_d "+now_d+", dt "+dt); if(dt>video_dt_d && dt<1000 && auline.available()<maxAvailableAudio-10000) { try { Thread.sleep(dt-video_dt_d); } catch (InterruptedException e) { } } /* else if(0>pts_d) { System.err.println("s: pts-v "+pts+", pts-d "+pts_d+", now_d "+now_d+", dt "+dt); } */ } pumpAudio(); lastVideoPTS = pts; } return lastTex; }
diff --git a/src/com/github/nicolassmith/urlevaluator/GeneralEvaluatorTask.java b/src/com/github/nicolassmith/urlevaluator/GeneralEvaluatorTask.java index 95b9599..700eeeb 100644 --- a/src/com/github/nicolassmith/urlevaluator/GeneralEvaluatorTask.java +++ b/src/com/github/nicolassmith/urlevaluator/GeneralEvaluatorTask.java @@ -1,48 +1,51 @@ package com.github.nicolassmith.urlevaluator; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import android.util.Log; /** This is the most general version of the {@link EvaluatorTask} class. **/ public class GeneralEvaluatorTask extends EvaluatorTask { private static final String TAG = "GeneralEvaluatorTask"; public GeneralEvaluatorTask(EvaluatorTaskCaller passedCaller) { super(passedCaller); } @Override public String evaluate(String uriString) { HttpURLConnection con; int responseCode = 0; String location = null; try { // thanks to StackExchange user syb0rg con = (HttpURLConnection) (new URL(uriString).openConnection()); con.setInstanceFollowRedirects(false); con.setRequestMethod("HEAD"); + // This turns off gzip compression, because some servers lie! + // And this confuses the HttpEngine decoder. + con.setRequestProperty("Accept-Encoding", "identity"); con.connect(); responseCode = con.getResponseCode(); location = con.getHeaderField("Location"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "response code = " + responseCode); Log.d(TAG, "Location = " + location); } return location; } }
true
true
public String evaluate(String uriString) { HttpURLConnection con; int responseCode = 0; String location = null; try { // thanks to StackExchange user syb0rg con = (HttpURLConnection) (new URL(uriString).openConnection()); con.setInstanceFollowRedirects(false); con.setRequestMethod("HEAD"); con.connect(); responseCode = con.getResponseCode(); location = con.getHeaderField("Location"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "response code = " + responseCode); Log.d(TAG, "Location = " + location); } return location; }
public String evaluate(String uriString) { HttpURLConnection con; int responseCode = 0; String location = null; try { // thanks to StackExchange user syb0rg con = (HttpURLConnection) (new URL(uriString).openConnection()); con.setInstanceFollowRedirects(false); con.setRequestMethod("HEAD"); // This turns off gzip compression, because some servers lie! // And this confuses the HttpEngine decoder. con.setRequestProperty("Accept-Encoding", "identity"); con.connect(); responseCode = con.getResponseCode(); location = con.getHeaderField("Location"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "response code = " + responseCode); Log.d(TAG, "Location = " + location); } return location; }