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/src/gui/GUI_KitStand.java b/src/gui/GUI_KitStand.java index fabf641..7c6ac3f 100644 --- a/src/gui/GUI_KitStand.java +++ b/src/gui/GUI_KitStand.java @@ -1,112 +1,112 @@ package gui; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.ImageIcon; import javax.swing.JPanel; import agents.Kit; public class GUI_KitStand implements GUI_Component { GUI_Stand[] stands; // This is the constructor. It creates the array( size 3) of stands and sets // each stands. Then it sets stands[0] and stand[1] to normals stand objs // and stands[2] to inspection area obj. public GUI_KitStand(int x, int y) { stands = new GUI_Stand[3]; for (int i = 0; i < 3; i++) stands[i] = new GUI_Stand(x, i*150 + y); } public void DoAddKit(Kit k) { for (int s = 2; s>=0; s--){ if (stands[s].kit == null){ stands[s].kit = new GUI_Kit(k,getX(s),getY(s)); break; } } } public void DoAddKitToInspection(Kit k){ stands[0].kit = new GUI_Kit(k, getX(0),getY(0)); } public void DoRemoveKit(Kit k) { for (int s = 1; s<=2; s++){ if (stands[s].kit!= null){ stands[s].removeKit(); break; } } } // The paint function calls the drawing of each of the stands in the array. public void paintComponent(JPanel j, Graphics2D g) { for (GUI_Stand s : stands) s.paintComponent(j, g); } public void updateGraphics() { for (GUI_Stand s : stands) s.updateGraphics(); } public int getX(int i) { return stands[i].x; } public int getY(int i) { return stands[i].y; } public void addPart(int number, GUI_Part p) { stands[number].kit.addPart(p); } public boolean positionOpen(int i) { if (stands[i].kit == null){ return true; } else{ return false; } } public void addkit(GUI_Kit k, int number){ /*stands[number].kit = k; k.setX(stands[number].x); k.setY(stands[number].y);*/ } public GUI_Kit checkKit(int number){ return stands[number].kit; } public Kit getTempKit(){ - int i = 0; + int i = 2; for(int j = 0; j<2; j++){ if(stands[j].kit!= null){ i = j; break; } } return stands[i].kit.kit; } // the check status function will see if a GUIKit is done with it�s part // annimation and is ready to be inspected or if it being inspected will // make sure it gets picked up. // NOT NEEDED THIS VERSION! /* * void checkStatus(){ * * } */ }
true
true
public Kit getTempKit(){ int i = 0; for(int j = 0; j<2; j++){ if(stands[j].kit!= null){ i = j; break; } } return stands[i].kit.kit; }
public Kit getTempKit(){ int i = 2; for(int j = 0; j<2; j++){ if(stands[j].kit!= null){ i = j; break; } } return stands[i].kit.kit; }
diff --git a/Plugins/org.opendarts.core/src/main/java/org/opendarts/core/model/session/impl/GameSet.java b/Plugins/org.opendarts.core/src/main/java/org/opendarts/core/model/session/impl/GameSet.java index 4438fae..d3cb68a 100644 --- a/Plugins/org.opendarts.core/src/main/java/org/opendarts/core/model/session/impl/GameSet.java +++ b/Plugins/org.opendarts.core/src/main/java/org/opendarts/core/model/session/impl/GameSet.java @@ -1,263 +1,264 @@ /* * */ package org.opendarts.core.model.session.impl; import java.text.MessageFormat; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CopyOnWriteArraySet; import org.opendarts.core.model.game.IGame; import org.opendarts.core.model.game.IGameDefinition; import org.opendarts.core.model.game.impl.GameDefinition; import org.opendarts.core.model.player.IPlayer; import org.opendarts.core.model.session.ISession; import org.opendarts.core.model.session.ISet; import org.opendarts.core.model.session.ISetListener; import org.opendarts.core.model.session.SetEvent; import org.opendarts.core.service.game.IGameService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Class GameSet. */ public class GameSet extends GameContainer<IGame> implements ISet { /** The logger. */ private static final Logger LOG = LoggerFactory.getLogger(GameSet.class); /** The session. */ private final ISession session; /** The game definition. */ private final GameDefinition gameDefinition; /** The player games. */ private final Map<IPlayer, Integer> playerGames; /** The listeners. */ private final CopyOnWriteArraySet<ISetListener> listeners; /** The game service. */ private final IGameService gameService; /** * Instantiates a new game set. * * @param session the session * @param gameDefinition the game definition */ public GameSet(ISession session, GameDefinition gameDefinition) { super(); this.session = session; this.gameDefinition = gameDefinition; this.listeners = new CopyOnWriteArraySet<ISetListener>(); this.playerGames = new HashMap<IPlayer, Integer>(); this.gameService = gameDefinition.getGameService(); for (IPlayer player : gameDefinition.getPlayers()) { this.playerGames.put(player, 0); } // create the first game IGame game = this.gameService.createGame(this, this.gameDefinition.getPlayers()); this.getInternalsGame().add(game); } /* (non-Javadoc) * @see org.opendarts.prototype.model.session.ISet#initSet() */ @Override public void initSet() { this.setStart(Calendar.getInstance()); this.fireSetEvent(SetEvent.Factory.newSetInitializedEvent(this)); this.setCurrentGame(this.getInternalsGame().get(0)); } /* (non-Javadoc) * @see org.opendarts.prototype.model.session.ISet#getWinningMessage() */ @Override public String getWinningMessage() { IPlayer player = this.getWinner(); StringBuffer sb = new StringBuffer(); boolean isFirst = true; for (IPlayer p : this.gameDefinition.getPlayers()) { if (!p.equals(player)) { if (isFirst) { isFirst = false; } else { sb.append(", "); } sb.append(p); sb.append(": "); sb.append(this.getWinningGames(p)); } } return MessageFormat.format( "{0} win the set with {1} games against {2}", player, this.getWinningGames(player), sb); } /* (non-Javadoc) * @see org.opendarts.prototype.model.session.ISet#getName() */ @Override public String getName() { StringBuffer result = new StringBuffer("Set: "); boolean isFirst = true; for (IPlayer player : this.gameDefinition.getPlayers()) { if (isFirst) { result.append(", "); } result.append(player); result.append(" "); result.append(this.getWinningGames(player)); } result.append(" - "); result.append(this.gameDefinition); return result.toString(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return this.getName(); } /* (non-Javadoc) * @see org.opendarts.prototype.model.session.ISet#getDescription() */ @Override public String getDescription() { return this.getName(); } /* (non-Javadoc) * @see org.opendarts.prototype.model.session.ISet#getWinningGame(org.opendarts.prototype.model.player.IPlayer) */ @Override public int getWinningGames(IPlayer player) { return this.playerGames.get(player); } /* (non-Javadoc) * @see org.opendarts.prototype.model.session.ISet#getParentSession() */ @Override public ISession getParentSession() { return this.session; } /* (non-Javadoc) * @see org.opendarts.prototype.model.session.ISet#getGameDefinition() */ @Override public IGameDefinition getGameDefinition() { return this.gameDefinition; } /* (non-Javadoc) * @see org.opendarts.prototype.model.session.ISet#addListener(org.opendarts.prototype.model.session.ISetListener) */ @Override public void addListener(ISetListener listener) { this.listeners.add(listener); } /* (non-Javadoc) * @see org.opendarts.prototype.model.session.ISet#removeListener(org.opendarts.prototype.model.session.ISetListener) */ @Override public void removeListener(ISetListener listener) { this.listeners.remove(listener); } /** * Fire set event. * * @param event the event */ protected void fireSetEvent(final SetEvent event) { for (final ISetListener listener : this.listeners) { try { listener.notifySetEvent(event); } catch (Throwable t) { LOG.error("Error when sending game event: " + event, t); } } } /** * Handle finished game. * * @param game the game */ public void handleFinishedGame(IGame game) { // update player score IPlayer player = game.getWinner(); int score = this.getWinningGames(player); score++; this.playerGames.put(player, score); // check if player win if (this.getGameDefinition().isPlayerWin(this, player)) { this.setWinner(player); + this.setEnd(Calendar.getInstance()); } // check end if (this.getGameDefinition().isSetFinished(this)) { LOG.info("Set win by {}", player); this.fireSetEvent(SetEvent.Factory.newSetFinishedEvent(this, this.getWinner(), game)); } else { // create a new game IGame newGame = this.createNewGame(game.getFirstPlayer()); this.setCurrentGame(newGame); } } /* (non-Javadoc) * @see org.opendarts.prototype.internal.model.session.GameContainer#setCurrentGame(java.lang.Object) */ @Override protected void setCurrentGame(IGame game) { super.setCurrentGame(game); this.fireSetEvent(SetEvent.Factory.newSetGameEvent(this, game)); } /** * Creates the new game. * * @param player the player * @return the i game */ private IGame createNewGame(IPlayer player) { IGame game = this.gameService.createGame(this, this.gameDefinition.getNextPlayers(this)); this.getInternalsGame().add(game); return game; } /** * Cancel. */ public void cancelSet() { this.fireSetEvent(SetEvent.Factory.newSetCanceledEvent(this)); } /* (non-Javadoc) * @see org.opendarts.prototype.model.session.ISet#getGameService() */ @Override public IGameService getGameService() { return this.gameService; } }
true
true
public void handleFinishedGame(IGame game) { // update player score IPlayer player = game.getWinner(); int score = this.getWinningGames(player); score++; this.playerGames.put(player, score); // check if player win if (this.getGameDefinition().isPlayerWin(this, player)) { this.setWinner(player); } // check end if (this.getGameDefinition().isSetFinished(this)) { LOG.info("Set win by {}", player); this.fireSetEvent(SetEvent.Factory.newSetFinishedEvent(this, this.getWinner(), game)); } else { // create a new game IGame newGame = this.createNewGame(game.getFirstPlayer()); this.setCurrentGame(newGame); } }
public void handleFinishedGame(IGame game) { // update player score IPlayer player = game.getWinner(); int score = this.getWinningGames(player); score++; this.playerGames.put(player, score); // check if player win if (this.getGameDefinition().isPlayerWin(this, player)) { this.setWinner(player); this.setEnd(Calendar.getInstance()); } // check end if (this.getGameDefinition().isSetFinished(this)) { LOG.info("Set win by {}", player); this.fireSetEvent(SetEvent.Factory.newSetFinishedEvent(this, this.getWinner(), game)); } else { // create a new game IGame newGame = this.createNewGame(game.getFirstPlayer()); this.setCurrentGame(newGame); } }
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GraphicalEditorPart.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GraphicalEditorPart.java index 21e21cad3..b58346f2b 100644 --- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GraphicalEditorPart.java +++ b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GraphicalEditorPart.java @@ -1,2213 +1,2213 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Eclipse 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/org/documents/epl-v10.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ide.eclipse.adt.internal.editors.layout.gle2; import static com.android.ide.common.layout.LayoutConstants.ANDROID_STRING_PREFIX; import static com.android.ide.common.layout.LayoutConstants.SCROLL_VIEW; import static com.android.ide.common.layout.LayoutConstants.STRING_PREFIX; import static com.android.ide.eclipse.adt.AndroidConstants.ANDROID_PKG; import static com.android.sdklib.resources.Density.DEFAULT_DENSITY; import com.android.ide.common.rendering.LayoutLibrary; import com.android.ide.common.rendering.StaticRenderSession; import com.android.ide.common.rendering.api.Capability; import com.android.ide.common.rendering.api.ILayoutPullParser; import com.android.ide.common.rendering.api.LayoutLog; import com.android.ide.common.rendering.api.Params; import com.android.ide.common.rendering.api.RenderSession; import com.android.ide.common.rendering.api.ResourceValue; import com.android.ide.common.rendering.api.Result; import com.android.ide.common.rendering.api.Params.RenderingMode; import com.android.ide.common.sdk.LoadStatus; import com.android.ide.eclipse.adt.AdtPlugin; import com.android.ide.eclipse.adt.internal.editors.IPageImageProvider; import com.android.ide.eclipse.adt.internal.editors.IconFactory; import com.android.ide.eclipse.adt.internal.editors.layout.ContextPullParser; import com.android.ide.eclipse.adt.internal.editors.layout.ExplodedRenderingHelper; import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditor; import com.android.ide.eclipse.adt.internal.editors.layout.LayoutReloadMonitor; import com.android.ide.eclipse.adt.internal.editors.layout.ProjectCallback; import com.android.ide.eclipse.adt.internal.editors.layout.UiElementPullParser; import com.android.ide.eclipse.adt.internal.editors.layout.LayoutReloadMonitor.ChangeFlags; import com.android.ide.eclipse.adt.internal.editors.layout.LayoutReloadMonitor.ILayoutReloadListener; import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationComposite; import com.android.ide.eclipse.adt.internal.editors.layout.configuration.LayoutCreatorDialog; import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationComposite.CustomButton; import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationComposite.IConfigListener; import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder.Reference; import com.android.ide.eclipse.adt.internal.editors.layout.gre.RulesEngine; import com.android.ide.eclipse.adt.internal.editors.ui.DecorComposite; import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode; import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode; import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs; import com.android.ide.eclipse.adt.internal.resources.ResourceType; import com.android.ide.eclipse.adt.internal.resources.configurations.FolderConfiguration; import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources; import com.android.ide.eclipse.adt.internal.resources.manager.ResourceFile; import com.android.ide.eclipse.adt.internal.resources.manager.ResourceFolderType; import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager; import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData; import com.android.ide.eclipse.adt.internal.sdk.Sdk; import com.android.ide.eclipse.adt.internal.sdk.Sdk.ITargetChangeListener; import com.android.ide.eclipse.adt.io.IFileWrapper; import com.android.sdklib.IAndroidTarget; import com.android.sdklib.SdkConstants; import com.android.sdkuilib.internal.widgets.ResolutionChooserDialog; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.actions.OpenNewClassWizardAction; import org.eclipse.jdt.ui.wizards.NewClassWizardPage; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.INullSelectionListener; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.part.IPage; import org.eclipse.ui.part.PageBookView; import org.w3c.dom.Node; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; /** * Graphical layout editor part, version 2. * <p/> * The main component of the editor part is the {@link LayoutCanvasViewer}, which * actually delegates its work to the {@link LayoutCanvas} control. * <p/> * The {@link LayoutCanvasViewer} is set as the site's {@link ISelectionProvider}: * when the selection changes in the canvas, it is thus broadcasted to anyone listening * on the site's selection service. * <p/> * This part is also an {@link ISelectionListener}. It listens to the site's selection * service and thus receives selection changes from itself as well as the associated * outline and property sheet (these are registered by {@link LayoutEditor#getAdapter(Class)}). * * @since GLE2 */ public class GraphicalEditorPart extends EditorPart implements IPageImageProvider, ISelectionListener, INullSelectionListener { /* * Useful notes: * To understand Drag'n'drop: * http://www.eclipse.org/articles/Article-Workbench-DND/drag_drop.html * * To understand the site's selection listener, selection provider, and the * confusion of different-yet-similarly-named interfaces, consult this: * http://www.eclipse.org/articles/Article-WorkbenchSelections/article.html * * To summarize the selection mechanism: * - The workbench site selection service can be seen as "centralized" * service that registers selection providers and selection listeners. * - The editor part and the outline are selection providers. * - The editor part, the outline and the property sheet are listeners * which all listen to each others indirectly. */ /** * Session-property on files which specifies the initial config state to be used on * this file */ public final static QualifiedName NAME_INITIAL_STATE = new QualifiedName(AdtPlugin.PLUGIN_ID, "initialstate");//$NON-NLS-1$ /** * Session-property on files which specifies the inclusion-context (reference to another layout * which should be "including" this layout) when the file is opened */ public final static QualifiedName NAME_INCLUDE = new QualifiedName(AdtPlugin.PLUGIN_ID, "includer");//$NON-NLS-1$ /** Reference to the layout editor */ private final LayoutEditor mLayoutEditor; /** Reference to the file being edited. Can also be used to access the {@link IProject}. */ private IFile mEditedFile; /** The configuration composite at the top of the layout editor. */ private ConfigurationComposite mConfigComposite; /** The sash that splits the palette from the canvas. */ private SashForm mSashPalette; /** The sash that splits the palette from the error view. * The error view is shown only when needed. */ private SashForm mSashError; /** The palette displayed on the left of the sash. */ private PaletteControl mPalette; /** The layout canvas displayed to the right of the sash. */ private LayoutCanvasViewer mCanvasViewer; /** The Rules Engine associated with this editor. It is project-specific. */ private RulesEngine mRulesEngine; /** Styled text displaying the most recent error in the error view. */ private StyledText mErrorLabel; /** * The resource reference to a file that should surround this file (e.g. include this file * visually), or null if not applicable */ private Reference mIncludedWithin; private Map<String, Map<String, ResourceValue>> mConfiguredFrameworkRes; private Map<String, Map<String, ResourceValue>> mConfiguredProjectRes; private ProjectCallback mProjectCallback; private boolean mNeedsRecompute = false; private TargetListener mTargetListener; private ConfigListener mConfigListener; private ReloadListener mReloadListener; private boolean mUseExplodeMode; private CustomButton mZoomRealSizeButton; private CustomButton mZoomOutButton; private CustomButton mZoomResetButton; private CustomButton mZoomInButton; private CustomButton mClippingButton; public GraphicalEditorPart(LayoutEditor layoutEditor) { mLayoutEditor = layoutEditor; setPartName("Graphical Layout"); } // ------------------------------------ // Methods overridden from base classes //------------------------------------ /** * Initializes the editor part with a site and input. * {@inheritDoc} */ @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); useNewEditorInput(input); if (mTargetListener == null) { mTargetListener = new TargetListener(); AdtPlugin.getDefault().addTargetListener(mTargetListener); } } private void useNewEditorInput(IEditorInput input) throws PartInitException { // The contract of init() mentions we need to fail if we can't understand the input. if (!(input instanceof FileEditorInput)) { throw new PartInitException("Input is not of type FileEditorInput: " + //$NON-NLS-1$ input == null ? "null" : input.toString()); //$NON-NLS-1$ } } public Image getPageImage() { return IconFactory.getInstance().getIcon("editor_page_design"); //$NON-NLS-1$ } @Override public void createPartControl(Composite parent) { Display d = parent.getDisplay(); GridLayout gl = new GridLayout(1, false); parent.setLayout(gl); gl.marginHeight = gl.marginWidth = 0; // create the top part for the configuration control CustomButton[][] customButtons = new CustomButton[][] { new CustomButton[] { mZoomRealSizeButton = new CustomButton( "*", null, //image "Emulate real size", true /*isToggle*/, false /*defaultValue*/ ) { @Override public void onSelected(boolean newState) { if (rescaleToReal(newState)) { mZoomOutButton.setEnabled(!newState); mZoomResetButton.setEnabled(!newState); mZoomInButton.setEnabled(!newState); } else { mZoomRealSizeButton.setSelection(!newState); } } }, mZoomOutButton = new CustomButton( "-", null, //image "Canvas zoom out." ) { @Override public void onSelected(boolean newState) { rescale(-1); } }, mZoomResetButton = new CustomButton( "100%", null, //image "Reset Canvas to 100%" ) { @Override public void onSelected(boolean newState) { resetScale(); } }, mZoomInButton = new CustomButton( "+", null, //image "Canvas zoom in." ) { @Override public void onSelected(boolean newState) { rescale(+1); } }, }, new CustomButton[] { new CustomButton( null, //text IconFactory.getInstance().getIcon("explode"), //$NON-NLS-1$ "Displays extra margins in the layout.", true /*toggle*/, false /*defaultValue*/ ) { @Override public void onSelected(boolean newState) { mUseExplodeMode = newState; recomputeLayout(); } }, new CustomButton( null, //text IconFactory.getInstance().getIcon("outline"), //$NON-NLS-1$ "Shows the outline of all views in the layout.", true /*toggle*/, false /*defaultValue*/ ) { @Override public void onSelected(boolean newState) { mCanvasViewer.getCanvas().setShowOutline(newState); } }, mClippingButton = new CustomButton( null, //text IconFactory.getInstance().getIcon("clipping"), //$NON-NLS-1$ "Toggles screen clipping on/off", true /*toggle*/, true /*defaultValue*/ ) { @Override public void onSelected(boolean newState) { recomputeLayout(); } } } }; mConfigListener = new ConfigListener(); // Check whether somebody has requested an initial state for the newly opened file. // The initial state is a serialized version of the state compatible with // {@link ConfigurationComposite#CONFIG_STATE}. String initialState = null; IFile file = mEditedFile; if (file == null) { IEditorInput input = mLayoutEditor.getEditorInput(); if (input instanceof FileEditorInput) { file = ((FileEditorInput) input).getFile(); } } if (file != null) { try { initialState = (String) file.getSessionProperty(NAME_INITIAL_STATE); if (initialState != null) { // Only use once file.setSessionProperty(NAME_INITIAL_STATE, null); } } catch (CoreException e) { AdtPlugin.log(e, "Can't read session property %1$s", NAME_INITIAL_STATE); } } mConfigComposite = new ConfigurationComposite(mConfigListener, customButtons, parent, SWT.BORDER, initialState); mSashPalette = new SashForm(parent, SWT.HORIZONTAL); mSashPalette.setLayoutData(new GridData(GridData.FILL_BOTH)); DecorComposite paleteDecor = new DecorComposite(mSashPalette, SWT.BORDER); paleteDecor.setContent(new PaletteControl.PaletteDecor(this)); mPalette = (PaletteControl) paleteDecor.getContentControl(); mSashError = new SashForm(mSashPalette, SWT.VERTICAL | SWT.BORDER); mSashError.setLayoutData(new GridData(GridData.FILL_BOTH)); mCanvasViewer = new LayoutCanvasViewer(mLayoutEditor, mRulesEngine, mSashError, SWT.NONE); - mErrorLabel = new StyledText(mSashError, SWT.READ_ONLY); + mErrorLabel = new StyledText(mSashError, SWT.READ_ONLY | SWT.WRAP); mErrorLabel.setEditable(false); mErrorLabel.setBackground(d.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); mErrorLabel.setForeground(d.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); mErrorLabel.addMouseListener(new ErrorLabelListener()); mSashPalette.setWeights(new int[] { 20, 80 }); mSashError.setWeights(new int[] { 80, 20 }); mSashError.setMaximizedControl(mCanvasViewer.getControl()); // Initialize the state reloadPalette(); getSite().setSelectionProvider(mCanvasViewer); getSite().getPage().addSelectionListener(this); } /** * Listens to workbench selections that does NOT come from {@link LayoutEditor} * (those are generated by ourselves). * <p/> * Selection can be null, as indicated by this class implementing * {@link INullSelectionListener}. */ public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (!(part instanceof LayoutEditor)) { if (part instanceof PageBookView) { PageBookView pbv = (PageBookView) part; IPage currentPage = pbv.getCurrentPage(); if (currentPage instanceof OutlinePage) { LayoutCanvas canvas = getCanvasControl(); if (canvas != null && canvas.getOutlinePage() != currentPage) { // The notification is not for this view; ignore // (can happen when there are multiple pages simultaneously // visible) return; } } } mCanvasViewer.setSelection(selection); } } /** * Rescales canvas. * @param direction +1 for zoom in, -1 for zoom out */ private void rescale(int direction) { double s = mCanvasViewer.getCanvas().getScale(); if (direction > 0) { s = s * 1.2; } else { s = s / 1.2; } // Some operations are faster if the zoom is EXACTLY 1.0 rather than ALMOST 1.0. // (This is because there is a fast-path when image copying and the scale is 1.0; // in that case it does not have to do any scaling). // // If you zoom out 10 times and then back in 10 times, small rounding errors mean // that you end up with a scale=1.0000000000000004. In the cases, when you get close // to 1.0, just make the zoom an exact 1.0. if (Math.abs(s-1.0) < 0.0001) { s = 1.0; } mCanvasViewer.getCanvas().setScale(s, true /*redraw*/); } /** * Reset the canvas scale to 100% */ private void resetScale() { mCanvasViewer.getCanvas().setScale(1, true /*redraw*/); } private boolean rescaleToReal(boolean real) { if (real) { return computeAndSetRealScale(true /*redraw*/); } else { // reset the scale to 100% mCanvasViewer.getCanvas().setScale(1, true /*redraw*/); return true; } } private boolean computeAndSetRealScale(boolean redraw) { // compute average dpi of X and Y float dpi = (mConfigComposite.getXDpi() + mConfigComposite.getYDpi()) / 2.f; // get the monitor dpi float monitor = AdtPrefs.getPrefs().getMonitorDensity(); if (monitor == 0.f) { ResolutionChooserDialog dialog = new ResolutionChooserDialog( mConfigComposite.getShell()); if (dialog.open() == Window.OK) { monitor = dialog.getDensity(); AdtPrefs.getPrefs().setMonitorDensity(monitor); } else { return false; } } mCanvasViewer.getCanvas().setScale(monitor / dpi, redraw); return true; } @Override public void dispose() { getSite().getPage().removeSelectionListener(this); getSite().setSelectionProvider(null); if (mTargetListener != null) { AdtPlugin.getDefault().removeTargetListener(mTargetListener); mTargetListener = null; } if (mReloadListener != null) { LayoutReloadMonitor.getMonitor().removeListener(mReloadListener); mReloadListener = null; } if (mCanvasViewer != null) { mCanvasViewer.dispose(); mCanvasViewer = null; } super.dispose(); } /** * Select the visual element corresponding to the given XML node * @param xmlNode The Node whose element we want to select */ public void select(Node xmlNode) { mCanvasViewer.getCanvas().getSelectionManager().select(xmlNode); } /** * Listens to changes from the Configuration UI banner and triggers layout rendering when * changed. Also provide the Configuration UI with the list of resources/layout to display. */ private class ConfigListener implements IConfigListener { /** * Looks for a file matching the new {@link FolderConfiguration} and attempts to open it. * <p/>If there is no match, notify the user. */ public void onConfigurationChange() { mConfiguredFrameworkRes = mConfiguredProjectRes = null; if (mEditedFile == null || mConfigComposite.getEditedConfig() == null) { return; } // Before doing the normal process, test for the following case. // - the editor is being opened (or reset for a new input) // - the file being opened is not the best match for any possible configuration // - another random compatible config was chosen in the config composite. // The result is that 'match' will not be the file being edited, but because this is not // due to a config change, we should not trigger opening the actual best match (also, // because the editor is still opening the MatchingStrategy woudln't answer true // and the best match file would open in a different editor). // So the solution is that if the editor is being created, we just call recomputeLayout // without looking for a better matching layout file. if (mLayoutEditor.isCreatingPages()) { recomputeLayout(); } else { // get the resources of the file's project. ProjectResources resources = ResourceManager.getInstance().getProjectResources( mEditedFile.getProject()); // from the resources, look for a matching file ResourceFile match = null; if (resources != null) { match = resources.getMatchingFile(mEditedFile.getName(), ResourceFolderType.LAYOUT, mConfigComposite.getCurrentConfig()); } if (match != null) { // since this is coming from Eclipse, this is always an instance of IFileWrapper IFileWrapper iFileWrapper = (IFileWrapper) match.getFile(); IFile iFile = iFileWrapper.getIFile(); if (iFile.equals(mEditedFile) == false) { try { // tell the editor that the next replacement file is due to a config // change. mLayoutEditor.setNewFileOnConfigChange(true); // ask the IDE to open the replacement file. IDE.openEditor(getSite().getWorkbenchWindow().getActivePage(), iFile); // we're done! return; } catch (PartInitException e) { // FIXME: do something! } } // at this point, we have not opened a new file. // Store the state in the current file mConfigComposite.storeState(); // Even though the layout doesn't change, the config changed, and referenced // resources need to be updated. recomputeLayout(); } else { // display the error. FolderConfiguration currentConfig = mConfigComposite.getCurrentConfig(); displayError( "No resources match the configuration\n \n\t%1$s\n \nChange the configuration or create:\n \n\tres/%2$s/%3$s\n \nYou can also click the 'Create' button above.", currentConfig.toDisplayString(), currentConfig.getFolderName(ResourceFolderType.LAYOUT), mEditedFile.getName()); } } } public void onThemeChange() { // Store the state in the current file mConfigComposite.storeState(); recomputeLayout(); } public void onCreate() { LayoutCreatorDialog dialog = new LayoutCreatorDialog(mConfigComposite.getShell(), mEditedFile.getName(), mConfigComposite.getCurrentConfig()); if (dialog.open() == Window.OK) { final FolderConfiguration config = new FolderConfiguration(); dialog.getConfiguration(config); createAlternateLayout(config); } } public void onRenderingTargetPreChange(IAndroidTarget oldTarget) { preRenderingTargetChangeCleanUp(oldTarget); } public void onRenderingTargetPostChange(IAndroidTarget target) { AndroidTargetData targetData = Sdk.getCurrent().getTargetData(target); updateCapabilities(targetData); } public Map<String, Map<String, ResourceValue>> getConfiguredFrameworkResources() { if (mConfiguredFrameworkRes == null && mConfigComposite != null) { ProjectResources frameworkRes = getFrameworkResources(); if (frameworkRes == null) { AdtPlugin.log(IStatus.ERROR, "Failed to get ProjectResource for the framework"); } else { // get the framework resource values based on the current config mConfiguredFrameworkRes = frameworkRes.getConfiguredResources( mConfigComposite.getCurrentConfig()); } } return mConfiguredFrameworkRes; } public Map<String, Map<String, ResourceValue>> getConfiguredProjectResources() { if (mConfiguredProjectRes == null && mConfigComposite != null) { ProjectResources project = getProjectResources(); // make sure they are loaded project.loadAll(); // get the project resource values based on the current config mConfiguredProjectRes = project.getConfiguredResources( mConfigComposite.getCurrentConfig()); } return mConfiguredProjectRes; } /** * Returns a {@link ProjectResources} for the framework resources based on the current * configuration selection. * @return the framework resources or null if not found. */ public ProjectResources getFrameworkResources() { return getFrameworkResources(getRenderingTarget()); } /** * Returns a {@link ProjectResources} for the framework resources of a given * target. * @param target the target for which to return the framework resources. * @return the framework resources or null if not found. */ public ProjectResources getFrameworkResources(IAndroidTarget target) { if (target != null) { AndroidTargetData data = Sdk.getCurrent().getTargetData(target); if (data != null) { return data.getFrameworkResources(); } } return null; } public ProjectResources getProjectResources() { if (mEditedFile != null) { ResourceManager manager = ResourceManager.getInstance(); return manager.getProjectResources(mEditedFile.getProject()); } return null; } /** * Creates a new layout file from the specified {@link FolderConfiguration}. */ private void createAlternateLayout(final FolderConfiguration config) { new Job("Create Alternate Resource") { @Override protected IStatus run(IProgressMonitor monitor) { // get the folder name String folderName = config.getFolderName(ResourceFolderType.LAYOUT); try { // look to see if it exists. // get the res folder IFolder res = (IFolder)mEditedFile.getParent().getParent(); String path = res.getLocation().toOSString(); File newLayoutFolder = new File(path + File.separator + folderName); if (newLayoutFolder.isFile()) { // this should not happen since aapt would have complained // before, but if one disable the automatic build, this could // happen. String message = String.format("File 'res/%1$s' is in the way!", folderName); AdtPlugin.displayError("Layout Creation", message); return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, message); } else if (newLayoutFolder.exists() == false) { // create it. newLayoutFolder.mkdir(); } // now create the file File newLayoutFile = new File(newLayoutFolder.getAbsolutePath() + File.separator + mEditedFile.getName()); newLayoutFile.createNewFile(); InputStream input = mEditedFile.getContents(); FileOutputStream fos = new FileOutputStream(newLayoutFile); byte[] data = new byte[512]; int count; while ((count = input.read(data)) != -1) { fos.write(data, 0, count); } input.close(); fos.close(); // refreshes the res folder to show up the new // layout folder (if needed) and the file. // We use a progress monitor to catch the end of the refresh // to trigger the edit of the new file. res.refreshLocal(IResource.DEPTH_INFINITE, new IProgressMonitor() { public void done() { mConfigComposite.getDisplay().asyncExec(new Runnable() { public void run() { onConfigurationChange(); } }); } public void beginTask(String name, int totalWork) { // pass } public void internalWorked(double work) { // pass } public boolean isCanceled() { // pass return false; } public void setCanceled(boolean value) { // pass } public void setTaskName(String name) { // pass } public void subTask(String name) { // pass } public void worked(int work) { // pass } }); } catch (IOException e2) { String message = String.format( "Failed to create File 'res/%1$s/%2$s' : %3$s", folderName, mEditedFile.getName(), e2.getMessage()); AdtPlugin.displayError("Layout Creation", message); return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, message, e2); } catch (CoreException e2) { String message = String.format( "Failed to create File 'res/%1$s/%2$s' : %3$s", folderName, mEditedFile.getName(), e2.getMessage()); AdtPlugin.displayError("Layout Creation", message); return e2.getStatus(); } return Status.OK_STATUS; } }.schedule(); } } /** * Listens to target changed in the current project, to trigger a new layout rendering. */ private class TargetListener implements ITargetChangeListener { public void onProjectTargetChange(IProject changedProject) { if (changedProject != null && changedProject.equals(getProject())) { updateEditor(); } } public void onTargetLoaded(IAndroidTarget loadedTarget) { IAndroidTarget target = getRenderingTarget(); if (target != null && target.equals(loadedTarget)) { updateEditor(); } } public void onSdkLoaded() { // get the current rendering target to unload it IAndroidTarget oldTarget = getRenderingTarget(); preRenderingTargetChangeCleanUp(oldTarget); // get the project target Sdk currentSdk = Sdk.getCurrent(); if (currentSdk != null) { IAndroidTarget target = currentSdk.getTarget(mEditedFile.getProject()); if (target != null) { mConfigComposite.onSdkLoaded(target); mConfigListener.onConfigurationChange(); } } } private void updateEditor() { mLayoutEditor.commitPages(false /* onSave */); // because the target changed we must reset the configured resources. mConfiguredFrameworkRes = mConfiguredProjectRes = null; // make sure we remove the custom view loader, since its parent class loader is the // bridge class loader. mProjectCallback = null; // recreate the ui root node always, this will also call onTargetChange // on the config composite mLayoutEditor.initUiRootNode(true /*force*/); } private IProject getProject() { return getLayoutEditor().getProject(); } } /** Refresh the configured project resources associated with this editor */ /*package*/ void refreshProjectResources() { mConfiguredProjectRes = null; mConfigListener.getConfiguredProjectResources(); } /** * Returns the currently edited file * * @return the currently edited file, or null */ public IFile getEditedFile() { return mEditedFile; } /** * Returns the project for the currently edited file, or null * * @return the project containing the edited file, or null */ public IProject getProject() { if (mEditedFile != null) { return mEditedFile.getProject(); } else { return null; } } // ---------------- /** * Save operation in the Graphical Editor Part. * <p/> * In our workflow, the model is owned by the Structured XML Editor. * The graphical layout editor just displays it -- thus we don't really * save anything here. * <p/> * This must NOT call the parent editor part. At the contrary, the parent editor * part will call this *after* having done the actual save operation. * <p/> * The only action this editor must do is mark the undo command stack as * being no longer dirty. */ @Override public void doSave(IProgressMonitor monitor) { // TODO implement a command stack // getCommandStack().markSaveLocation(); // firePropertyChange(PROP_DIRTY); } /** * Save operation in the Graphical Editor Part. * <p/> * In our workflow, the model is owned by the Structured XML Editor. * The graphical layout editor just displays it -- thus we don't really * save anything here. */ @Override public void doSaveAs() { // pass } /** * In our workflow, the model is owned by the Structured XML Editor. * The graphical layout editor just displays it -- thus we don't really * save anything here. */ @Override public boolean isDirty() { return false; } /** * In our workflow, the model is owned by the Structured XML Editor. * The graphical layout editor just displays it -- thus we don't really * save anything here. */ @Override public boolean isSaveAsAllowed() { return false; } @Override public void setFocus() { // TODO Auto-generated method stub } /** * Responds to a page change that made the Graphical editor page the activated page. */ public void activated() { if (mNeedsRecompute) { recomputeLayout(); } } /** * Responds to a page change that made the Graphical editor page the deactivated page */ public void deactivated() { // nothing to be done here for now. } /** * Opens and initialize the editor with a new file. * @param file the file being edited. */ public void openFile(IFile file) { mEditedFile = file; mConfigComposite.setFile(mEditedFile); if (mReloadListener == null) { mReloadListener = new ReloadListener(); LayoutReloadMonitor.getMonitor().addListener(mEditedFile.getProject(), mReloadListener); } if (mRulesEngine == null) { mRulesEngine = new RulesEngine(this, mEditedFile.getProject()); if (mCanvasViewer != null) { mCanvasViewer.getCanvas().setRulesEngine(mRulesEngine); } } // Pick up hand-off data: somebody requesting this file to be opened may have // requested that it should be opened as included within another file if (mEditedFile != null) { try { mIncludedWithin = (Reference) mEditedFile.getSessionProperty(NAME_INCLUDE); if (mIncludedWithin != null) { // Only use once mEditedFile.setSessionProperty(NAME_INCLUDE, null); } } catch (CoreException e) { AdtPlugin.log(e, "Can't access session property %1$s", NAME_INCLUDE); } } } /** * Resets the editor with a replacement file. * @param file the replacement file. */ public void replaceFile(IFile file) { mEditedFile = file; mConfigComposite.replaceFile(mEditedFile); } /** * Resets the editor with a replacement file coming from a config change in the config * selector. * @param file the replacement file. */ public void changeFileOnNewConfig(IFile file) { mEditedFile = file; mConfigComposite.changeFileOnNewConfig(mEditedFile); } /** * Responds to a target change for the project of the edited file */ public void onTargetChange() { AndroidTargetData targetData = mConfigComposite.onXmlModelLoaded(); updateCapabilities(targetData); mConfigListener.onConfigurationChange(); } /** Updates the capabilities for the given target data (which may be null) */ private void updateCapabilities(AndroidTargetData targetData) { if (targetData != null) { LayoutLibrary layoutLib = targetData.getLayoutLibrary(); setClippingSupport(layoutLib.supports(Capability.UNBOUND_RENDERING)); if (mIncludedWithin != null && !layoutLib.supports(Capability.EMBEDDED_LAYOUT)) { showIn(null); } } } public LayoutEditor getLayoutEditor() { return mLayoutEditor; } /** * Returns the {@link RulesEngine} associated with this editor * * @return the {@link RulesEngine} associated with this editor, never null */ public RulesEngine getRulesEngine() { return mRulesEngine; } /** * Return the {@link LayoutCanvas} associated with this editor * * @return the associated {@link LayoutCanvas} */ public LayoutCanvas getCanvasControl() { if (mCanvasViewer != null) { return mCanvasViewer.getCanvas(); } return null; } public UiDocumentNode getModel() { return mLayoutEditor.getUiRootNode(); } /** * Callback for XML model changed. Only update/recompute the layout if the editor is visible */ public void onXmlModelChanged() { // To optimize the rendering when the user is editing in the XML pane, we don't // refresh the editor if it's not the active part. // // This behavior is acceptable when the editor is the single "full screen" part // (as in this case active means visible.) // Unfortunately this breaks in 2 cases: // - when performing a drag'n'drop from one editor to another, the target is not // properly refreshed before it becomes active. // - when duplicating the editor window and placing both editors side by side (xml in one // and canvas in the other one), the canvas may not be refreshed when the XML is edited. // // TODO find a way to really query whether the pane is visible, not just active. if (mLayoutEditor.isGraphicalEditorActive()) { recomputeLayout(); } else { // Remember we want to recompute as soon as the editor becomes active. mNeedsRecompute = true; } } public void recomputeLayout() { try { if (!ensureFileValid()) { return; } UiDocumentNode model = getModel(); if (!ensureModelValid(model)) { // Although we display an error, we still treat an empty document as a // successful layout result so that we can drop new elements in it. // // For that purpose, create a special LayoutScene that has no image, // no root view yet indicates success and then update the canvas with it. mCanvasViewer.getCanvas().setSession( new StaticRenderSession( Result.Status.SUCCESS.createResult(), null /*rootViewInfo*/, null /*image*/), null /*explodeNodes*/); return; } LayoutLibrary layoutLib = getReadyLayoutLib(true /*displayError*/); if (layoutLib != null) { // if drawing in real size, (re)set the scaling factor. if (mZoomRealSizeButton.getSelection()) { computeAndSetRealScale(false /* redraw */); } IProject iProject = mEditedFile.getProject(); renderWithBridge(iProject, model, layoutLib); } } finally { // no matter the result, we are done doing the recompute based on the latest // resource/code change. mNeedsRecompute = false; } } public void reloadPalette() { if (mPalette != null) { mPalette.reloadPalette(mLayoutEditor.getTargetData()); } } /** * Renders the given model, using this editor's theme and screen settings, and returns * the result as a {@link RenderSession}. * * @param model the model to be rendered, which can be different than the editor's own * {@link #getModel()}. * @param width the width to use for the layout, or -1 to use the width of the screen * associated with this editor * @param height the height to use for the layout, or -1 to use the height of the screen * associated with this editor * @param explodeNodes a set of nodes to explode, or null for none * @param transparentBackground If true, the rendering will <b>not</b> paint the * normal background requested by the theme, and it will instead paint the * background using a fully transparent background color * @param logger a logger where rendering errors are reported * @return the resulting rendered image wrapped in an {@link RenderSession} */ public RenderSession render(UiDocumentNode model, int width, int height, Set<UiElementNode> explodeNodes, boolean transparentBackground, LayoutLog logger) { if (!ensureFileValid()) { return null; } if (!ensureModelValid(model)) { return null; } LayoutLibrary layoutLib = getReadyLayoutLib(true /*displayError*/); IProject iProject = mEditedFile.getProject(); return renderWithBridge(iProject, model, layoutLib, width, height, explodeNodes, transparentBackground, logger); } /** * Returns the {@link LayoutLibrary} associated with this editor, if it has * been initialized already. May return null if it has not been initialized (or has * not finished initializing). * * @return The {@link LayoutLibrary}, or null */ public LayoutLibrary getLayoutLibrary() { return getReadyLayoutLib(false /*displayError*/); } /** * Returns the current bounds of the Android device screen, in canvas control pixels. * * @return the bounds of the screen, never null */ public Rectangle getScreenBounds() { return mConfigComposite.getScreenBounds(); } /** * Returns the scale to multiply pixels in the layout coordinate space with to obtain * the corresponding dip (device independent pixel) * * @return the scale to multiple layout coordinates with to obtain the dip position */ public float getDipScale() { return DEFAULT_DENSITY / (float) mConfigComposite.getDensity().getDpiValue(); } // --- private methods --- private void setClippingSupport(boolean b) { mClippingButton.setEnabled(b); if (b) { mClippingButton.setToolTipText("Toggles screen clipping on/off"); } else { mClippingButton.setSelection(true); mClippingButton.setToolTipText("Non clipped rendering is not supported"); } } /** * Ensure that the file associated with this editor is valid (exists and is * synchronized). Any reasons why it is not are displayed in the editor's error area. * * @return True if the editor is valid, false otherwise. */ private boolean ensureFileValid() { // check that the resource exists. If the file is opened but the project is closed // or deleted for some reason (changed from outside of eclipse), then this will // return false; if (mEditedFile.exists() == false) { displayError("Resource '%1$s' does not exist.", mEditedFile.getFullPath().toString()); return false; } if (mEditedFile.isSynchronized(IResource.DEPTH_ZERO) == false) { String message = String.format("%1$s is out of sync. Please refresh.", mEditedFile.getName()); displayError(message); // also print it in the error console. IProject iProject = mEditedFile.getProject(); AdtPlugin.printErrorToConsole(iProject.getName(), message); return false; } return true; } /** * Returns a {@link LayoutLibrary} that is ready for rendering, or null if the bridge * is not available or not ready yet (due to SDK loading still being in progress etc). * If enabled, any reasons preventing the bridge from being returned are displayed to the * editor's error area. * * @param displayError whether to display the loading error or not. * * @return LayoutBridge the layout bridge for rendering this editor's scene */ private LayoutLibrary getReadyLayoutLib(boolean displayError) { Sdk currentSdk = Sdk.getCurrent(); if (currentSdk != null) { IAndroidTarget target = getRenderingTarget(); if (target != null) { AndroidTargetData data = currentSdk.getTargetData(target); if (data != null) { LayoutLibrary layoutLib = data.getLayoutLibrary(); if (layoutLib.getStatus() == LoadStatus.LOADED) { return layoutLib; } else if (displayError) { // getBridge() == null // SDK is loaded but not the layout library! // check whether the bridge managed to load, or not if (layoutLib.getStatus() == LoadStatus.LOADING) { displayError("Eclipse is loading framework information and the layout library from the SDK folder.\n%1$s will refresh automatically once the process is finished.", mEditedFile.getName()); } else { String message = layoutLib.getLoadMessage(); displayError("Eclipse failed to load the framework information and the layout library!" + message != null ? "\n" + message : ""); } } } else { // data == null // It can happen that the workspace refreshes while the SDK is loading its // data, which could trigger a redraw of the opened layout if some resources // changed while Eclipse is closed. // In this case data could be null, but this is not an error. // We can just silently return, as all the opened editors are automatically // refreshed once the SDK finishes loading. LoadStatus targetLoadStatus = currentSdk.checkAndLoadTargetData(target, null); // display error is asked. if (displayError) { switch (targetLoadStatus) { case LOADING: displayError("The project target (%1$s) is still loading.\n%2$s will refresh automatically once the process is finished.", target.getName(), mEditedFile.getName()); break; case FAILED: // known failure case LOADED: // success but data isn't loaded?!?! displayError("The project target (%s) was not properly loaded.", target.getName()); break; } } } } else if (displayError) { // target == null displayError("The project target is not set."); } } else if (displayError) { // currentSdk == null displayError("Eclipse is loading the SDK.\n%1$s will refresh automatically once the process is finished.", mEditedFile.getName()); } return null; } /** * Returns the {@link IAndroidTarget} used for the rendering. * <p/> * This first looks for the rendering target setup in the config UI, and if nothing has * been setup yet, returns the target of the project. * * @return an IAndroidTarget object or null if no target is setup and the project has no * target set. * */ private IAndroidTarget getRenderingTarget() { // if the SDK is null no targets are loaded. Sdk currentSdk = Sdk.getCurrent(); if (currentSdk == null) { return null; } assert mConfigComposite.getDisplay().getThread() == Thread.currentThread(); // attempt to get a target from the configuration selector. IAndroidTarget renderingTarget = mConfigComposite.getRenderingTarget(); if (renderingTarget != null) { return renderingTarget; } // fall back to the project target if (mEditedFile != null) { return currentSdk.getTarget(mEditedFile.getProject()); } return null; } /** * Returns whether the current rendering target supports the given capability * * @param capability the capability to be looked up * @return true if the current rendering target supports the given capability */ public boolean renderingSupports(Capability capability) { IAndroidTarget target = getRenderingTarget(); if (target != null) { AndroidTargetData targetData = Sdk.getCurrent().getTargetData(target); LayoutLibrary layoutLib = targetData.getLayoutLibrary(); return layoutLib.supports(capability); } return false; } private boolean ensureModelValid(UiDocumentNode model) { // check there is actually a model (maybe the file is empty). if (model.getUiChildren().size() == 0) { displayError( "No XML content. Please add a root view or layout to your document."); return false; } return true; } private void renderWithBridge(IProject iProject, UiDocumentNode model, LayoutLibrary layoutLib) { LayoutCanvas canvas = getCanvasControl(); Set<UiElementNode> explodeNodes = canvas.getNodesToExplode(); // Compute the layout Rectangle rect = getScreenBounds(); int width = rect.width; int height = rect.height; RenderLogger logger = new RenderLogger(mEditedFile.getName()); RenderSession session = renderWithBridge(iProject, model, layoutLib, width, height, explodeNodes, false, logger); canvas.setSession(session, explodeNodes); // update the UiElementNode with the layout info. if (session.getResult().isSuccess() == false) { // An error was generated. Print it (and any other accumulated warnings) String errorMessage = session.getResult().getErrorMessage(); if (errorMessage != null && errorMessage.length() > 0) { logger.error(null, session.getResult().getErrorMessage()); } else if (!logger.hasProblems()) { logger.error(null, "Unexpected error in rendering, no details given"); } displayError(logger.getProblems()); } else { // Success means there was no exception. But we might have detected // some missing classes and swapped them by a mock view. Set<String> missingClasses = mProjectCallback.getMissingClasses(); Set<String> brokenClasses = mProjectCallback.getUninstantiatableClasses(); if (missingClasses.size() > 0 || brokenClasses.size() > 0) { displayFailingClasses(missingClasses, brokenClasses); } else if (logger.hasProblems()) { displayError(logger.getProblems()); } else { // Nope, no missing or broken classes. Clear success, congrats! hideError(); } } model.refreshUi(); } private RenderSession renderWithBridge(IProject iProject, UiDocumentNode model, LayoutLibrary layoutLib, int width, int height, Set<UiElementNode> explodeNodes, boolean transparentBackground, LayoutLog logger) { ResourceManager resManager = ResourceManager.getInstance(); ProjectResources projectRes = resManager.getProjectResources(iProject); if (projectRes == null) { displayError("Missing project resources."); return null; } // Get the resources of the file's project. Map<String, Map<String, ResourceValue>> configuredProjectRes = mConfigListener.getConfiguredProjectResources(); // Get the framework resources Map<String, Map<String, ResourceValue>> frameworkResources = mConfigListener.getConfiguredFrameworkResources(); // Abort the rendering if the resources are not found. if (configuredProjectRes == null) { displayError("Missing project resources for current configuration."); return null; } if (frameworkResources == null) { displayError("Missing framework resources."); return null; } // Lazily create the project callback the first time we need it if (mProjectCallback == null) { mProjectCallback = new ProjectCallback( layoutLib.getClassLoader(), projectRes, iProject); } else { // Also clears the set of missing classes prior to rendering mProjectCallback.getMissingClasses().clear(); } // get the selected theme String theme = mConfigComposite.getTheme(); if (theme == null) { displayError("Missing theme."); return null; } if (mUseExplodeMode) { // compute how many padding in x and y will bump the screen size List<UiElementNode> children = model.getUiChildren(); if (children.size() == 1) { ExplodedRenderingHelper helper = new ExplodedRenderingHelper( children.get(0).getXmlNode(), iProject); // there are 2 paddings for each view // left and right, or top and bottom. int paddingValue = ExplodedRenderingHelper.PADDING_VALUE * 2; width += helper.getWidthPadding() * paddingValue; height += helper.getHeightPadding() * paddingValue; } } int density = mConfigComposite.getDensity().getDpiValue(); float xdpi = mConfigComposite.getXDpi(); float ydpi = mConfigComposite.getYDpi(); boolean isProjectTheme = mConfigComposite.isProjectTheme(); ILayoutPullParser modelParser = new UiElementPullParser(model, mUseExplodeMode, explodeNodes, density, xdpi, iProject); ILayoutPullParser topParser = modelParser; // Code to support editing included layout // Outer layout name: if (mIncludedWithin != null) { String contextLayoutName = mIncludedWithin.getName(); // Find the layout file. Map<String, ResourceValue> layouts = configuredProjectRes.get( ResourceType.LAYOUT.getName()); ResourceValue contextLayout = layouts.get(contextLayoutName); if (contextLayout != null) { File layoutFile = new File(contextLayout.getValue()); if (layoutFile.isFile()) { try { // Get the name of the layout actually being edited, without the extension // as it's what IXmlPullParser.getParser(String) will receive. String queryLayoutName = getLayoutResourceName(); topParser = new ContextPullParser(queryLayoutName, modelParser); topParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); topParser.setInput(new FileReader(layoutFile)); } catch (XmlPullParserException e) { AdtPlugin.log(e, ""); //$NON-NLS-1$ } catch (FileNotFoundException e) { // this will not happen since we check above. } } } } RenderingMode renderingMode = RenderingMode.NORMAL; if (mClippingButton.getSelection() == false) { renderingMode = RenderingMode.FULL_EXPAND; } else { // FIXME set the rendering mode using ViewRule or something. List<UiElementNode> children = model.getUiChildren(); if (children.size() > 0 && children.get(0).getDescriptor().getXmlLocalName().equals(SCROLL_VIEW)) { renderingMode = RenderingMode.V_SCROLL; } } Params params = new Params( topParser, iProject /* projectKey */, width, height, renderingMode, density, xdpi, ydpi, theme, isProjectTheme, configuredProjectRes, frameworkResources, mProjectCallback, logger); if (transparentBackground) { // It doesn't matter what the background color is as long as the alpha // is 0 (fully transparent). We're using red to make it more obvious if // for some reason the background is painted when it shouldn't be. params.setOverrideBgColor(0x00FF0000); } // set the Image Overlay as the image factory. params.setImageFactory(getCanvasControl().getImageOverlay()); try { return layoutLib.createSession(params); } catch (RuntimeException t) { // Exceptions from the bridge displayError(t.getLocalizedMessage()); throw t; } } /** * Returns the resource name of this layout, NOT including the @layout/ prefix * * @return the resource name of this layout, NOT including the @layout/ prefix */ public String getLayoutResourceName() { String name = mEditedFile.getName(); int dotIndex = name.indexOf('.'); if (dotIndex != -1) { name = name.substring(0, dotIndex); } return name; } /** * Cleans up when the rendering target is about to change * @param oldTarget the old rendering target. */ private void preRenderingTargetChangeCleanUp(IAndroidTarget oldTarget) { // first clear the caches related to this file in the old target Sdk currentSdk = Sdk.getCurrent(); if (currentSdk != null) { AndroidTargetData data = currentSdk.getTargetData(oldTarget); if (data != null) { LayoutLibrary layoutLib = data.getLayoutLibrary(); // layoutLib can never be null. layoutLib.clearCaches(mEditedFile.getProject()); } } // FIXME: get rid of the current LayoutScene if any. } private class ReloadListener implements ILayoutReloadListener { /** * Called when the file changes triggered a redraw of the layout */ public void reloadLayout(final ChangeFlags flags, final boolean libraryChanged) { Display display = mConfigComposite.getDisplay(); display.asyncExec(new Runnable() { public void run() { reloadLayoutSwt(flags, libraryChanged); } }); } /** Reload layout. <b>Must be called on the SWT thread</b> */ private void reloadLayoutSwt(ChangeFlags flags, boolean libraryChanged) { assert mConfigComposite.getDisplay().getThread() == Thread.currentThread(); boolean recompute = false; if (flags.rClass) { recompute = true; if (mEditedFile != null) { ResourceManager manager = ResourceManager.getInstance(); ProjectResources projectRes = manager.getProjectResources( mEditedFile.getProject()); if (projectRes != null) { projectRes.resetDynamicIds(); } } } if (flags.localeList) { // the locale list *potentially* changed so we update the locale in the // config composite. // However there's no recompute, as it could not be needed // (for instance a new layout) // If a resource that's not a layout changed this will trigger a recompute anyway. mConfigComposite.updateLocales(); } // if a resources was modified. // also, if a layout in a library was modified. if (flags.resources || (libraryChanged && flags.layout)) { recompute = true; // TODO: differentiate between single and multi resource file changed, and whether // the resource change affects the cache. // force a reparse in case a value XML file changed. mConfiguredProjectRes = null; // clear the cache in the bridge in case a bitmap/9-patch changed. LayoutLibrary layoutLib = getReadyLayoutLib(true /*displayError*/); if (layoutLib != null) { layoutLib.clearCaches(mEditedFile.getProject()); } } if (flags.code) { // only recompute if the custom view loader was used to load some code. if (mProjectCallback != null && mProjectCallback.isUsed()) { mProjectCallback = null; recompute = true; } } if (recompute) { if (mLayoutEditor.isGraphicalEditorActive()) { recomputeLayout(); } else { mNeedsRecompute = true; } } } } // ---- Error handling ---- /** * Switches the sash to display the error label. * * @param errorFormat The new error to display if not null. * @param parameters String.format parameters for the error format. */ private void displayError(String errorFormat, Object...parameters) { if (errorFormat != null) { mErrorLabel.setText(String.format(errorFormat, parameters)); } else { mErrorLabel.setText(""); } mSashError.setMaximizedControl(null); } /** Displays the canvas and hides the error label. */ private void hideError() { mErrorLabel.setText(""); mSashError.setMaximizedControl(mCanvasViewer.getControl()); } /** * Switches the sash to display the error label to show a list of * missing classes and give options to create them. */ private void displayFailingClasses(Set<String> missingClasses, Set<String> brokenClasses) { mErrorLabel.setText(""); if (missingClasses.size() > 0) { addText(mErrorLabel, "The following classes could not be found:\n"); for (String clazz : missingClasses) { addText(mErrorLabel, "- "); addClassLink(mErrorLabel, clazz); addText(mErrorLabel, "\n"); } } if (brokenClasses.size() > 0) { addText(mErrorLabel, "The following classes could not be instantiated:\n"); // Do we have a custom class (not an Android or add-ons class) boolean haveCustomClass = false; for (String clazz : brokenClasses) { addText(mErrorLabel, "- "); addClassLink(mErrorLabel, clazz); addText(mErrorLabel, "\n"); if (!(clazz.startsWith("android.") || //$NON-NLS-1$ clazz.startsWith("com.google."))) { //$NON-NLS-1$ haveCustomClass = true; } } addText(mErrorLabel, "See the Error Log (Window > Show View) for more details.\n"); if (haveCustomClass) { addText(mErrorLabel, "Tip: Use View.isInEditMode() in your custom views " + "to skip code when shown in Eclipse"); } } mSashError.setMaximizedControl(null); } /** Add a normal line of text to the styled text widget. */ private void addText(StyledText styledText, String...string) { for (String s : string) { styledText.append(s); } } /** * Add a URL-looking link to the styled text widget. * <p/> * A mouse-click listener is setup and it interprets the link as being a missing class name. * The logic *must* be changed if this is used later for a different purpose. */ private void addClassLink(StyledText styledText, String link) { String s = styledText.getText(); int start = (s == null ? 0 : s.length()); styledText.append(link); StyleRange sr = new ClassLinkStyleRange(); sr.start = start; sr.length = link.length(); sr.fontStyle = SWT.NORMAL; sr.underlineStyle = SWT.UNDERLINE_LINK; sr.underline = true; styledText.setStyleRange(sr); } /** * Looks up the resource file corresponding to the given type * * @param type The type of resource to look up, such as {@link ResourceType#LAYOUT} * @param name The name of the resource (not including ".xml") * @param isFrameworkResource if true, the resource is a framework resource, otherwise * it's a project resource * @return the resource file defining the named resource, or null if not found */ public IPath findResourceFile(ResourceType type, String name, boolean isFrameworkResource) { // FIXME: This code does not handle theme value resolution. // There is code to handle this, but it's in layoutlib; we should // expose that and use it here. Map<String, Map<String, ResourceValue>> map; map = isFrameworkResource ? mConfiguredFrameworkRes : mConfiguredProjectRes; if (map == null) { // Not yet configured return null; } Map<String, ResourceValue> layoutMap = map.get(type.getName()); if (layoutMap != null) { ResourceValue value = layoutMap.get(name); if (value != null) { String valueStr = value.getValue(); if (valueStr.startsWith("?")) { //$NON-NLS-1$ // FIXME: It's a reference. We should resolve this properly. return null; } return new Path(valueStr); } } return null; } /** * Looks up the path to the file corresponding to the given attribute value, such as * @layout/foo, which will return the foo.xml file in res/layout/. (The general format * of the resource url is {@literal @[<package_name>:]<resource_type>/<resource_name>}. * * @param url the attribute url * @return the path to the file defining this attribute, or null if not found */ public IPath findResourceFile(String url) { if (!url.startsWith("@")) { //$NON-NLS-1$ return null; } int typeEnd = url.indexOf('/', 1); if (typeEnd == -1) { return null; } int nameBegin = typeEnd + 1; int typeBegin = 1; int colon = url.lastIndexOf(':', typeEnd); boolean isFrameworkResource = false; if (colon != -1) { // The URL contains a package name. // While the url format technically allows other package names, // the platform apparently only supports @android for now (or if it does, // there are no usages in the current code base so this is not common). String packageName = url.substring(typeBegin, colon); if (ANDROID_PKG.equals(packageName)) { isFrameworkResource = true; } typeBegin = colon + 1; } String typeName = url.substring(typeBegin, typeEnd); ResourceType type = ResourceType.getEnum(typeName); if (type == null) { return null; } String name = url.substring(nameBegin); return findResourceFile(type, name, isFrameworkResource); } /** * Resolve the given @string reference into a literal String using the current project * configuration * * @param text the text resource reference to resolve * @return the resolved string, or null */ public String findString(String text) { if (text.startsWith(STRING_PREFIX)) { return findString(text.substring(STRING_PREFIX.length()), false); } else if (text.startsWith(ANDROID_STRING_PREFIX)) { return findString(text.substring(ANDROID_STRING_PREFIX.length()), true); } else { return text; } } private String findString(String name, boolean isFrameworkResource) { Map<String, Map<String, ResourceValue>> map; map = isFrameworkResource ? mConfiguredFrameworkRes : mConfiguredProjectRes; if (map == null) { // Not yet configured return null; } Map<String, ResourceValue> layoutMap = map.get(ResourceType.STRING.getName()); if (layoutMap != null) { ResourceValue value = layoutMap.get(name); if (value != null) { // FIXME: This code does not handle theme value resolution. // There is code to handle this, but it's in layoutlib; we should // expose that and use it here. return value.getValue(); } } return null; } /** This StyleRange represents a missing class link that the user can click */ private static class ClassLinkStyleRange extends StyleRange {} /** * Returns the error label for the graphical editor (which may not be visible * or showing errors) * * @return the error label, never null */ StyledText getErrorLabel() { return mErrorLabel; } /** * Monitor clicks on the error label. * If the click happens on a style range created by * {@link GraphicalEditorPart#addClassLink(StyledText, String)}, we assume it's about * a missing class and we then proceed to display the standard Eclipse class creator wizard. */ private class ErrorLabelListener extends MouseAdapter { @Override public void mouseUp(MouseEvent event) { super.mouseUp(event); if (event.widget != mErrorLabel) { return; } int offset = mErrorLabel.getCaretOffset(); StyleRange r = null; StyleRange[] ranges = mErrorLabel.getStyleRanges(); if (ranges != null && ranges.length > 0) { for (StyleRange sr : ranges) { if (sr.start <= offset && sr.start + sr.length > offset) { r = sr; break; } } } if (r instanceof ClassLinkStyleRange) { String link = mErrorLabel.getText(r.start, r.start + r.length - 1); createNewClass(link); } LayoutCanvas canvas = getCanvasControl(); canvas.updateMenuActionState(canvas.getSelectionManager().getSelections().isEmpty()); } private void createNewClass(String fqcn) { int pos = fqcn.lastIndexOf('.'); String packageName = pos < 0 ? "" : fqcn.substring(0, pos); //$NON-NLS-1$ String className = pos <= 0 || pos >= fqcn.length() ? "" : fqcn.substring(pos + 1); //$NON-NLS-1$ // create the wizard page for the class creation, and configure it NewClassWizardPage page = new NewClassWizardPage(); // set the parent class page.setSuperClass(SdkConstants.CLASS_VIEW, true /* canBeModified */); // get the source folders as java elements. IPackageFragmentRoot[] roots = getPackageFragmentRoots(mLayoutEditor.getProject(), true /*include_containers*/); IPackageFragmentRoot currentRoot = null; IPackageFragment currentFragment = null; int packageMatchCount = -1; for (IPackageFragmentRoot root : roots) { // Get the java element for the package. // This method is said to always return a IPackageFragment even if the // underlying folder doesn't exist... IPackageFragment fragment = root.getPackageFragment(packageName); if (fragment != null && fragment.exists()) { // we have a perfect match! we use it. currentRoot = root; currentFragment = fragment; packageMatchCount = -1; break; } else { // we don't have a match. we look for the fragment with the best match // (ie the closest parent package we can find) try { IJavaElement[] children; children = root.getChildren(); for (IJavaElement child : children) { if (child instanceof IPackageFragment) { fragment = (IPackageFragment)child; if (packageName.startsWith(fragment.getElementName())) { // its a match. get the number of segments String[] segments = fragment.getElementName().split("\\."); //$NON-NLS-1$ if (segments.length > packageMatchCount) { packageMatchCount = segments.length; currentFragment = fragment; currentRoot = root; } } } } } catch (JavaModelException e) { // Couldn't get the children: we just ignore this package root. } } } ArrayList<IPackageFragment> createdFragments = null; if (currentRoot != null) { // if we have a perfect match, we set it and we're done. if (packageMatchCount == -1) { page.setPackageFragmentRoot(currentRoot, true /* canBeModified*/); page.setPackageFragment(currentFragment, true /* canBeModified */); } else { // we have a partial match. // create the package. We have to start with the first segment so that we // know what to delete in case of a cancel. try { createdFragments = new ArrayList<IPackageFragment>(); int totalCount = packageName.split("\\.").length; //$NON-NLS-1$ int count = 0; int index = -1; // skip the matching packages while (count < packageMatchCount) { index = packageName.indexOf('.', index+1); count++; } // create the rest of the segments, except for the last one as indexOf will // return -1; while (count < totalCount - 1) { index = packageName.indexOf('.', index+1); count++; createdFragments.add(currentRoot.createPackageFragment( packageName.substring(0, index), true /* force*/, new NullProgressMonitor())); } // create the last package createdFragments.add(currentRoot.createPackageFragment( packageName, true /* force*/, new NullProgressMonitor())); // set the root and fragment in the Wizard page page.setPackageFragmentRoot(currentRoot, true /* canBeModified*/); page.setPackageFragment(createdFragments.get(createdFragments.size()-1), true /* canBeModified */); } catch (JavaModelException e) { // If we can't create the packages, there's a problem. // We revert to the default package for (IPackageFragmentRoot root : roots) { // Get the java element for the package. // This method is said to always return a IPackageFragment even if the // underlying folder doesn't exist... IPackageFragment fragment = root.getPackageFragment(packageName); if (fragment != null && fragment.exists()) { page.setPackageFragmentRoot(root, true /* canBeModified*/); page.setPackageFragment(fragment, true /* canBeModified */); break; } } } } } else if (roots.length > 0) { // if we haven't found a valid fragment, we set the root to the first source folder. page.setPackageFragmentRoot(roots[0], true /* canBeModified*/); } // if we have a starting class name we use it if (className != null) { page.setTypeName(className, true /* canBeModified*/); } // create the action that will open it the wizard. OpenNewClassWizardAction action = new OpenNewClassWizardAction(); action.setConfiguredWizardPage(page); action.run(); IJavaElement element = action.getCreatedElement(); if (element == null) { // lets delete the packages we created just for this. // we need to start with the leaf and go up if (createdFragments != null) { try { for (int i = createdFragments.size() - 1 ; i >= 0 ; i--) { createdFragments.get(i).delete(true /* force*/, new NullProgressMonitor()); } } catch (JavaModelException e) { e.printStackTrace(); } } } } /** * Computes and return the {@link IPackageFragmentRoot}s corresponding to the source * folders of the specified project. * * @param project the project * @param include_containers True to include containers * @return an array of IPackageFragmentRoot. */ private IPackageFragmentRoot[] getPackageFragmentRoots(IProject project, boolean include_containers) { ArrayList<IPackageFragmentRoot> result = new ArrayList<IPackageFragmentRoot>(); try { IJavaProject javaProject = JavaCore.create(project); IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots(); for (int i = 0; i < roots.length; i++) { IClasspathEntry entry = roots[i].getRawClasspathEntry(); if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE || (include_containers && entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER)) { result.add(roots[i]); } } } catch (JavaModelException e) { } return result.toArray(new IPackageFragmentRoot[result.size()]); } } /** * Reopens this file as included within the given file (this assumes that the given * file has an include tag referencing this view, and the set of views that have this * property can be found using the {@link IncludeFinder}. * * @param includeWithin reference to a file to include as a surrounding context, * or null to show the file standalone */ public void showIn(Reference includeWithin) { mIncludedWithin = includeWithin; if (includeWithin != null) { IFile file = includeWithin.getFile(); // Update configuration if (file != null) { mConfigComposite.resetConfigFor(file); } } recomputeLayout(); } /** * Returns the resource name of the file that is including this current layout, if any * (may be null) * * @return the resource name of an including layout, or null */ public Reference getIncludedWithin() { return mIncludedWithin; } /** * Return all resource names of a given type, either in the project or in the * framework. * * @param framework if true, return all the framework resource names, otherwise return * all the project resource names * @param type the type of resource to look up * @return a collection of resource names, never null but possibly empty */ public Collection<String> getResourceNames(boolean framework, ResourceType type) { Map<String, Map<String, ResourceValue>> map = framework ? mConfiguredFrameworkRes : mConfiguredProjectRes; Map<String, ResourceValue> animations = map.get(type.getName()); if (animations != null) { return animations.keySet(); } else { return Collections.emptyList(); } } }
true
true
public void createPartControl(Composite parent) { Display d = parent.getDisplay(); GridLayout gl = new GridLayout(1, false); parent.setLayout(gl); gl.marginHeight = gl.marginWidth = 0; // create the top part for the configuration control CustomButton[][] customButtons = new CustomButton[][] { new CustomButton[] { mZoomRealSizeButton = new CustomButton( "*", null, //image "Emulate real size", true /*isToggle*/, false /*defaultValue*/ ) { @Override public void onSelected(boolean newState) { if (rescaleToReal(newState)) { mZoomOutButton.setEnabled(!newState); mZoomResetButton.setEnabled(!newState); mZoomInButton.setEnabled(!newState); } else { mZoomRealSizeButton.setSelection(!newState); } } }, mZoomOutButton = new CustomButton( "-", null, //image "Canvas zoom out." ) { @Override public void onSelected(boolean newState) { rescale(-1); } }, mZoomResetButton = new CustomButton( "100%", null, //image "Reset Canvas to 100%" ) { @Override public void onSelected(boolean newState) { resetScale(); } }, mZoomInButton = new CustomButton( "+", null, //image "Canvas zoom in." ) { @Override public void onSelected(boolean newState) { rescale(+1); } }, }, new CustomButton[] { new CustomButton( null, //text IconFactory.getInstance().getIcon("explode"), //$NON-NLS-1$ "Displays extra margins in the layout.", true /*toggle*/, false /*defaultValue*/ ) { @Override public void onSelected(boolean newState) { mUseExplodeMode = newState; recomputeLayout(); } }, new CustomButton( null, //text IconFactory.getInstance().getIcon("outline"), //$NON-NLS-1$ "Shows the outline of all views in the layout.", true /*toggle*/, false /*defaultValue*/ ) { @Override public void onSelected(boolean newState) { mCanvasViewer.getCanvas().setShowOutline(newState); } }, mClippingButton = new CustomButton( null, //text IconFactory.getInstance().getIcon("clipping"), //$NON-NLS-1$ "Toggles screen clipping on/off", true /*toggle*/, true /*defaultValue*/ ) { @Override public void onSelected(boolean newState) { recomputeLayout(); } } } }; mConfigListener = new ConfigListener(); // Check whether somebody has requested an initial state for the newly opened file. // The initial state is a serialized version of the state compatible with // {@link ConfigurationComposite#CONFIG_STATE}. String initialState = null; IFile file = mEditedFile; if (file == null) { IEditorInput input = mLayoutEditor.getEditorInput(); if (input instanceof FileEditorInput) { file = ((FileEditorInput) input).getFile(); } } if (file != null) { try { initialState = (String) file.getSessionProperty(NAME_INITIAL_STATE); if (initialState != null) { // Only use once file.setSessionProperty(NAME_INITIAL_STATE, null); } } catch (CoreException e) { AdtPlugin.log(e, "Can't read session property %1$s", NAME_INITIAL_STATE); } } mConfigComposite = new ConfigurationComposite(mConfigListener, customButtons, parent, SWT.BORDER, initialState); mSashPalette = new SashForm(parent, SWT.HORIZONTAL); mSashPalette.setLayoutData(new GridData(GridData.FILL_BOTH)); DecorComposite paleteDecor = new DecorComposite(mSashPalette, SWT.BORDER); paleteDecor.setContent(new PaletteControl.PaletteDecor(this)); mPalette = (PaletteControl) paleteDecor.getContentControl(); mSashError = new SashForm(mSashPalette, SWT.VERTICAL | SWT.BORDER); mSashError.setLayoutData(new GridData(GridData.FILL_BOTH)); mCanvasViewer = new LayoutCanvasViewer(mLayoutEditor, mRulesEngine, mSashError, SWT.NONE); mErrorLabel = new StyledText(mSashError, SWT.READ_ONLY); mErrorLabel.setEditable(false); mErrorLabel.setBackground(d.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); mErrorLabel.setForeground(d.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); mErrorLabel.addMouseListener(new ErrorLabelListener()); mSashPalette.setWeights(new int[] { 20, 80 }); mSashError.setWeights(new int[] { 80, 20 }); mSashError.setMaximizedControl(mCanvasViewer.getControl()); // Initialize the state reloadPalette(); getSite().setSelectionProvider(mCanvasViewer); getSite().getPage().addSelectionListener(this); }
public void createPartControl(Composite parent) { Display d = parent.getDisplay(); GridLayout gl = new GridLayout(1, false); parent.setLayout(gl); gl.marginHeight = gl.marginWidth = 0; // create the top part for the configuration control CustomButton[][] customButtons = new CustomButton[][] { new CustomButton[] { mZoomRealSizeButton = new CustomButton( "*", null, //image "Emulate real size", true /*isToggle*/, false /*defaultValue*/ ) { @Override public void onSelected(boolean newState) { if (rescaleToReal(newState)) { mZoomOutButton.setEnabled(!newState); mZoomResetButton.setEnabled(!newState); mZoomInButton.setEnabled(!newState); } else { mZoomRealSizeButton.setSelection(!newState); } } }, mZoomOutButton = new CustomButton( "-", null, //image "Canvas zoom out." ) { @Override public void onSelected(boolean newState) { rescale(-1); } }, mZoomResetButton = new CustomButton( "100%", null, //image "Reset Canvas to 100%" ) { @Override public void onSelected(boolean newState) { resetScale(); } }, mZoomInButton = new CustomButton( "+", null, //image "Canvas zoom in." ) { @Override public void onSelected(boolean newState) { rescale(+1); } }, }, new CustomButton[] { new CustomButton( null, //text IconFactory.getInstance().getIcon("explode"), //$NON-NLS-1$ "Displays extra margins in the layout.", true /*toggle*/, false /*defaultValue*/ ) { @Override public void onSelected(boolean newState) { mUseExplodeMode = newState; recomputeLayout(); } }, new CustomButton( null, //text IconFactory.getInstance().getIcon("outline"), //$NON-NLS-1$ "Shows the outline of all views in the layout.", true /*toggle*/, false /*defaultValue*/ ) { @Override public void onSelected(boolean newState) { mCanvasViewer.getCanvas().setShowOutline(newState); } }, mClippingButton = new CustomButton( null, //text IconFactory.getInstance().getIcon("clipping"), //$NON-NLS-1$ "Toggles screen clipping on/off", true /*toggle*/, true /*defaultValue*/ ) { @Override public void onSelected(boolean newState) { recomputeLayout(); } } } }; mConfigListener = new ConfigListener(); // Check whether somebody has requested an initial state for the newly opened file. // The initial state is a serialized version of the state compatible with // {@link ConfigurationComposite#CONFIG_STATE}. String initialState = null; IFile file = mEditedFile; if (file == null) { IEditorInput input = mLayoutEditor.getEditorInput(); if (input instanceof FileEditorInput) { file = ((FileEditorInput) input).getFile(); } } if (file != null) { try { initialState = (String) file.getSessionProperty(NAME_INITIAL_STATE); if (initialState != null) { // Only use once file.setSessionProperty(NAME_INITIAL_STATE, null); } } catch (CoreException e) { AdtPlugin.log(e, "Can't read session property %1$s", NAME_INITIAL_STATE); } } mConfigComposite = new ConfigurationComposite(mConfigListener, customButtons, parent, SWT.BORDER, initialState); mSashPalette = new SashForm(parent, SWT.HORIZONTAL); mSashPalette.setLayoutData(new GridData(GridData.FILL_BOTH)); DecorComposite paleteDecor = new DecorComposite(mSashPalette, SWT.BORDER); paleteDecor.setContent(new PaletteControl.PaletteDecor(this)); mPalette = (PaletteControl) paleteDecor.getContentControl(); mSashError = new SashForm(mSashPalette, SWT.VERTICAL | SWT.BORDER); mSashError.setLayoutData(new GridData(GridData.FILL_BOTH)); mCanvasViewer = new LayoutCanvasViewer(mLayoutEditor, mRulesEngine, mSashError, SWT.NONE); mErrorLabel = new StyledText(mSashError, SWT.READ_ONLY | SWT.WRAP); mErrorLabel.setEditable(false); mErrorLabel.setBackground(d.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); mErrorLabel.setForeground(d.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); mErrorLabel.addMouseListener(new ErrorLabelListener()); mSashPalette.setWeights(new int[] { 20, 80 }); mSashError.setWeights(new int[] { 80, 20 }); mSashError.setMaximizedControl(mCanvasViewer.getControl()); // Initialize the state reloadPalette(); getSite().setSelectionProvider(mCanvasViewer); getSite().getPage().addSelectionListener(this); }
diff --git a/org.eclipse.text/src/org/eclipse/jface/text/SequentialRewriteTextStore.java b/org.eclipse.text/src/org/eclipse/jface/text/SequentialRewriteTextStore.java index 1848f1a23..3e3ffabc5 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/SequentialRewriteTextStore.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/SequentialRewriteTextStore.java @@ -1,273 +1,273 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.text; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * A text store that optimizes a given source text store for sequential rewriting. * While rewritten it keeps a list of replace command that serve as patches for * the source store. Only on request, the source store is indeed manipulated * by applying the patch commands to the source text store. * * @since 2.0 */ public class SequentialRewriteTextStore implements ITextStore { /** * A buffered replace command. */ private static class Replace { public int newOffset; public final int offset; public final int length; public final String text; public Replace(int offset, int newOffset, int length, String text) { this.newOffset= newOffset; this.offset= offset; this.length= length; this.text= text; } } /** The list of buffered replacements. */ private List fReplaceList; /** The source text store */ private ITextStore fSource; /** A flag to enforce sequential access. */ private static final boolean ASSERT_SEQUENTIALITY= false; /** * Creates a new sequential rewrite store for the given source store. * * @param source the source text store */ public SequentialRewriteTextStore(ITextStore source) { fReplaceList= new LinkedList(); fSource= source; } /** * Returns the source store of this rewrite store. * * @return the source store of this rewrite store */ public ITextStore getSourceStore() { commit(); return fSource; } /* * @see ITextStore#replace(int, int, String) */ public void replace(int offset, int length, String text) { if (fReplaceList.size() == 0) { fReplaceList.add(new Replace(offset, offset, length, text)); } else { Replace firstReplace= (Replace) fReplaceList.get(0); Replace lastReplace= (Replace) fReplaceList.get(fReplaceList.size() - 1); // backward if (offset + length <= firstReplace.newOffset) { int delta= text.length() - length; if (delta != 0) { for (Iterator i= fReplaceList.iterator(); i.hasNext(); ) { Replace replace= (Replace) i.next(); replace.newOffset += delta; } } fReplaceList.add(0, new Replace(offset, offset, length, text)); // forward } else if (offset >= lastReplace.newOffset + lastReplace.text.length()) { int delta= getDelta(lastReplace); fReplaceList.add(new Replace(offset - delta, offset, length, text)); } else if (ASSERT_SEQUENTIALITY) { throw new IllegalArgumentException(); } else { commit(); fSource.replace(offset, length, text); } } } /* * @see ITextStore#set(String) */ public void set(String text) { fSource.set(text); fReplaceList.clear(); } /* * @see ITextStore#get(int, int) */ public String get(int offset, int length) { if (fReplaceList.size() == 0) { return fSource.get(offset, length); } else { Replace firstReplace= (Replace) fReplaceList.get(0); Replace lastReplace= (Replace) fReplaceList.get(fReplaceList.size() - 1); // before if (offset + length <= firstReplace.newOffset) { return fSource.get(offset, length); // after } else if (offset >= lastReplace.newOffset + lastReplace.text.length()) { int delta= getDelta(lastReplace); return fSource.get(offset - delta, length); } else if (ASSERT_SEQUENTIALITY) { throw new IllegalArgumentException(); } else { int delta= 0; for (Iterator i= fReplaceList.iterator(); i.hasNext(); ) { Replace replace= (Replace) i.next(); if (offset + length < replace.newOffset) { return fSource.get(offset - delta, length); } else if (offset >= replace.newOffset && offset + length <= replace.newOffset + replace.text.length()) { - return replace.text.substring(offset - replace.newOffset, length); + return replace.text.substring(offset - replace.newOffset, offset - replace.newOffset + length); } else if (offset >= replace.newOffset + replace.text.length()) { delta= getDelta(replace); continue; } else { commit(); return fSource.get(offset, length); } } return fSource.get(offset - delta, length); } } } /** * Returns the difference between the offset in the source store and the "same" offset in the * rewrite store after the replace operation. * * @param replace the replace command */ private static final int getDelta(Replace replace) { return replace.newOffset - replace.offset + replace.text.length() - replace.length; } /* * @see ITextStore#get(int) */ public char get(int offset) { if (fReplaceList.size() == 0) { return fSource.get(offset); } else { Replace firstReplace= (Replace) fReplaceList.get(0); Replace lastReplace= (Replace) fReplaceList.get(fReplaceList.size() - 1); // before if (offset < firstReplace.newOffset) { return fSource.get(offset); // after } else if (offset >= lastReplace.newOffset + lastReplace.text.length()) { int delta= getDelta(lastReplace); return fSource.get(offset - delta); } else if (ASSERT_SEQUENTIALITY) { throw new IllegalArgumentException(); } else { int delta= 0; for (Iterator i= fReplaceList.iterator(); i.hasNext(); ) { Replace replace= (Replace) i.next(); if (offset < replace.newOffset) return fSource.get(offset - delta); else if (offset < replace.newOffset + replace.text.length()) return replace.text.charAt(offset - replace.newOffset); delta= getDelta(replace); } return fSource.get(offset - delta); } } } /* * @see ITextStore#getLength() */ public int getLength() { if (fReplaceList.size() == 0) { return fSource.getLength(); } else { Replace lastReplace= (Replace) fReplaceList.get(fReplaceList.size() - 1); return fSource.getLength() + getDelta(lastReplace); } } /** * Disposes this rewrite store. */ public void dispose() { fReplaceList= null; fSource= null; } /** * Commits all buffered replace commands. */ private void commit() { if (fReplaceList.size() == 0) return; StringBuffer buffer= new StringBuffer(); int delta= 0; for (Iterator i= fReplaceList.iterator(); i.hasNext(); ) { Replace replace= (Replace) i.next(); int offset= buffer.length() - delta; buffer.append(fSource.get(offset, replace.offset - offset)); buffer.append(replace.text); delta= getDelta(replace); } int offset= buffer.length() - delta; buffer.append(fSource.get(offset, fSource.getLength() - offset)); fSource.set(buffer.toString()); fReplaceList.clear(); } }
true
true
public String get(int offset, int length) { if (fReplaceList.size() == 0) { return fSource.get(offset, length); } else { Replace firstReplace= (Replace) fReplaceList.get(0); Replace lastReplace= (Replace) fReplaceList.get(fReplaceList.size() - 1); // before if (offset + length <= firstReplace.newOffset) { return fSource.get(offset, length); // after } else if (offset >= lastReplace.newOffset + lastReplace.text.length()) { int delta= getDelta(lastReplace); return fSource.get(offset - delta, length); } else if (ASSERT_SEQUENTIALITY) { throw new IllegalArgumentException(); } else { int delta= 0; for (Iterator i= fReplaceList.iterator(); i.hasNext(); ) { Replace replace= (Replace) i.next(); if (offset + length < replace.newOffset) { return fSource.get(offset - delta, length); } else if (offset >= replace.newOffset && offset + length <= replace.newOffset + replace.text.length()) { return replace.text.substring(offset - replace.newOffset, length); } else if (offset >= replace.newOffset + replace.text.length()) { delta= getDelta(replace); continue; } else { commit(); return fSource.get(offset, length); } } return fSource.get(offset - delta, length); } } }
public String get(int offset, int length) { if (fReplaceList.size() == 0) { return fSource.get(offset, length); } else { Replace firstReplace= (Replace) fReplaceList.get(0); Replace lastReplace= (Replace) fReplaceList.get(fReplaceList.size() - 1); // before if (offset + length <= firstReplace.newOffset) { return fSource.get(offset, length); // after } else if (offset >= lastReplace.newOffset + lastReplace.text.length()) { int delta= getDelta(lastReplace); return fSource.get(offset - delta, length); } else if (ASSERT_SEQUENTIALITY) { throw new IllegalArgumentException(); } else { int delta= 0; for (Iterator i= fReplaceList.iterator(); i.hasNext(); ) { Replace replace= (Replace) i.next(); if (offset + length < replace.newOffset) { return fSource.get(offset - delta, length); } else if (offset >= replace.newOffset && offset + length <= replace.newOffset + replace.text.length()) { return replace.text.substring(offset - replace.newOffset, offset - replace.newOffset + length); } else if (offset >= replace.newOffset + replace.text.length()) { delta= getDelta(replace); continue; } else { commit(); return fSource.get(offset, length); } } return fSource.get(offset - delta, length); } } }
diff --git a/src/gtpdummy/Main.java b/src/gtpdummy/Main.java index 9882cf94..33d6295e 100644 --- a/src/gtpdummy/Main.java +++ b/src/gtpdummy/Main.java @@ -1,66 +1,66 @@ //---------------------------------------------------------------------------- // $Id$ // $Source$ //---------------------------------------------------------------------------- package gtpdummy; import java.io.*; import go.*; import gtp.*; import utils.Options; import utils.StringUtils; import version.*; //---------------------------------------------------------------------------- public class Main { public static void main(String[] args) { try { String options[] = { "config:", "help", "log:", "version" }; - Options opt = Options.parse(options, args); + Options opt = Options.parse(args, options); if (opt.isSet("help")) { String helpText = "Usage: java -jar gtpdummy.jar [options]\n" + "\n" + "-config config file\n" + "-help display this help and exit\n" + "-log file log GTP stream to file\n" + "-version print version and exit\n"; System.out.print(helpText); return; } if (opt.isSet("version")) { System.out.println("GtpDummy " + Version.get()); return; } PrintStream log = null; if (opt.isSet("log")) { File file = new File(opt.getString("log")); log = new PrintStream(new FileOutputStream(file)); } GtpDummy gtpDummy = new GtpDummy(System.in, System.out, log); gtpDummy.mainLoop(); if (log != null) log.close(); } catch (Throwable t) { StringUtils.printException(t); System.exit(-1); } } } //----------------------------------------------------------------------------
true
true
public static void main(String[] args) { try { String options[] = { "config:", "help", "log:", "version" }; Options opt = Options.parse(options, args); if (opt.isSet("help")) { String helpText = "Usage: java -jar gtpdummy.jar [options]\n" + "\n" + "-config config file\n" + "-help display this help and exit\n" + "-log file log GTP stream to file\n" + "-version print version and exit\n"; System.out.print(helpText); return; } if (opt.isSet("version")) { System.out.println("GtpDummy " + Version.get()); return; } PrintStream log = null; if (opt.isSet("log")) { File file = new File(opt.getString("log")); log = new PrintStream(new FileOutputStream(file)); } GtpDummy gtpDummy = new GtpDummy(System.in, System.out, log); gtpDummy.mainLoop(); if (log != null) log.close(); } catch (Throwable t) { StringUtils.printException(t); System.exit(-1); } }
public static void main(String[] args) { try { String options[] = { "config:", "help", "log:", "version" }; Options opt = Options.parse(args, options); if (opt.isSet("help")) { String helpText = "Usage: java -jar gtpdummy.jar [options]\n" + "\n" + "-config config file\n" + "-help display this help and exit\n" + "-log file log GTP stream to file\n" + "-version print version and exit\n"; System.out.print(helpText); return; } if (opt.isSet("version")) { System.out.println("GtpDummy " + Version.get()); return; } PrintStream log = null; if (opt.isSet("log")) { File file = new File(opt.getString("log")); log = new PrintStream(new FileOutputStream(file)); } GtpDummy gtpDummy = new GtpDummy(System.in, System.out, log); gtpDummy.mainLoop(); if (log != null) log.close(); } catch (Throwable t) { StringUtils.printException(t); System.exit(-1); } }
diff --git a/src/com/android/contacts/ContactsListActivity.java b/src/com/android/contacts/ContactsListActivity.java index aeb401464..4169e3752 100644 --- a/src/com/android/contacts/ContactsListActivity.java +++ b/src/com/android/contacts/ContactsListActivity.java @@ -1,3566 +1,3568 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts; import com.android.contacts.TextHighlightingAnimation.TextWithHighlighting; import com.android.contacts.model.ContactsSource; import com.android.contacts.model.Sources; import com.android.contacts.ui.ContactsPreferences; import com.android.contacts.ui.ContactsPreferencesActivity; import com.android.contacts.ui.ContactsPreferencesActivity.Prefs; import com.android.contacts.util.AccountSelectionUtil; import com.android.contacts.util.Constants; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.app.SearchManager; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.IContentService; import android.content.Intent; import android.content.SharedPreferences; import android.content.UriMatcher; import android.content.res.ColorStateList; import android.content.res.Resources; import android.database.CharArrayBuffer; import android.database.ContentObserver; import android.database.Cursor; import android.database.MatrixCursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.os.RemoteException; import android.preference.PreferenceManager; import android.provider.ContactsContract; import android.provider.Settings; import android.provider.Contacts.ContactMethods; import android.provider.Contacts.People; import android.provider.Contacts.PeopleColumns; import android.provider.Contacts.Phones; import android.provider.ContactsContract.ContactCounts; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Intents; import android.provider.ContactsContract.ProviderStatus; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.SearchSnippetColumns; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Photo; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.Contacts.AggregationSuggestions; import android.provider.ContactsContract.Intents.Insert; import android.provider.ContactsContract.Intents.UI; import android.telephony.TelephonyManager; import android.text.Editable; import android.text.Html; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.ContextMenu; import android.view.ContextThemeWrapper; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnTouchListener; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.Filter; import android.widget.ImageView; import android.widget.ListView; import android.widget.QuickContactBadge; import android.widget.SectionIndexer; import android.widget.TextView; import android.widget.Toast; import android.widget.AbsListView.OnScrollListener; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Displays a list of contacts. Usually is embedded into the ContactsActivity. */ @SuppressWarnings("deprecation") public class ContactsListActivity extends ListActivity implements View.OnCreateContextMenuListener, View.OnClickListener, View.OnKeyListener, TextWatcher, TextView.OnEditorActionListener, OnFocusChangeListener, OnTouchListener { public static class JoinContactActivity extends ContactsListActivity { } public static class ContactsSearchActivity extends ContactsListActivity { } private static final String TAG = "ContactsListActivity"; private static final boolean ENABLE_ACTION_ICON_OVERLAYS = true; private static final String LIST_STATE_KEY = "liststate"; private static final String SHORTCUT_ACTION_KEY = "shortcutAction"; static final int MENU_ITEM_VIEW_CONTACT = 1; static final int MENU_ITEM_CALL = 2; static final int MENU_ITEM_EDIT_BEFORE_CALL = 3; static final int MENU_ITEM_SEND_SMS = 4; static final int MENU_ITEM_SEND_IM = 5; static final int MENU_ITEM_EDIT = 6; static final int MENU_ITEM_DELETE = 7; static final int MENU_ITEM_TOGGLE_STAR = 8; private static final int SUBACTIVITY_NEW_CONTACT = 1; private static final int SUBACTIVITY_VIEW_CONTACT = 2; private static final int SUBACTIVITY_DISPLAY_GROUP = 3; private static final int SUBACTIVITY_SEARCH = 4; private static final int SUBACTIVITY_FILTER = 5; private static final int TEXT_HIGHLIGHTING_ANIMATION_DURATION = 350; /** * The action for the join contact activity. * <p> * Input: extra field {@link #EXTRA_AGGREGATE_ID} is the aggregate ID. * * TODO: move to {@link ContactsContract}. */ public static final String JOIN_AGGREGATE = "com.android.contacts.action.JOIN_AGGREGATE"; /** * Used with {@link #JOIN_AGGREGATE} to give it the target for aggregation. * <p> * Type: LONG */ public static final String EXTRA_AGGREGATE_ID = "com.android.contacts.action.AGGREGATE_ID"; /** * Used with {@link #JOIN_AGGREGATE} to give it the name of the aggregation target. * <p> * Type: STRING */ @Deprecated public static final String EXTRA_AGGREGATE_NAME = "com.android.contacts.action.AGGREGATE_NAME"; public static final String AUTHORITIES_FILTER_KEY = "authorities"; private static final Uri CONTACTS_CONTENT_URI_WITH_LETTER_COUNTS = buildSectionIndexerUri(Contacts.CONTENT_URI); /** Mask for picker mode */ static final int MODE_MASK_PICKER = 0x80000000; /** Mask for no presence mode */ static final int MODE_MASK_NO_PRESENCE = 0x40000000; /** Mask for enabling list filtering */ static final int MODE_MASK_NO_FILTER = 0x20000000; /** Mask for having a "create new contact" header in the list */ static final int MODE_MASK_CREATE_NEW = 0x10000000; /** Mask for showing photos in the list */ static final int MODE_MASK_SHOW_PHOTOS = 0x08000000; /** Mask for hiding additional information e.g. primary phone number in the list */ static final int MODE_MASK_NO_DATA = 0x04000000; /** Mask for showing a call button in the list */ static final int MODE_MASK_SHOW_CALL_BUTTON = 0x02000000; /** Mask to disable quickcontact (images will show as normal images) */ static final int MODE_MASK_DISABLE_QUIKCCONTACT = 0x01000000; /** Mask to show the total number of contacts at the top */ static final int MODE_MASK_SHOW_NUMBER_OF_CONTACTS = 0x00800000; /** Unknown mode */ static final int MODE_UNKNOWN = 0; /** Default mode */ static final int MODE_DEFAULT = 4 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Custom mode */ static final int MODE_CUSTOM = 8; /** Show all starred contacts */ static final int MODE_STARRED = 20 | MODE_MASK_SHOW_PHOTOS; /** Show frequently contacted contacts */ static final int MODE_FREQUENT = 30 | MODE_MASK_SHOW_PHOTOS; /** Show starred and the frequent */ static final int MODE_STREQUENT = 35 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_SHOW_CALL_BUTTON; /** Show all contacts and pick them when clicking */ static final int MODE_PICK_CONTACT = 40 | MODE_MASK_PICKER | MODE_MASK_SHOW_PHOTOS | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all contacts as well as the option to create a new one */ static final int MODE_PICK_OR_CREATE_CONTACT = 42 | MODE_MASK_PICKER | MODE_MASK_CREATE_NEW | MODE_MASK_SHOW_PHOTOS | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all people through the legacy provider and pick them when clicking */ static final int MODE_LEGACY_PICK_PERSON = 43 | MODE_MASK_PICKER | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all people through the legacy provider as well as the option to create a new one */ static final int MODE_LEGACY_PICK_OR_CREATE_PERSON = 44 | MODE_MASK_PICKER | MODE_MASK_CREATE_NEW | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all contacts and pick them when clicking, and allow creating a new contact */ static final int MODE_INSERT_OR_EDIT_CONTACT = 45 | MODE_MASK_PICKER | MODE_MASK_CREATE_NEW | MODE_MASK_SHOW_PHOTOS | MODE_MASK_DISABLE_QUIKCCONTACT; /** Show all phone numbers and pick them when clicking */ static final int MODE_PICK_PHONE = 50 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE; /** Show all phone numbers through the legacy provider and pick them when clicking */ static final int MODE_LEGACY_PICK_PHONE = 51 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE | MODE_MASK_NO_FILTER; /** Show all postal addresses and pick them when clicking */ static final int MODE_PICK_POSTAL = 55 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE | MODE_MASK_NO_FILTER; /** Show all postal addresses and pick them when clicking */ static final int MODE_LEGACY_PICK_POSTAL = 56 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE | MODE_MASK_NO_FILTER; static final int MODE_GROUP = 57 | MODE_MASK_SHOW_PHOTOS; /** Run a search query */ static final int MODE_QUERY = 60 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_NO_FILTER | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Run a search query in PICK mode, but that still launches to VIEW */ static final int MODE_QUERY_PICK_TO_VIEW = 65 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_PICKER | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Show join suggestions followed by an A-Z list */ static final int MODE_JOIN_CONTACT = 70 | MODE_MASK_PICKER | MODE_MASK_NO_PRESENCE | MODE_MASK_NO_DATA | MODE_MASK_SHOW_PHOTOS | MODE_MASK_DISABLE_QUIKCCONTACT; /** Run a search query in a PICK mode */ static final int MODE_QUERY_PICK = 75 | MODE_MASK_SHOW_PHOTOS | MODE_MASK_NO_FILTER | MODE_MASK_PICKER | MODE_MASK_DISABLE_QUIKCCONTACT | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Run a search query in a PICK_PHONE mode */ static final int MODE_QUERY_PICK_PHONE = 80 | MODE_MASK_NO_FILTER | MODE_MASK_PICKER | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** Run a search query in PICK mode, but that still launches to EDIT */ static final int MODE_QUERY_PICK_TO_EDIT = 85 | MODE_MASK_NO_FILTER | MODE_MASK_SHOW_PHOTOS | MODE_MASK_PICKER | MODE_MASK_SHOW_NUMBER_OF_CONTACTS; /** * An action used to do perform search while in a contact picker. It is initiated * by the ContactListActivity itself. */ private static final String ACTION_SEARCH_INTERNAL = "com.android.contacts.INTERNAL_SEARCH"; /** Maximum number of suggestions shown for joining aggregates */ static final int MAX_SUGGESTIONS = 4; static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] { Contacts._ID, // 0 Contacts.DISPLAY_NAME_PRIMARY, // 1 Contacts.DISPLAY_NAME_ALTERNATIVE, // 2 Contacts.SORT_KEY_PRIMARY, // 3 Contacts.STARRED, // 4 Contacts.TIMES_CONTACTED, // 5 Contacts.CONTACT_PRESENCE, // 6 Contacts.PHOTO_ID, // 7 Contacts.LOOKUP_KEY, // 8 Contacts.PHONETIC_NAME, // 9 Contacts.HAS_PHONE_NUMBER, // 10 }; static final String[] CONTACTS_SUMMARY_PROJECTION_FROM_EMAIL = new String[] { Contacts._ID, // 0 Contacts.DISPLAY_NAME_PRIMARY, // 1 Contacts.DISPLAY_NAME_ALTERNATIVE, // 2 Contacts.SORT_KEY_PRIMARY, // 3 Contacts.STARRED, // 4 Contacts.TIMES_CONTACTED, // 5 Contacts.CONTACT_PRESENCE, // 6 Contacts.PHOTO_ID, // 7 Contacts.LOOKUP_KEY, // 8 Contacts.PHONETIC_NAME, // 9 // email lookup doesn't included HAS_PHONE_NUMBER in projection }; static final String[] CONTACTS_SUMMARY_FILTER_PROJECTION = new String[] { Contacts._ID, // 0 Contacts.DISPLAY_NAME_PRIMARY, // 1 Contacts.DISPLAY_NAME_ALTERNATIVE, // 2 Contacts.SORT_KEY_PRIMARY, // 3 Contacts.STARRED, // 4 Contacts.TIMES_CONTACTED, // 5 Contacts.CONTACT_PRESENCE, // 6 Contacts.PHOTO_ID, // 7 Contacts.LOOKUP_KEY, // 8 Contacts.PHONETIC_NAME, // 9 Contacts.HAS_PHONE_NUMBER, // 10 SearchSnippetColumns.SNIPPET_MIMETYPE, // 11 SearchSnippetColumns.SNIPPET_DATA1, // 12 SearchSnippetColumns.SNIPPET_DATA4, // 13 }; static final String[] LEGACY_PEOPLE_PROJECTION = new String[] { People._ID, // 0 People.DISPLAY_NAME, // 1 People.DISPLAY_NAME, // 2 People.DISPLAY_NAME, // 3 People.STARRED, // 4 PeopleColumns.TIMES_CONTACTED, // 5 People.PRESENCE_STATUS, // 6 }; static final int SUMMARY_ID_COLUMN_INDEX = 0; static final int SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX = 1; static final int SUMMARY_DISPLAY_NAME_ALTERNATIVE_COLUMN_INDEX = 2; static final int SUMMARY_SORT_KEY_PRIMARY_COLUMN_INDEX = 3; static final int SUMMARY_STARRED_COLUMN_INDEX = 4; static final int SUMMARY_TIMES_CONTACTED_COLUMN_INDEX = 5; static final int SUMMARY_PRESENCE_STATUS_COLUMN_INDEX = 6; static final int SUMMARY_PHOTO_ID_COLUMN_INDEX = 7; static final int SUMMARY_LOOKUP_KEY_COLUMN_INDEX = 8; static final int SUMMARY_PHONETIC_NAME_COLUMN_INDEX = 9; static final int SUMMARY_HAS_PHONE_COLUMN_INDEX = 10; static final int SUMMARY_SNIPPET_MIMETYPE_COLUMN_INDEX = 11; static final int SUMMARY_SNIPPET_DATA1_COLUMN_INDEX = 12; static final int SUMMARY_SNIPPET_DATA4_COLUMN_INDEX = 13; static final String[] PHONES_PROJECTION = new String[] { Phone._ID, //0 Phone.TYPE, //1 Phone.LABEL, //2 Phone.NUMBER, //3 Phone.DISPLAY_NAME, // 4 Phone.CONTACT_ID, // 5 }; static final String[] LEGACY_PHONES_PROJECTION = new String[] { Phones._ID, //0 Phones.TYPE, //1 Phones.LABEL, //2 Phones.NUMBER, //3 People.DISPLAY_NAME, // 4 }; static final int PHONE_ID_COLUMN_INDEX = 0; static final int PHONE_TYPE_COLUMN_INDEX = 1; static final int PHONE_LABEL_COLUMN_INDEX = 2; static final int PHONE_NUMBER_COLUMN_INDEX = 3; static final int PHONE_DISPLAY_NAME_COLUMN_INDEX = 4; static final int PHONE_CONTACT_ID_COLUMN_INDEX = 5; static final String[] POSTALS_PROJECTION = new String[] { StructuredPostal._ID, //0 StructuredPostal.TYPE, //1 StructuredPostal.LABEL, //2 StructuredPostal.DATA, //3 StructuredPostal.DISPLAY_NAME, // 4 }; static final String[] LEGACY_POSTALS_PROJECTION = new String[] { ContactMethods._ID, //0 ContactMethods.TYPE, //1 ContactMethods.LABEL, //2 ContactMethods.DATA, //3 People.DISPLAY_NAME, // 4 }; static final String[] RAW_CONTACTS_PROJECTION = new String[] { RawContacts._ID, //0 RawContacts.CONTACT_ID, //1 RawContacts.ACCOUNT_TYPE, //2 }; static final int POSTAL_ID_COLUMN_INDEX = 0; static final int POSTAL_TYPE_COLUMN_INDEX = 1; static final int POSTAL_LABEL_COLUMN_INDEX = 2; static final int POSTAL_ADDRESS_COLUMN_INDEX = 3; static final int POSTAL_DISPLAY_NAME_COLUMN_INDEX = 4; private static final int QUERY_TOKEN = 42; static final String KEY_PICKER_MODE = "picker_mode"; private ContactItemListAdapter mAdapter; int mMode = MODE_DEFAULT; private QueryHandler mQueryHandler; private boolean mJustCreated; private boolean mSyncEnabled; Uri mSelectedContactUri; // private boolean mDisplayAll; private boolean mDisplayOnlyPhones; private Uri mGroupUri; private long mQueryAggregateId; private ArrayList<Long> mWritableRawContactIds = new ArrayList<Long>(); private int mWritableSourcesCnt; private int mReadOnlySourcesCnt; /** * Used to keep track of the scroll state of the list. */ private Parcelable mListState = null; private String mShortcutAction; /** * Internal query type when in mode {@link #MODE_QUERY_PICK_TO_VIEW}. */ private int mQueryMode = QUERY_MODE_NONE; private static final int QUERY_MODE_NONE = -1; private static final int QUERY_MODE_MAILTO = 1; private static final int QUERY_MODE_TEL = 2; private int mProviderStatus = ProviderStatus.STATUS_NORMAL; private boolean mSearchMode; private boolean mSearchResultsMode; private boolean mShowNumberOfContacts; private boolean mShowSearchSnippets; private boolean mSearchInitiated; private String mInitialFilter; private static final String CLAUSE_ONLY_VISIBLE = Contacts.IN_VISIBLE_GROUP + "=1"; private static final String CLAUSE_ONLY_PHONES = Contacts.HAS_PHONE_NUMBER + "=1"; /** * In the {@link #MODE_JOIN_CONTACT} determines whether we display a list item with the label * "Show all contacts" or actually show all contacts */ private boolean mJoinModeShowAllContacts; /** * The ID of the special item described above. */ private static final long JOIN_MODE_SHOW_ALL_CONTACTS_ID = -2; // Uri matcher for contact id private static final int CONTACTS_ID = 1001; private static final UriMatcher sContactsIdMatcher; private ContactPhotoLoader mPhotoLoader; final String[] sLookupProjection = new String[] { Contacts.LOOKUP_KEY }; static { sContactsIdMatcher = new UriMatcher(UriMatcher.NO_MATCH); sContactsIdMatcher.addURI(ContactsContract.AUTHORITY, "contacts/#", CONTACTS_ID); } private class DeleteClickListener implements DialogInterface.OnClickListener { public void onClick(DialogInterface dialog, int which) { if (mSelectedContactUri != null) { getContentResolver().delete(mSelectedContactUri, null, null); } } } /** * A {@link TextHighlightingAnimation} that redraws just the contact display name in a * list item. */ private static class NameHighlightingAnimation extends TextHighlightingAnimation { private final ListView mListView; private NameHighlightingAnimation(ListView listView, int duration) { super(duration); this.mListView = listView; } /** * Redraws all visible items of the list corresponding to contacts */ @Override protected void invalidate() { int childCount = mListView.getChildCount(); for (int i = 0; i < childCount; i++) { View itemView = mListView.getChildAt(i); if (itemView instanceof ContactListItemView) { final ContactListItemView view = (ContactListItemView)itemView; view.getNameTextView().invalidate(); } } } @Override protected void onAnimationStarted() { mListView.setScrollingCacheEnabled(false); } @Override protected void onAnimationEnded() { mListView.setScrollingCacheEnabled(true); } } // The size of a home screen shortcut icon. private int mIconSize; private ContactsPreferences mContactsPrefs; private int mDisplayOrder; private int mSortOrder; private boolean mHighlightWhenScrolling; private TextHighlightingAnimation mHighlightingAnimation; private SearchEditText mSearchEditText; /** * An approximation of the background color of the pinned header. This color * is used when the pinned header is being pushed up. At that point the header * "fades away". Rather than computing a faded bitmap based on the 9-patch * normally used for the background, we will use a solid color, which will * provide better performance and reduced complexity. */ private int mPinnedHeaderBackgroundColor; private ContentObserver mProviderStatusObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { checkProviderState(true); } }; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); mIconSize = getResources().getDimensionPixelSize(android.R.dimen.app_icon_size); mContactsPrefs = new ContactsPreferences(this); mPhotoLoader = new ContactPhotoLoader(this, R.drawable.ic_contact_list_picture); // Resolve the intent final Intent intent = getIntent(); // Allow the title to be set to a custom String using an extra on the intent String title = intent.getStringExtra(UI.TITLE_EXTRA_KEY); if (title != null) { setTitle(title); } String action = intent.getAction(); String component = intent.getComponent().getClassName(); // When we get a FILTER_CONTACTS_ACTION, it represents search in the context // of some other action. Let's retrieve the original action to provide proper // context for the search queries. if (UI.FILTER_CONTACTS_ACTION.equals(action)) { mSearchMode = true; mShowSearchSnippets = true; Bundle extras = intent.getExtras(); if (extras != null) { mInitialFilter = extras.getString(UI.FILTER_TEXT_EXTRA_KEY); String originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); if (originalAction != null) { action = originalAction; } String originalComponent = extras.getString(ContactsSearchManager.ORIGINAL_COMPONENT_EXTRA_KEY); if (originalComponent != null) { component = originalComponent; } } else { mInitialFilter = null; } } Log.i(TAG, "Called with action: " + action); mMode = MODE_UNKNOWN; if (UI.LIST_DEFAULT.equals(action) || UI.FILTER_CONTACTS_ACTION.equals(action)) { mMode = MODE_DEFAULT; // When mDefaultMode is true the mode is set in onResume(), since the preferneces // activity may change it whenever this activity isn't running } else if (UI.LIST_GROUP_ACTION.equals(action)) { mMode = MODE_GROUP; String groupName = intent.getStringExtra(UI.GROUP_NAME_EXTRA_KEY); if (TextUtils.isEmpty(groupName)) { finish(); return; } buildUserGroupUri(groupName); } else if (UI.LIST_ALL_CONTACTS_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = false; } else if (UI.LIST_STARRED_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STARRED; } else if (UI.LIST_FREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_FREQUENT; } else if (UI.LIST_STREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STREQUENT; } else if (UI.LIST_CONTACTS_WITH_PHONES_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = true; } else if (Intent.ACTION_PICK.equals(action)) { // XXX These should be showing the data from the URI given in // the Intent. final String type = intent.resolveType(this); if (Contacts.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_CONTACT; } else if (People.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PERSON; } else if (Phone.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } } else if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { if (component.equals("alias.DialShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_CALL; + mShowSearchSnippets = false; setTitle(R.string.callShortcutActivityTitle); } else if (component.equals("alias.MessageShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_SENDTO; + mShowSearchSnippets = false; setTitle(R.string.messageShortcutActivityTitle); } else if (mSearchMode) { mMode = MODE_PICK_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } else { mMode = MODE_PICK_OR_CREATE_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } } else if (Intent.ACTION_GET_CONTENT.equals(action)) { final String type = intent.resolveType(this); if (Contacts.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_PICK_OR_CREATE_CONTACT; } } else if (Phone.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } else if (People.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_LEGACY_PICK_PERSON; } else { mMode = MODE_LEGACY_PICK_OR_CREATE_PERSON; } } } else if (Intent.ACTION_INSERT_OR_EDIT.equals(action)) { mMode = MODE_INSERT_OR_EDIT_CONTACT; } else if (Intent.ACTION_SEARCH.equals(action)) { // See if the suggestion was clicked with a search action key (call button) if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG))) { String query = intent.getStringExtra(SearchManager.QUERY); if (!TextUtils.isEmpty(query)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", query, null)); startActivity(newIntent); } finish(); return; } // See if search request has extras to specify query if (intent.hasExtra(Insert.EMAIL)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_MAILTO; mInitialFilter = intent.getStringExtra(Insert.EMAIL); } else if (intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { // Otherwise handle the more normal search case mMode = MODE_QUERY; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; } else if (ACTION_SEARCH_INTERNAL.equals(action)) { String originalAction = null; Bundle extras = intent.getExtras(); if (extras != null) { originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); } mShortcutAction = intent.getStringExtra(SHORTCUT_ACTION_KEY); if (Intent.ACTION_INSERT_OR_EDIT.equals(originalAction)) { mMode = MODE_QUERY_PICK_TO_EDIT; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } else if (mShortcutAction != null && intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_PHONE; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { mMode = MODE_QUERY_PICK; mQueryMode = QUERY_MODE_NONE; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; // Since this is the filter activity it receives all intents // dispatched from the SearchManager for security reasons // so we need to re-dispatch from here to the intended target. } else if (Intents.SEARCH_SUGGESTION_CLICKED.equals(action)) { Uri data = intent.getData(); Uri telUri = null; if (sContactsIdMatcher.match(data) == CONTACTS_ID) { long contactId = Long.valueOf(data.getLastPathSegment()); final Cursor cursor = queryPhoneNumbers(contactId); if (cursor != null) { if (cursor.getCount() == 1 && cursor.moveToFirst()) { int phoneNumberIndex = cursor.getColumnIndex(Phone.NUMBER); String phoneNumber = cursor.getString(phoneNumberIndex); telUri = Uri.parse("tel:" + phoneNumber); } cursor.close(); } } // See if the suggestion was clicked with a search action key (call button) Intent newIntent; if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG)) && telUri != null) { newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, telUri); } else { newIntent = new Intent(Intent.ACTION_VIEW, data); } startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED.equals(action)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED.equals(action)) { // TODO actually support this in EditContactActivity. String number = intent.getData().getSchemeSpecificPart(); Intent newIntent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); newIntent.putExtra(Intents.Insert.PHONE, number); startActivity(newIntent); finish(); return; } if (JOIN_AGGREGATE.equals(action)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_JOIN_CONTACT; mQueryAggregateId = intent.getLongExtra(EXTRA_AGGREGATE_ID, -1); if (mQueryAggregateId == -1) { Log.e(TAG, "Intent " + action + " is missing required extra: " + EXTRA_AGGREGATE_ID); setResult(RESULT_CANCELED); finish(); } } } if (mMode == MODE_UNKNOWN) { mMode = MODE_DEFAULT; } if (((mMode & MODE_MASK_SHOW_NUMBER_OF_CONTACTS) != 0 || mSearchMode) && !mSearchResultsMode) { mShowNumberOfContacts = true; } if (mMode == MODE_JOIN_CONTACT) { setContentView(R.layout.contacts_list_content_join); TextView blurbView = (TextView)findViewById(R.id.join_contact_blurb); String blurb = getString(R.string.blurbJoinContactDataWith, getContactDisplayName(mQueryAggregateId)); blurbView.setText(blurb); mJoinModeShowAllContacts = true; } else if (mSearchMode) { setContentView(R.layout.contacts_search_content); } else if (mSearchResultsMode) { setContentView(R.layout.contacts_list_search_results); TextView titleText = (TextView)findViewById(R.id.search_results_for); titleText.setText(Html.fromHtml(getString(R.string.search_results_for, "<b>" + mInitialFilter + "</b>"))); } else { setContentView(R.layout.contacts_list_content); } setupListView(); if (mSearchMode) { setupSearchView(); } mQueryHandler = new QueryHandler(this); mJustCreated = true; mSyncEnabled = true; } /** * Register an observer for provider status changes - we will need to * reflect them in the UI. */ private void registerProviderStatusObserver() { getContentResolver().registerContentObserver(ProviderStatus.CONTENT_URI, false, mProviderStatusObserver); } /** * Register an observer for provider status changes - we will need to * reflect them in the UI. */ private void unregisterProviderStatusObserver() { getContentResolver().unregisterContentObserver(mProviderStatusObserver); } private void setupListView() { final ListView list = getListView(); final LayoutInflater inflater = getLayoutInflater(); mHighlightingAnimation = new NameHighlightingAnimation(list, TEXT_HIGHLIGHTING_ANIMATION_DURATION); // Tell list view to not show dividers. We'll do it ourself so that we can *not* show // them when an A-Z headers is visible. list.setDividerHeight(0); list.setOnCreateContextMenuListener(this); mAdapter = new ContactItemListAdapter(this); setListAdapter(mAdapter); if (list instanceof PinnedHeaderListView && mAdapter.getDisplaySectionHeadersEnabled()) { mPinnedHeaderBackgroundColor = getResources().getColor(R.color.pinned_header_background); PinnedHeaderListView pinnedHeaderList = (PinnedHeaderListView)list; View pinnedHeader = inflater.inflate(R.layout.list_section, list, false); pinnedHeaderList.setPinnedHeaderView(pinnedHeader); } list.setOnScrollListener(mAdapter); list.setOnKeyListener(this); list.setOnFocusChangeListener(this); list.setOnTouchListener(this); // We manually save/restore the listview state list.setSaveEnabled(false); } /** * Configures search UI. */ private void setupSearchView() { mSearchEditText = (SearchEditText)findViewById(R.id.search_src_text); mSearchEditText.addTextChangedListener(this); mSearchEditText.setOnEditorActionListener(this); mSearchEditText.setText(mInitialFilter); } private String getContactDisplayName(long contactId) { String contactName = null; Cursor c = getContentResolver().query( ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), new String[] {Contacts.DISPLAY_NAME}, null, null, null); try { if (c != null && c.moveToFirst()) { contactName = c.getString(0); } } finally { if (c != null) { c.close(); } } if (contactName == null) { contactName = ""; } return contactName; } private int getSummaryDisplayNameColumnIndex() { if (mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_PRIMARY) { return SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX; } else { return SUMMARY_DISPLAY_NAME_ALTERNATIVE_COLUMN_INDEX; } } /** {@inheritDoc} */ public void onClick(View v) { int id = v.getId(); switch (id) { // TODO a better way of identifying the button case android.R.id.button1: { final int position = (Integer)v.getTag(); Cursor c = mAdapter.getCursor(); if (c != null) { c.moveToPosition(position); callContact(c); } break; } } } private void setEmptyText() { if (mMode == MODE_JOIN_CONTACT || mSearchMode) { return; } TextView empty = (TextView) findViewById(R.id.emptyText); if (mDisplayOnlyPhones) { empty.setText(getText(R.string.noContactsWithPhoneNumbers)); } else if (mMode == MODE_STREQUENT || mMode == MODE_STARRED) { empty.setText(getText(R.string.noFavoritesHelpText)); } else if (mMode == MODE_QUERY || mMode == MODE_QUERY_PICK || mMode == MODE_QUERY_PICK_PHONE || mMode == MODE_QUERY_PICK_TO_VIEW || mMode == MODE_QUERY_PICK_TO_EDIT) { empty.setText(getText(R.string.noMatchingContacts)); } else { boolean hasSim = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)) .hasIccCard(); boolean createShortcut = Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction()); if (isSyncActive()) { if (createShortcut) { // Help text is the same no matter whether there is SIM or not. empty.setText(getText(R.string.noContactsHelpTextWithSyncForCreateShortcut)); } else if (hasSim) { empty.setText(getText(R.string.noContactsHelpTextWithSync)); } else { empty.setText(getText(R.string.noContactsNoSimHelpTextWithSync)); } } else { if (createShortcut) { // Help text is the same no matter whether there is SIM or not. empty.setText(getText(R.string.noContactsHelpTextForCreateShortcut)); } else if (hasSim) { empty.setText(getText(R.string.noContactsHelpText)); } else { empty.setText(getText(R.string.noContactsNoSimHelpText)); } } } } private boolean isSyncActive() { Account[] accounts = AccountManager.get(this).getAccounts(); if (accounts != null && accounts.length > 0) { IContentService contentService = ContentResolver.getContentService(); for (Account account : accounts) { try { if (contentService.isSyncActive(account, ContactsContract.AUTHORITY)) { return true; } } catch (RemoteException e) { Log.e(TAG, "Could not get the sync status"); } } } return false; } private void buildUserGroupUri(String group) { mGroupUri = Uri.withAppendedPath(Contacts.CONTENT_GROUP_URI, group); } /** * Sets the mode when the request is for "default" */ private void setDefaultMode() { // Load the preferences SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); mDisplayOnlyPhones = prefs.getBoolean(Prefs.DISPLAY_ONLY_PHONES, Prefs.DISPLAY_ONLY_PHONES_DEFAULT); } @Override protected void onDestroy() { super.onDestroy(); mPhotoLoader.stop(); } @Override protected void onPause() { super.onPause(); unregisterProviderStatusObserver(); } @Override protected void onResume() { super.onResume(); registerProviderStatusObserver(); mPhotoLoader.resume(); Activity parent = getParent(); // Do this before setting the filter. The filter thread relies // on some state that is initialized in setDefaultMode if (mMode == MODE_DEFAULT) { // If we're in default mode we need to possibly reset the mode due to a change // in the preferences activity while we weren't running setDefaultMode(); } // See if we were invoked with a filter if (mSearchMode) { mSearchEditText.requestFocus(); } if (!mSearchMode && !checkProviderState(mJustCreated)) { return; } if (mJustCreated) { // We need to start a query here the first time the activity is launched, as long // as we aren't doing a filter. startQuery(); } mJustCreated = false; mSearchInitiated = false; } /** * Obtains the contacts provider status and configures the UI accordingly. * * @param loadData true if the method needs to start a query when the * provider is in the normal state * @return true if the provider status is normal */ private boolean checkProviderState(boolean loadData) { View importFailureView = findViewById(R.id.import_failure); if (importFailureView == null) { return true; } TextView messageView = (TextView) findViewById(R.id.emptyText); // This query can be performed on the UI thread because // the API explicitly allows such use. Cursor cursor = getContentResolver().query(ProviderStatus.CONTENT_URI, new String[] { ProviderStatus.STATUS, ProviderStatus.DATA1 }, null, null, null); try { if (cursor.moveToFirst()) { int status = cursor.getInt(0); if (status != mProviderStatus) { mProviderStatus = status; switch (status) { case ProviderStatus.STATUS_NORMAL: mAdapter.notifyDataSetInvalidated(); if (loadData) { startQuery(); } break; case ProviderStatus.STATUS_CHANGING_LOCALE: messageView.setText(R.string.locale_change_in_progress); mAdapter.changeCursor(null); mAdapter.notifyDataSetInvalidated(); break; case ProviderStatus.STATUS_UPGRADING: messageView.setText(R.string.upgrade_in_progress); mAdapter.changeCursor(null); mAdapter.notifyDataSetInvalidated(); break; case ProviderStatus.STATUS_UPGRADE_OUT_OF_MEMORY: long size = cursor.getLong(1); String message = getResources().getString( R.string.upgrade_out_of_memory, new Object[] {size}); messageView.setText(message); configureImportFailureView(importFailureView); mAdapter.changeCursor(null); mAdapter.notifyDataSetInvalidated(); break; } } } } finally { cursor.close(); } importFailureView.setVisibility( mProviderStatus == ProviderStatus.STATUS_UPGRADE_OUT_OF_MEMORY ? View.VISIBLE : View.GONE); return mProviderStatus == ProviderStatus.STATUS_NORMAL; } private void configureImportFailureView(View importFailureView) { OnClickListener listener = new OnClickListener(){ public void onClick(View v) { switch(v.getId()) { case R.id.import_failure_uninstall_apps: { startActivity(new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS)); break; } case R.id.import_failure_retry_upgrade: { // Send a provider status update, which will trigger a retry ContentValues values = new ContentValues(); values.put(ProviderStatus.STATUS, ProviderStatus.STATUS_UPGRADING); getContentResolver().update(ProviderStatus.CONTENT_URI, values, null, null); break; } } }}; Button uninstallApps = (Button) findViewById(R.id.import_failure_uninstall_apps); uninstallApps.setOnClickListener(listener); Button retryUpgrade = (Button) findViewById(R.id.import_failure_retry_upgrade); retryUpgrade.setOnClickListener(listener); } private String getTextFilter() { if (mSearchEditText != null) { return mSearchEditText.getText().toString(); } return null; } @Override protected void onRestart() { super.onRestart(); if (!checkProviderState(false)) { return; } // The cursor was killed off in onStop(), so we need to get a new one here // We do not perform the query if a filter is set on the list because the // filter will cause the query to happen anyway if (TextUtils.isEmpty(getTextFilter())) { startQuery(); } else { // Run the filtered query on the adapter mAdapter.onContentChanged(); } } @Override protected void onSaveInstanceState(Bundle icicle) { super.onSaveInstanceState(icicle); // Save list state in the bundle so we can restore it after the QueryHandler has run if (mList != null) { icicle.putParcelable(LIST_STATE_KEY, mList.onSaveInstanceState()); } } @Override protected void onRestoreInstanceState(Bundle icicle) { super.onRestoreInstanceState(icicle); // Retrieve list state. This will be applied after the QueryHandler has run mListState = icicle.getParcelable(LIST_STATE_KEY); } @Override protected void onStop() { super.onStop(); mAdapter.setSuggestionsCursor(null); mAdapter.changeCursor(null); if (mMode == MODE_QUERY) { // Make sure the search box is closed SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); searchManager.stopSearch(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // If Contacts was invoked by another Activity simply as a way of // picking a contact, don't show the options menu if ((mMode & MODE_MASK_PICKER) == MODE_MASK_PICKER) { return false; } MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.list, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { final boolean defaultMode = (mMode == MODE_DEFAULT); menu.findItem(R.id.menu_display_groups).setVisible(defaultMode); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_display_groups: { final Intent intent = new Intent(this, ContactsPreferencesActivity.class); startActivityForResult(intent, SUBACTIVITY_DISPLAY_GROUP); return true; } case R.id.menu_search: { onSearchRequested(); return true; } case R.id.menu_add: { final Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); startActivity(intent); return true; } case R.id.menu_import_export: { displayImportExportDialog(); return true; } case R.id.menu_accounts: { final Intent intent = new Intent(Settings.ACTION_SYNC_SETTINGS); intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { ContactsContract.AUTHORITY }); startActivity(intent); return true; } } return false; } @Override public void startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch) { if (mProviderStatus != ProviderStatus.STATUS_NORMAL) { return; } if (globalSearch) { super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch); } else { if (!mSearchMode && (mMode & MODE_MASK_NO_FILTER) == 0) { if ((mMode & MODE_MASK_PICKER) != 0) { ContactsSearchManager.startSearchForResult(this, initialQuery, SUBACTIVITY_FILTER); } else { ContactsSearchManager.startSearch(this, initialQuery); } } } } /** * Performs filtering of the list based on the search query entered in the * search text edit. */ protected void onSearchTextChanged() { // Set the proper empty string setEmptyText(); Filter filter = mAdapter.getFilter(); filter.filter(getTextFilter()); } /** * Starts a new activity that will run a search query and display search results. */ private void doSearch() { String query = getTextFilter(); if (TextUtils.isEmpty(query)) { return; } Intent intent = new Intent(this, SearchResultsActivity.class); Intent originalIntent = getIntent(); Bundle originalExtras = originalIntent.getExtras(); if (originalExtras != null) { intent.putExtras(originalExtras); } intent.putExtra(SearchManager.QUERY, query); if ((mMode & MODE_MASK_PICKER) != 0) { intent.setAction(ACTION_SEARCH_INTERNAL); intent.putExtra(SHORTCUT_ACTION_KEY, mShortcutAction); if (mShortcutAction != null) { if (Intent.ACTION_CALL.equals(mShortcutAction) || Intent.ACTION_SENDTO.equals(mShortcutAction)) { intent.putExtra(Insert.PHONE, query); } } else { switch (mQueryMode) { case QUERY_MODE_MAILTO: intent.putExtra(Insert.EMAIL, query); break; case QUERY_MODE_TEL: intent.putExtra(Insert.PHONE, query); break; } } startActivityForResult(intent, SUBACTIVITY_SEARCH); } else { intent.setAction(Intent.ACTION_SEARCH); startActivity(intent); } } @Override protected Dialog onCreateDialog(int id, Bundle bundle) { switch (id) { case R.string.import_from_sim: case R.string.import_from_sdcard: { return AccountSelectionUtil.getSelectAccountDialog(this, id); } case R.id.dialog_sdcard_not_found: { return new AlertDialog.Builder(this) .setTitle(R.string.no_sdcard_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.no_sdcard_message) .setPositiveButton(android.R.string.ok, null).create(); } case R.id.dialog_delete_contact_confirmation: { return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.deleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener()).create(); } case R.id.dialog_readonly_contact_hide_confirmation: { return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.readOnlyContactWarning) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener()).create(); } case R.id.dialog_readonly_contact_delete_confirmation: { return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.readOnlyContactDeleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener()).create(); } case R.id.dialog_multiple_contact_delete_confirmation: { return new AlertDialog.Builder(this) .setTitle(R.string.deleteConfirmation_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.multipleContactDeleteConfirmation) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DeleteClickListener()).create(); } } return super.onCreateDialog(id, bundle); } /** * Create a {@link Dialog} that allows the user to pick from a bulk import * or bulk export task across all contacts. */ private void displayImportExportDialog() { // Wrap our context to inflate list items using correct theme final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final Resources res = dialogContext.getResources(); final LayoutInflater dialogInflater = (LayoutInflater)dialogContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Adapter that shows a list of string resources final ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_list_item_1) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = dialogInflater.inflate(android.R.layout.simple_list_item_1, parent, false); } final int resId = this.getItem(position); ((TextView)convertView).setText(resId); return convertView; } }; if (TelephonyManager.getDefault().hasIccCard()) { adapter.add(R.string.import_from_sim); } if (res.getBoolean(R.bool.config_allow_import_from_sdcard)) { adapter.add(R.string.import_from_sdcard); } if (res.getBoolean(R.bool.config_allow_export_to_sdcard)) { adapter.add(R.string.export_to_sdcard); } if (res.getBoolean(R.bool.config_allow_share_visible_contacts)) { adapter.add(R.string.share_visible_contacts); } final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); final int resId = adapter.getItem(which); switch (resId) { case R.string.import_from_sim: case R.string.import_from_sdcard: { handleImportRequest(resId); break; } case R.string.export_to_sdcard: { Context context = ContactsListActivity.this; Intent exportIntent = new Intent(context, ExportVCardActivity.class); context.startActivity(exportIntent); break; } case R.string.share_visible_contacts: { doShareVisibleContacts(); break; } default: { Log.e(TAG, "Unexpected resource: " + getResources().getResourceEntryName(resId)); } } } }; new AlertDialog.Builder(this) .setTitle(R.string.dialog_import_export) .setNegativeButton(android.R.string.cancel, null) .setSingleChoiceItems(adapter, -1, clickListener) .show(); } private void doShareVisibleContacts() { final Cursor cursor = getContentResolver().query(Contacts.CONTENT_URI, sLookupProjection, getContactSelection(), null, null); try { if (!cursor.moveToFirst()) { Toast.makeText(this, R.string.share_error, Toast.LENGTH_SHORT).show(); return; } StringBuilder uriListBuilder = new StringBuilder(); int index = 0; for (;!cursor.isAfterLast(); cursor.moveToNext()) { if (index != 0) uriListBuilder.append(':'); uriListBuilder.append(cursor.getString(0)); index++; } Uri uri = Uri.withAppendedPath( Contacts.CONTENT_MULTI_VCARD_URI, Uri.encode(uriListBuilder.toString())); final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType(Contacts.CONTENT_VCARD_TYPE); intent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(intent); } finally { cursor.close(); } } private void handleImportRequest(int resId) { // There's three possibilities: // - more than one accounts -> ask the user // - just one account -> use the account without asking the user // - no account -> use phone-local storage without asking the user final Sources sources = Sources.getInstance(this); final List<Account> accountList = sources.getAccounts(true); final int size = accountList.size(); if (size > 1) { showDialog(resId); return; } AccountSelectionUtil.doImport(this, resId, (size == 1 ? accountList.get(0) : null)); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case SUBACTIVITY_NEW_CONTACT: if (resultCode == RESULT_OK) { returnPickerResult(null, data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME), data.getData()); } break; case SUBACTIVITY_VIEW_CONTACT: if (resultCode == RESULT_OK) { mAdapter.notifyDataSetChanged(); } break; case SUBACTIVITY_DISPLAY_GROUP: // Mark as just created so we re-run the view query mJustCreated = true; break; case SUBACTIVITY_FILTER: case SUBACTIVITY_SEARCH: // Pass through results of filter or search UI if (resultCode == RESULT_OK) { setResult(RESULT_OK, data); finish(); } break; } } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { // If Contacts was invoked by another Activity simply as a way of // picking a contact, don't show the context menu if ((mMode & MODE_MASK_PICKER) == MODE_MASK_PICKER) { return; } AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) menuInfo; } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return; } Cursor cursor = (Cursor) getListAdapter().getItem(info.position); if (cursor == null) { // For some reason the requested item isn't available, do nothing return; } long id = info.id; Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, id); long rawContactId = ContactsUtils.queryForRawContactId(getContentResolver(), id); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); // Setup the menu header menu.setHeaderTitle(cursor.getString(getSummaryDisplayNameColumnIndex())); // View contact details menu.add(0, MENU_ITEM_VIEW_CONTACT, 0, R.string.menu_viewContact) .setIntent(new Intent(Intent.ACTION_VIEW, contactUri)); if (cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0) { // Calling contact menu.add(0, MENU_ITEM_CALL, 0, getString(R.string.menu_call)); // Send SMS item menu.add(0, MENU_ITEM_SEND_SMS, 0, getString(R.string.menu_sendSMS)); } // Star toggling int starState = cursor.getInt(SUMMARY_STARRED_COLUMN_INDEX); if (starState == 0) { menu.add(0, MENU_ITEM_TOGGLE_STAR, 0, R.string.menu_addStar); } else { menu.add(0, MENU_ITEM_TOGGLE_STAR, 0, R.string.menu_removeStar); } // Contact editing menu.add(0, MENU_ITEM_EDIT, 0, R.string.menu_editContact) .setIntent(new Intent(Intent.ACTION_EDIT, rawContactUri)); menu.add(0, MENU_ITEM_DELETE, 0, R.string.menu_deleteContact); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return false; } Cursor cursor = (Cursor) getListAdapter().getItem(info.position); switch (item.getItemId()) { case MENU_ITEM_TOGGLE_STAR: { // Toggle the star ContentValues values = new ContentValues(1); values.put(Contacts.STARRED, cursor.getInt(SUMMARY_STARRED_COLUMN_INDEX) == 0 ? 1 : 0); final Uri selectedUri = this.getContactUri(info.position); getContentResolver().update(selectedUri, values, null, null); return true; } case MENU_ITEM_CALL: { callContact(cursor); return true; } case MENU_ITEM_SEND_SMS: { smsContact(cursor); return true; } case MENU_ITEM_DELETE: { doContactDelete(getContactUri(info.position)); return true; } } return super.onContextItemSelected(item); } /** * Event handler for the use case where the user starts typing without * bringing up the search UI first. */ public boolean onKey(View v, int keyCode, KeyEvent event) { if (!mSearchMode && (mMode & MODE_MASK_NO_FILTER) == 0 && !mSearchInitiated) { int unicodeChar = event.getUnicodeChar(); if (unicodeChar != 0) { mSearchInitiated = true; startSearch(new String(new int[]{unicodeChar}, 0, 1), false, null, false); return true; } } return false; } /** * Event handler for search UI. */ public void afterTextChanged(Editable s) { onSearchTextChanged(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } /** * Event handler for search UI. */ public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { hideSoftKeyboard(); if (TextUtils.isEmpty(getTextFilter())) { finish(); } return true; } return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_CALL: { if (callSelection()) { return true; } break; } case KeyEvent.KEYCODE_DEL: { if (deleteSelection()) { return true; } break; } } return super.onKeyDown(keyCode, event); } private boolean deleteSelection() { if ((mMode & MODE_MASK_PICKER) != 0) { return false; } final int position = getListView().getSelectedItemPosition(); if (position != ListView.INVALID_POSITION) { Uri contactUri = getContactUri(position); if (contactUri != null) { doContactDelete(contactUri); return true; } } return false; } /** * Prompt the user before deleting the given {@link Contacts} entry. */ protected void doContactDelete(Uri contactUri) { mReadOnlySourcesCnt = 0; mWritableSourcesCnt = 0; mWritableRawContactIds.clear(); Sources sources = Sources.getInstance(ContactsListActivity.this); Cursor c = getContentResolver().query(RawContacts.CONTENT_URI, RAW_CONTACTS_PROJECTION, RawContacts.CONTACT_ID + "=" + ContentUris.parseId(contactUri), null, null); if (c != null) { try { while (c.moveToNext()) { final String accountType = c.getString(2); final long rawContactId = c.getLong(0); ContactsSource contactsSource = sources.getInflatedSource(accountType, ContactsSource.LEVEL_SUMMARY); if (contactsSource != null && contactsSource.readOnly) { mReadOnlySourcesCnt += 1; } else { mWritableSourcesCnt += 1; mWritableRawContactIds.add(rawContactId); } } } finally { c.close(); } } mSelectedContactUri = contactUri; if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt > 0) { showDialog(R.id.dialog_readonly_contact_delete_confirmation); } else if (mReadOnlySourcesCnt > 0 && mWritableSourcesCnt == 0) { showDialog(R.id.dialog_readonly_contact_hide_confirmation); } else if (mReadOnlySourcesCnt == 0 && mWritableSourcesCnt > 1) { showDialog(R.id.dialog_multiple_contact_delete_confirmation); } else { showDialog(R.id.dialog_delete_contact_confirmation); } } /** * Dismisses the soft keyboard when the list takes focus. */ public void onFocusChange(View view, boolean hasFocus) { if (view == getListView() && hasFocus) { hideSoftKeyboard(); } } /** * Dismisses the soft keyboard when the list takes focus. */ public boolean onTouch(View view, MotionEvent event) { if (view == getListView()) { hideSoftKeyboard(); } return false; } /** * Dismisses the search UI along with the keyboard if the filter text is empty. */ public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (mSearchMode && keyCode == KeyEvent.KEYCODE_BACK && TextUtils.isEmpty(getTextFilter())) { hideSoftKeyboard(); onBackPressed(); return true; } return false; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { hideSoftKeyboard(); if (mSearchMode && mAdapter.isSearchAllContactsItemPosition(position)) { doSearch(); } else if (mMode == MODE_INSERT_OR_EDIT_CONTACT || mMode == MODE_QUERY_PICK_TO_EDIT) { Intent intent; if (position == 0 && !mSearchMode && mMode != MODE_QUERY_PICK_TO_EDIT) { intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); } else { intent = new Intent(Intent.ACTION_EDIT, getSelectedUri(position)); } intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); Bundle extras = getIntent().getExtras(); if (extras != null) { intent.putExtras(extras); } intent.putExtra(KEY_PICKER_MODE, (mMode & MODE_MASK_PICKER) == MODE_MASK_PICKER); startActivity(intent); finish(); } else if ((mMode & MODE_MASK_CREATE_NEW) == MODE_MASK_CREATE_NEW && position == 0) { Intent newContact = new Intent(Intents.Insert.ACTION, Contacts.CONTENT_URI); startActivityForResult(newContact, SUBACTIVITY_NEW_CONTACT); } else if (mMode == MODE_JOIN_CONTACT && id == JOIN_MODE_SHOW_ALL_CONTACTS_ID) { mJoinModeShowAllContacts = false; startQuery(); } else if (id > 0) { final Uri uri = getSelectedUri(position); if ((mMode & MODE_MASK_PICKER) == 0) { final Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivityForResult(intent, SUBACTIVITY_VIEW_CONTACT); } else if (mMode == MODE_JOIN_CONTACT) { returnPickerResult(null, null, uri); } else if (mMode == MODE_QUERY_PICK_TO_VIEW) { // Started with query that should launch to view contact final Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); finish(); } else if (mMode == MODE_PICK_PHONE || mMode == MODE_QUERY_PICK_PHONE) { Cursor c = (Cursor) mAdapter.getItem(position); returnPickerResult(c, c.getString(PHONE_DISPLAY_NAME_COLUMN_INDEX), uri); } else if ((mMode & MODE_MASK_PICKER) != 0) { Cursor c = (Cursor) mAdapter.getItem(position); returnPickerResult(c, c.getString(getSummaryDisplayNameColumnIndex()), uri); } else if (mMode == MODE_PICK_POSTAL || mMode == MODE_LEGACY_PICK_POSTAL || mMode == MODE_LEGACY_PICK_PHONE) { returnPickerResult(null, null, uri); } } else { signalError(); } } private void hideSoftKeyboard() { // Hide soft keyboard, if visible InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(mList.getWindowToken(), 0); } /** * @param selectedUri In most cases, this should be a lookup {@link Uri}, possibly * generated through {@link Contacts#getLookupUri(long, String)}. */ private void returnPickerResult(Cursor c, String name, Uri selectedUri) { final Intent intent = new Intent(); if (mShortcutAction != null) { Intent shortcutIntent; if (Intent.ACTION_VIEW.equals(mShortcutAction)) { // This is a simple shortcut to view a contact. shortcutIntent = new Intent(ContactsContract.QuickContact.ACTION_QUICK_CONTACT); shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); shortcutIntent.setData(selectedUri); shortcutIntent.putExtra(ContactsContract.QuickContact.EXTRA_MODE, ContactsContract.QuickContact.MODE_LARGE); shortcutIntent.putExtra(ContactsContract.QuickContact.EXTRA_EXCLUDE_MIMES, (String[]) null); final Bitmap icon = framePhoto(loadContactPhoto(selectedUri, null)); if (icon != null) { intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, scaleToAppIconSize(icon)); } else { intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher_shortcut_contact)); } } else { // This is a direct dial or sms shortcut. String number = c.getString(PHONE_NUMBER_COLUMN_INDEX); int type = c.getInt(PHONE_TYPE_COLUMN_INDEX); String scheme; int resid; if (Intent.ACTION_CALL.equals(mShortcutAction)) { scheme = Constants.SCHEME_TEL; resid = R.drawable.badge_action_call; } else { scheme = Constants.SCHEME_SMSTO; resid = R.drawable.badge_action_sms; } // Make the URI a direct tel: URI so that it will always continue to work Uri phoneUri = Uri.fromParts(scheme, number, null); shortcutIntent = new Intent(mShortcutAction, phoneUri); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, generatePhoneNumberIcon(selectedUri, type, resid)); } shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); setResult(RESULT_OK, intent); } else { intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); setResult(RESULT_OK, intent.setData(selectedUri)); } finish(); } private Bitmap framePhoto(Bitmap photo) { final Resources r = getResources(); final Drawable frame = r.getDrawable(com.android.internal.R.drawable.quickcontact_badge); final int width = r.getDimensionPixelSize(R.dimen.contact_shortcut_frame_width); final int height = r.getDimensionPixelSize(R.dimen.contact_shortcut_frame_height); frame.setBounds(0, 0, width, height); final Rect padding = new Rect(); frame.getPadding(padding); final Rect source = new Rect(0, 0, photo.getWidth(), photo.getHeight()); final Rect destination = new Rect(padding.left, padding.top, width - padding.right, height - padding.bottom); final int d = Math.max(width, height); final Bitmap b = Bitmap.createBitmap(d, d, Bitmap.Config.ARGB_8888); final Canvas c = new Canvas(b); c.translate((d - width) / 2.0f, (d - height) / 2.0f); frame.draw(c); c.drawBitmap(photo, source, destination, new Paint(Paint.FILTER_BITMAP_FLAG)); return b; } /** * Generates a phone number shortcut icon. Adds an overlay describing the type of the phone * number, and if there is a photo also adds the call action icon. * * @param lookupUri The person the phone number belongs to * @param type The type of the phone number * @param actionResId The ID for the action resource * @return The bitmap for the icon */ private Bitmap generatePhoneNumberIcon(Uri lookupUri, int type, int actionResId) { final Resources r = getResources(); boolean drawPhoneOverlay = true; final float scaleDensity = getResources().getDisplayMetrics().scaledDensity; Bitmap photo = loadContactPhoto(lookupUri, null); if (photo == null) { // If there isn't a photo use the generic phone action icon instead Bitmap phoneIcon = getPhoneActionIcon(r, actionResId); if (phoneIcon != null) { photo = phoneIcon; drawPhoneOverlay = false; } else { return null; } } // Setup the drawing classes Bitmap icon = createShortcutBitmap(); Canvas canvas = new Canvas(icon); // Copy in the photo Paint photoPaint = new Paint(); photoPaint.setDither(true); photoPaint.setFilterBitmap(true); Rect src = new Rect(0,0, photo.getWidth(),photo.getHeight()); Rect dst = new Rect(0,0, mIconSize, mIconSize); canvas.drawBitmap(photo, src, dst, photoPaint); // Create an overlay for the phone number type String overlay = null; switch (type) { case Phone.TYPE_HOME: overlay = getString(R.string.type_short_home); break; case Phone.TYPE_MOBILE: overlay = getString(R.string.type_short_mobile); break; case Phone.TYPE_WORK: overlay = getString(R.string.type_short_work); break; case Phone.TYPE_PAGER: overlay = getString(R.string.type_short_pager); break; case Phone.TYPE_OTHER: overlay = getString(R.string.type_short_other); break; } if (overlay != null) { Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); textPaint.setTextSize(20.0f * scaleDensity); textPaint.setTypeface(Typeface.DEFAULT_BOLD); textPaint.setColor(r.getColor(R.color.textColorIconOverlay)); textPaint.setShadowLayer(3f, 1, 1, r.getColor(R.color.textColorIconOverlayShadow)); canvas.drawText(overlay, 2 * scaleDensity, 16 * scaleDensity, textPaint); } // Draw the phone action icon as an overlay if (ENABLE_ACTION_ICON_OVERLAYS && drawPhoneOverlay) { Bitmap phoneIcon = getPhoneActionIcon(r, actionResId); if (phoneIcon != null) { src.set(0, 0, phoneIcon.getWidth(), phoneIcon.getHeight()); int iconWidth = icon.getWidth(); dst.set(iconWidth - ((int) (20 * scaleDensity)), -1, iconWidth, ((int) (19 * scaleDensity))); canvas.drawBitmap(phoneIcon, src, dst, photoPaint); } } return icon; } private Bitmap scaleToAppIconSize(Bitmap photo) { // Setup the drawing classes Bitmap icon = createShortcutBitmap(); Canvas canvas = new Canvas(icon); // Copy in the photo Paint photoPaint = new Paint(); photoPaint.setDither(true); photoPaint.setFilterBitmap(true); Rect src = new Rect(0,0, photo.getWidth(),photo.getHeight()); Rect dst = new Rect(0,0, mIconSize, mIconSize); canvas.drawBitmap(photo, src, dst, photoPaint); return icon; } private Bitmap createShortcutBitmap() { return Bitmap.createBitmap(mIconSize, mIconSize, Bitmap.Config.ARGB_8888); } /** * Returns the icon for the phone call action. * * @param r The resources to load the icon from * @param resId The resource ID to load * @return the icon for the phone call action */ private Bitmap getPhoneActionIcon(Resources r, int resId) { Drawable phoneIcon = r.getDrawable(resId); if (phoneIcon instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) phoneIcon; return bd.getBitmap(); } else { return null; } } private Uri getUriToQuery() { switch(mMode) { case MODE_JOIN_CONTACT: return getJoinSuggestionsUri(null); case MODE_FREQUENT: case MODE_STARRED: return Contacts.CONTENT_URI; case MODE_DEFAULT: case MODE_INSERT_OR_EDIT_CONTACT: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT:{ return CONTACTS_CONTENT_URI_WITH_LETTER_COUNTS; } case MODE_STREQUENT: { return Contacts.CONTENT_STREQUENT_URI; } case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { return People.CONTENT_URI; } case MODE_PICK_PHONE: { return buildSectionIndexerUri(Phone.CONTENT_URI); } case MODE_LEGACY_PICK_PHONE: { return Phones.CONTENT_URI; } case MODE_PICK_POSTAL: { return buildSectionIndexerUri(StructuredPostal.CONTENT_URI); } case MODE_LEGACY_PICK_POSTAL: { return ContactMethods.CONTENT_URI; } case MODE_QUERY_PICK_TO_VIEW: { if (mQueryMode == QUERY_MODE_MAILTO) { return Uri.withAppendedPath(Email.CONTENT_FILTER_URI, Uri.encode(mInitialFilter)); } else if (mQueryMode == QUERY_MODE_TEL) { return Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(mInitialFilter)); } return CONTACTS_CONTENT_URI_WITH_LETTER_COUNTS; } case MODE_QUERY: case MODE_QUERY_PICK: case MODE_QUERY_PICK_TO_EDIT: { return getContactFilterUri(mInitialFilter); } case MODE_QUERY_PICK_PHONE: { return Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(mInitialFilter)); } case MODE_GROUP: { return mGroupUri; } default: { throw new IllegalStateException("Can't generate URI: Unsupported Mode."); } } } /** * Build the {@link Contacts#CONTENT_LOOKUP_URI} for the given * {@link ListView} position, using {@link #mAdapter}. */ private Uri getContactUri(int position) { if (position == ListView.INVALID_POSITION) { throw new IllegalArgumentException("Position not in list bounds"); } final Cursor cursor = (Cursor)mAdapter.getItem(position); if (cursor == null) { return null; } switch(mMode) { case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { final long personId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX); return ContentUris.withAppendedId(People.CONTENT_URI, personId); } default: { // Build and return soft, lookup reference final long contactId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX); final String lookupKey = cursor.getString(SUMMARY_LOOKUP_KEY_COLUMN_INDEX); return Contacts.getLookupUri(contactId, lookupKey); } } } /** * Build the {@link Uri} for the given {@link ListView} position, which can * be used as result when in {@link #MODE_MASK_PICKER} mode. */ private Uri getSelectedUri(int position) { if (position == ListView.INVALID_POSITION) { throw new IllegalArgumentException("Position not in list bounds"); } final long id = mAdapter.getItemId(position); switch(mMode) { case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { return ContentUris.withAppendedId(People.CONTENT_URI, id); } case MODE_PICK_PHONE: case MODE_QUERY_PICK_PHONE: { return ContentUris.withAppendedId(Data.CONTENT_URI, id); } case MODE_LEGACY_PICK_PHONE: { return ContentUris.withAppendedId(Phones.CONTENT_URI, id); } case MODE_PICK_POSTAL: { return ContentUris.withAppendedId(Data.CONTENT_URI, id); } case MODE_LEGACY_PICK_POSTAL: { return ContentUris.withAppendedId(ContactMethods.CONTENT_URI, id); } default: { return getContactUri(position); } } } String[] getProjectionForQuery() { switch(mMode) { case MODE_JOIN_CONTACT: case MODE_STREQUENT: case MODE_FREQUENT: case MODE_STARRED: case MODE_DEFAULT: case MODE_INSERT_OR_EDIT_CONTACT: case MODE_GROUP: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT: { return mSearchMode ? CONTACTS_SUMMARY_FILTER_PROJECTION : CONTACTS_SUMMARY_PROJECTION; } case MODE_QUERY: case MODE_QUERY_PICK: case MODE_QUERY_PICK_TO_EDIT: { return CONTACTS_SUMMARY_FILTER_PROJECTION; } case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { return LEGACY_PEOPLE_PROJECTION ; } case MODE_QUERY_PICK_PHONE: case MODE_PICK_PHONE: { return PHONES_PROJECTION; } case MODE_LEGACY_PICK_PHONE: { return LEGACY_PHONES_PROJECTION; } case MODE_PICK_POSTAL: { return POSTALS_PROJECTION; } case MODE_LEGACY_PICK_POSTAL: { return LEGACY_POSTALS_PROJECTION; } case MODE_QUERY_PICK_TO_VIEW: { if (mQueryMode == QUERY_MODE_MAILTO) { return CONTACTS_SUMMARY_PROJECTION_FROM_EMAIL; } else if (mQueryMode == QUERY_MODE_TEL) { return PHONES_PROJECTION; } break; } } // Default to normal aggregate projection return CONTACTS_SUMMARY_PROJECTION; } private Bitmap loadContactPhoto(Uri selectedUri, BitmapFactory.Options options) { Uri contactUri = null; if (Contacts.CONTENT_ITEM_TYPE.equals(getContentResolver().getType(selectedUri))) { // TODO we should have a "photo" directory under the lookup URI itself contactUri = Contacts.lookupContact(getContentResolver(), selectedUri); } else { Cursor cursor = getContentResolver().query(selectedUri, new String[] { Data.CONTACT_ID }, null, null, null); try { if (cursor != null && cursor.moveToFirst()) { final long contactId = cursor.getLong(0); contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); } } finally { if (cursor != null) cursor.close(); } } Cursor cursor = null; Bitmap bm = null; try { Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY); cursor = getContentResolver().query(photoUri, new String[] {Photo.PHOTO}, null, null, null); if (cursor != null && cursor.moveToFirst()) { bm = ContactsUtils.loadContactPhoto(cursor, 0, options); } } finally { if (cursor != null) { cursor.close(); } } if (bm == null) { final int[] fallbacks = { R.drawable.ic_contact_picture, R.drawable.ic_contact_picture_2, R.drawable.ic_contact_picture_3 }; bm = BitmapFactory.decodeResource(getResources(), fallbacks[new Random().nextInt(fallbacks.length)]); } return bm; } /** * Return the selection arguments for a default query based on the * {@link #mDisplayOnlyPhones} flag. */ private String getContactSelection() { if (mDisplayOnlyPhones) { return CLAUSE_ONLY_VISIBLE + " AND " + CLAUSE_ONLY_PHONES; } else { return CLAUSE_ONLY_VISIBLE; } } private Uri getContactFilterUri(String filter) { Uri baseUri; if (!TextUtils.isEmpty(filter)) { baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(filter)); } else { baseUri = Contacts.CONTENT_URI; } if (mAdapter.getDisplaySectionHeadersEnabled()) { return buildSectionIndexerUri(baseUri); } else { return baseUri; } } private Uri getPeopleFilterUri(String filter) { if (!TextUtils.isEmpty(filter)) { return Uri.withAppendedPath(People.CONTENT_FILTER_URI, Uri.encode(filter)); } else { return People.CONTENT_URI; } } private static Uri buildSectionIndexerUri(Uri uri) { return uri.buildUpon() .appendQueryParameter(ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, "true").build(); } private Uri getJoinSuggestionsUri(String filter) { Builder builder = Contacts.CONTENT_URI.buildUpon(); builder.appendEncodedPath(String.valueOf(mQueryAggregateId)); builder.appendEncodedPath(AggregationSuggestions.CONTENT_DIRECTORY); if (!TextUtils.isEmpty(filter)) { builder.appendEncodedPath(Uri.encode(filter)); } builder.appendQueryParameter("limit", String.valueOf(MAX_SUGGESTIONS)); return builder.build(); } private String getSortOrder(String[] projectionType) { if (mSortOrder == ContactsContract.Preferences.SORT_ORDER_PRIMARY) { return Contacts.SORT_KEY_PRIMARY; } else { return Contacts.SORT_KEY_ALTERNATIVE; } } void startQuery() { // Set the proper empty string setEmptyText(); if (mSearchResultsMode) { TextView foundContactsText = (TextView)findViewById(R.id.search_results_found); foundContactsText.setText(R.string.search_results_searching); } mAdapter.setLoading(true); // Cancel any pending queries mQueryHandler.cancelOperation(QUERY_TOKEN); mQueryHandler.setLoadingJoinSuggestions(false); mSortOrder = mContactsPrefs.getSortOrder(); mDisplayOrder = mContactsPrefs.getDisplayOrder(); // When sort order and display order contradict each other, we want to // highlight the part of the name used for sorting. mHighlightWhenScrolling = false; if (mSortOrder == ContactsContract.Preferences.SORT_ORDER_PRIMARY && mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_ALTERNATIVE) { mHighlightWhenScrolling = true; } else if (mSortOrder == ContactsContract.Preferences.SORT_ORDER_ALTERNATIVE && mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_PRIMARY) { mHighlightWhenScrolling = true; } String[] projection = getProjectionForQuery(); if (mSearchMode && TextUtils.isEmpty(getTextFilter())) { mAdapter.changeCursor(new MatrixCursor(projection)); return; } String callingPackage = getCallingPackage(); Uri uri = getUriToQuery(); if (!TextUtils.isEmpty(callingPackage)) { uri = uri.buildUpon() .appendQueryParameter(ContactsContract.REQUESTING_PACKAGE_PARAM_KEY, callingPackage) .build(); } // Kick off the new query switch (mMode) { case MODE_GROUP: case MODE_DEFAULT: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT: case MODE_INSERT_OR_EDIT_CONTACT: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, getContactSelection(), null, getSortOrder(projection)); break; case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: case MODE_PICK_POSTAL: case MODE_QUERY: case MODE_QUERY_PICK: case MODE_QUERY_PICK_PHONE: case MODE_QUERY_PICK_TO_VIEW: case MODE_QUERY_PICK_TO_EDIT: { mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, null, null, getSortOrder(projection)); break; } case MODE_STARRED: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, Contacts.STARRED + "=1", null, getSortOrder(projection)); break; case MODE_FREQUENT: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, Contacts.TIMES_CONTACTED + " > 0", null, Contacts.TIMES_CONTACTED + " DESC, " + getSortOrder(projection)); break; case MODE_STREQUENT: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, null, null, null); break; case MODE_PICK_PHONE: case MODE_LEGACY_PICK_PHONE: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, CLAUSE_ONLY_VISIBLE, null, getSortOrder(projection)); break; case MODE_LEGACY_PICK_POSTAL: mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, ContactMethods.KIND + "=" + android.provider.Contacts.KIND_POSTAL, null, getSortOrder(projection)); break; case MODE_JOIN_CONTACT: mQueryHandler.setLoadingJoinSuggestions(true); mQueryHandler.startQuery(QUERY_TOKEN, null, uri, projection, null, null, null); break; } } /** * Called from a background thread to do the filter and return the resulting cursor. * * @param filter the text that was entered to filter on * @return a cursor with the results of the filter */ Cursor doFilter(String filter) { String[] projection = getProjectionForQuery(); if (mSearchMode && TextUtils.isEmpty(getTextFilter())) { return new MatrixCursor(projection); } final ContentResolver resolver = getContentResolver(); switch (mMode) { case MODE_DEFAULT: case MODE_PICK_CONTACT: case MODE_PICK_OR_CREATE_CONTACT: case MODE_INSERT_OR_EDIT_CONTACT: { return resolver.query(getContactFilterUri(filter), projection, getContactSelection(), null, getSortOrder(projection)); } case MODE_LEGACY_PICK_PERSON: case MODE_LEGACY_PICK_OR_CREATE_PERSON: { return resolver.query(getPeopleFilterUri(filter), projection, null, null, getSortOrder(projection)); } case MODE_STARRED: { return resolver.query(getContactFilterUri(filter), projection, Contacts.STARRED + "=1", null, getSortOrder(projection)); } case MODE_FREQUENT: { return resolver.query(getContactFilterUri(filter), projection, Contacts.TIMES_CONTACTED + " > 0", null, Contacts.TIMES_CONTACTED + " DESC, " + getSortOrder(projection)); } case MODE_STREQUENT: { Uri uri; if (!TextUtils.isEmpty(filter)) { uri = Uri.withAppendedPath(Contacts.CONTENT_STREQUENT_FILTER_URI, Uri.encode(filter)); } else { uri = Contacts.CONTENT_STREQUENT_URI; } return resolver.query(uri, projection, null, null, null); } case MODE_PICK_PHONE: { Uri uri = getUriToQuery(); if (!TextUtils.isEmpty(filter)) { uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(filter)); } return resolver.query(uri, projection, CLAUSE_ONLY_VISIBLE, null, getSortOrder(projection)); } case MODE_LEGACY_PICK_PHONE: { //TODO: Support filtering here (bug 2092503) break; } case MODE_JOIN_CONTACT: { // We are on a background thread. Run queries one after the other synchronously Cursor cursor = resolver.query(getJoinSuggestionsUri(filter), projection, null, null, null); mAdapter.setSuggestionsCursor(cursor); mJoinModeShowAllContacts = false; return resolver.query(getContactFilterUri(filter), projection, Contacts._ID + " != " + mQueryAggregateId + " AND " + CLAUSE_ONLY_VISIBLE, null, getSortOrder(projection)); } } throw new UnsupportedOperationException("filtering not allowed in mode " + mMode); } private Cursor getShowAllContactsLabelCursor(String[] projection) { MatrixCursor matrixCursor = new MatrixCursor(projection); Object[] row = new Object[projection.length]; // The only columns we care about is the id row[SUMMARY_ID_COLUMN_INDEX] = JOIN_MODE_SHOW_ALL_CONTACTS_ID; matrixCursor.addRow(row); return matrixCursor; } /** * Calls the currently selected list item. * @return true if the call was initiated, false otherwise */ boolean callSelection() { ListView list = getListView(); if (list.hasFocus()) { Cursor cursor = (Cursor) list.getSelectedItem(); return callContact(cursor); } return false; } boolean callContact(Cursor cursor) { return callOrSmsContact(cursor, false /*call*/); } boolean smsContact(Cursor cursor) { return callOrSmsContact(cursor, true /*sms*/); } /** * Calls the contact which the cursor is point to. * @return true if the call was initiated, false otherwise */ boolean callOrSmsContact(Cursor cursor, boolean sendSms) { if (cursor == null) { return false; } switch (mMode) { case MODE_PICK_PHONE: case MODE_LEGACY_PICK_PHONE: case MODE_QUERY_PICK_PHONE: { String phone = cursor.getString(PHONE_NUMBER_COLUMN_INDEX); if (sendSms) { ContactsUtils.initiateSms(this, phone); } else { ContactsUtils.initiateCall(this, phone); } return true; } case MODE_PICK_POSTAL: case MODE_LEGACY_PICK_POSTAL: { return false; } default: { boolean hasPhone = cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0; if (!hasPhone) { // There is no phone number. signalError(); return false; } String phone = null; Cursor phonesCursor = null; phonesCursor = queryPhoneNumbers(cursor.getLong(SUMMARY_ID_COLUMN_INDEX)); if (phonesCursor == null || phonesCursor.getCount() == 0) { // No valid number signalError(); return false; } else if (phonesCursor.getCount() == 1) { // only one number, call it. phone = phonesCursor.getString(phonesCursor.getColumnIndex(Phone.NUMBER)); } else { phonesCursor.moveToPosition(-1); while (phonesCursor.moveToNext()) { if (phonesCursor.getInt(phonesCursor. getColumnIndex(Phone.IS_SUPER_PRIMARY)) != 0) { // Found super primary, call it. phone = phonesCursor. getString(phonesCursor.getColumnIndex(Phone.NUMBER)); break; } } } if (phone == null) { // Display dialog to choose a number to call. PhoneDisambigDialog phoneDialog = new PhoneDisambigDialog( this, phonesCursor, sendSms); phoneDialog.show(); } else { if (sendSms) { ContactsUtils.initiateSms(this, phone); } else { ContactsUtils.initiateCall(this, phone); } } } } return true; } private Cursor queryPhoneNumbers(long contactId) { Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); Uri dataUri = Uri.withAppendedPath(baseUri, Contacts.Data.CONTENT_DIRECTORY); Cursor c = getContentResolver().query(dataUri, new String[] {Phone._ID, Phone.NUMBER, Phone.IS_SUPER_PRIMARY, RawContacts.ACCOUNT_TYPE, Phone.TYPE, Phone.LABEL}, Data.MIMETYPE + "=?", new String[] {Phone.CONTENT_ITEM_TYPE}, null); if (c != null && c.moveToFirst()) { return c; } return null; } // TODO: fix PluralRules to handle zero correctly and use Resources.getQuantityText directly protected String getQuantityText(int count, int zeroResourceId, int pluralResourceId) { if (count == 0) { return getString(zeroResourceId); } else { String format = getResources().getQuantityText(pluralResourceId, count).toString(); return String.format(format, count); } } /** * Signal an error to the user. */ void signalError() { //TODO play an error beep or something... } Cursor getItemForView(View view) { ListView listView = getListView(); int index = listView.getPositionForView(view); if (index < 0) { return null; } return (Cursor) listView.getAdapter().getItem(index); } private static class QueryHandler extends AsyncQueryHandler { protected final WeakReference<ContactsListActivity> mActivity; protected boolean mLoadingJoinSuggestions = false; public QueryHandler(Context context) { super(context.getContentResolver()); mActivity = new WeakReference<ContactsListActivity>((ContactsListActivity) context); } public void setLoadingJoinSuggestions(boolean flag) { mLoadingJoinSuggestions = flag; } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { final ContactsListActivity activity = mActivity.get(); if (activity != null && !activity.isFinishing()) { // Whenever we get a suggestions cursor, we need to immediately kick off // another query for the complete list of contacts if (cursor != null && mLoadingJoinSuggestions) { mLoadingJoinSuggestions = false; if (cursor.getCount() > 0) { activity.mAdapter.setSuggestionsCursor(cursor); } else { cursor.close(); activity.mAdapter.setSuggestionsCursor(null); } if (activity.mAdapter.mSuggestionsCursorCount == 0 || !activity.mJoinModeShowAllContacts) { startQuery(QUERY_TOKEN, null, activity.getContactFilterUri( activity.getTextFilter()), CONTACTS_SUMMARY_PROJECTION, Contacts._ID + " != " + activity.mQueryAggregateId + " AND " + CLAUSE_ONLY_VISIBLE, null, activity.getSortOrder(CONTACTS_SUMMARY_PROJECTION)); return; } cursor = activity.getShowAllContactsLabelCursor(CONTACTS_SUMMARY_PROJECTION); } activity.mAdapter.changeCursor(cursor); // Now that the cursor is populated again, it's possible to restore the list state if (activity.mListState != null) { activity.mList.onRestoreInstanceState(activity.mListState); activity.mListState = null; } } else { if (cursor != null) { cursor.close(); } } } } final static class ContactListItemCache { public CharArrayBuffer nameBuffer = new CharArrayBuffer(128); public CharArrayBuffer dataBuffer = new CharArrayBuffer(128); public CharArrayBuffer highlightedTextBuffer = new CharArrayBuffer(128); public TextWithHighlighting textWithHighlighting; public CharArrayBuffer phoneticNameBuffer = new CharArrayBuffer(128); } final static class PinnedHeaderCache { public TextView titleView; public ColorStateList textColor; public Drawable background; } private final class ContactItemListAdapter extends CursorAdapter implements SectionIndexer, OnScrollListener, PinnedHeaderListView.PinnedHeaderAdapter { private SectionIndexer mIndexer; private boolean mLoading = true; private CharSequence mUnknownNameText; private boolean mDisplayPhotos = false; private boolean mDisplayCallButton = false; private boolean mDisplayAdditionalData = true; private int mFrequentSeparatorPos = ListView.INVALID_POSITION; private boolean mDisplaySectionHeaders = true; private Cursor mSuggestionsCursor; private int mSuggestionsCursorCount; public ContactItemListAdapter(Context context) { super(context, null, false); mUnknownNameText = context.getText(android.R.string.unknownName); switch (mMode) { case MODE_LEGACY_PICK_POSTAL: case MODE_PICK_POSTAL: case MODE_LEGACY_PICK_PHONE: case MODE_PICK_PHONE: case MODE_STREQUENT: case MODE_FREQUENT: mDisplaySectionHeaders = false; break; } if (mSearchMode) { mDisplaySectionHeaders = false; } // Do not display the second line of text if in a specific SEARCH query mode, usually for // matching a specific E-mail or phone number. Any contact details // shown would be identical, and columns might not even be present // in the returned cursor. if (mMode != MODE_QUERY_PICK_PHONE && mQueryMode != QUERY_MODE_NONE) { mDisplayAdditionalData = false; } if ((mMode & MODE_MASK_NO_DATA) == MODE_MASK_NO_DATA) { mDisplayAdditionalData = false; } if ((mMode & MODE_MASK_SHOW_CALL_BUTTON) == MODE_MASK_SHOW_CALL_BUTTON) { mDisplayCallButton = true; } if ((mMode & MODE_MASK_SHOW_PHOTOS) == MODE_MASK_SHOW_PHOTOS) { mDisplayPhotos = true; } } public boolean getDisplaySectionHeadersEnabled() { return mDisplaySectionHeaders; } public void setSuggestionsCursor(Cursor cursor) { if (mSuggestionsCursor != null) { mSuggestionsCursor.close(); } mSuggestionsCursor = cursor; mSuggestionsCursorCount = cursor == null ? 0 : cursor.getCount(); } /** * Callback on the UI thread when the content observer on the backing cursor fires. * Instead of calling requery we need to do an async query so that the requery doesn't * block the UI thread for a long time. */ @Override protected void onContentChanged() { CharSequence constraint = getTextFilter(); if (!TextUtils.isEmpty(constraint)) { // Reset the filter state then start an async filter operation Filter filter = getFilter(); filter.filter(constraint); } else { // Start an async query startQuery(); } } public void setLoading(boolean loading) { mLoading = loading; } @Override public boolean isEmpty() { if (mProviderStatus != ProviderStatus.STATUS_NORMAL) { return true; } if (mSearchMode) { return TextUtils.isEmpty(getTextFilter()); } else if ((mMode & MODE_MASK_CREATE_NEW) == MODE_MASK_CREATE_NEW) { // This mode mask adds a header and we always want it to show up, even // if the list is empty, so always claim the list is not empty. return false; } else { if (mCursor == null || mLoading) { // We don't want the empty state to show when loading. return false; } else { return super.isEmpty(); } } } @Override public int getItemViewType(int position) { if (position == 0 && (mShowNumberOfContacts || (mMode & MODE_MASK_CREATE_NEW) != 0)) { return IGNORE_ITEM_VIEW_TYPE; } if (isShowAllContactsItemPosition(position)) { return IGNORE_ITEM_VIEW_TYPE; } if (isSearchAllContactsItemPosition(position)) { return IGNORE_ITEM_VIEW_TYPE; } if (getSeparatorId(position) != 0) { // We don't want the separator view to be recycled. return IGNORE_ITEM_VIEW_TYPE; } return super.getItemViewType(position); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (!mDataValid) { throw new IllegalStateException( "this should only be called when the cursor is valid"); } // handle the total contacts item if (position == 0 && mShowNumberOfContacts) { return getTotalContactCountView(parent); } if (position == 0 && (mMode & MODE_MASK_CREATE_NEW) != 0) { // Add the header for creating a new contact return getLayoutInflater().inflate(R.layout.create_new_contact, parent, false); } if (isShowAllContactsItemPosition(position)) { return getLayoutInflater(). inflate(R.layout.contacts_list_show_all_item, parent, false); } if (isSearchAllContactsItemPosition(position)) { return getLayoutInflater(). inflate(R.layout.contacts_list_search_all_item, parent, false); } // Handle the separator specially int separatorId = getSeparatorId(position); if (separatorId != 0) { TextView view = (TextView) getLayoutInflater(). inflate(R.layout.list_separator, parent, false); view.setText(separatorId); return view; } boolean showingSuggestion; Cursor cursor; if (mSuggestionsCursorCount != 0 && position < mSuggestionsCursorCount + 2) { showingSuggestion = true; cursor = mSuggestionsCursor; } else { showingSuggestion = false; cursor = mCursor; } int realPosition = getRealPosition(position); if (!cursor.moveToPosition(realPosition)) { throw new IllegalStateException("couldn't move cursor to position " + position); } boolean newView; View v; if (convertView == null || convertView.getTag() == null) { newView = true; v = newView(mContext, cursor, parent); } else { newView = false; v = convertView; } bindView(v, mContext, cursor); bindSectionHeader(v, realPosition, mDisplaySectionHeaders && !showingSuggestion); return v; } private View getTotalContactCountView(ViewGroup parent) { final LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.total_contacts, parent, false); TextView totalContacts = (TextView) view.findViewById(R.id.totalContactsText); String text; int count = getRealCount(); if (mSearchMode && !TextUtils.isEmpty(getTextFilter())) { text = getQuantityText(count, R.string.listFoundAllContactsZero, R.plurals.searchFoundContacts); } else { if (mDisplayOnlyPhones) { text = getQuantityText(count, R.string.listTotalPhoneContactsZero, R.plurals.listTotalPhoneContacts); } else { text = getQuantityText(count, R.string.listTotalAllContactsZero, R.plurals.listTotalAllContacts); } } totalContacts.setText(text); return view; } private boolean isShowAllContactsItemPosition(int position) { return mMode == MODE_JOIN_CONTACT && mJoinModeShowAllContacts && mSuggestionsCursorCount != 0 && position == mSuggestionsCursorCount + 2; } private boolean isSearchAllContactsItemPosition(int position) { return mSearchMode && position == getCount() - 1; } private int getSeparatorId(int position) { int separatorId = 0; if (position == mFrequentSeparatorPos) { separatorId = R.string.favoritesFrquentSeparator; } if (mSuggestionsCursorCount != 0) { if (position == 0) { separatorId = R.string.separatorJoinAggregateSuggestions; } else if (position == mSuggestionsCursorCount + 1) { separatorId = R.string.separatorJoinAggregateAll; } } return separatorId; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { final ContactListItemView view = new ContactListItemView(context, null); view.setOnCallButtonClickListener(ContactsListActivity.this); view.setTag(new ContactListItemCache()); return view; } @Override public void bindView(View itemView, Context context, Cursor cursor) { final ContactListItemView view = (ContactListItemView)itemView; final ContactListItemCache cache = (ContactListItemCache) view.getTag(); int typeColumnIndex; int dataColumnIndex; int labelColumnIndex; int defaultType; int nameColumnIndex; int phoneticNameColumnIndex; boolean displayAdditionalData = mDisplayAdditionalData; boolean highlightingEnabled = false; switch(mMode) { case MODE_PICK_PHONE: case MODE_LEGACY_PICK_PHONE: case MODE_QUERY_PICK_PHONE: { nameColumnIndex = PHONE_DISPLAY_NAME_COLUMN_INDEX; phoneticNameColumnIndex = -1; dataColumnIndex = PHONE_NUMBER_COLUMN_INDEX; typeColumnIndex = PHONE_TYPE_COLUMN_INDEX; labelColumnIndex = PHONE_LABEL_COLUMN_INDEX; defaultType = Phone.TYPE_HOME; break; } case MODE_PICK_POSTAL: case MODE_LEGACY_PICK_POSTAL: { nameColumnIndex = POSTAL_DISPLAY_NAME_COLUMN_INDEX; phoneticNameColumnIndex = -1; dataColumnIndex = POSTAL_ADDRESS_COLUMN_INDEX; typeColumnIndex = POSTAL_TYPE_COLUMN_INDEX; labelColumnIndex = POSTAL_LABEL_COLUMN_INDEX; defaultType = StructuredPostal.TYPE_HOME; break; } default: { nameColumnIndex = getSummaryDisplayNameColumnIndex(); phoneticNameColumnIndex = SUMMARY_PHONETIC_NAME_COLUMN_INDEX; dataColumnIndex = -1; typeColumnIndex = -1; labelColumnIndex = -1; defaultType = Phone.TYPE_HOME; displayAdditionalData = false; highlightingEnabled = mHighlightWhenScrolling && mMode != MODE_STREQUENT; } } // Set the name cursor.copyStringToBuffer(nameColumnIndex, cache.nameBuffer); TextView nameView = view.getNameTextView(); int size = cache.nameBuffer.sizeCopied; if (size != 0) { if (highlightingEnabled) { if (cache.textWithHighlighting == null) { cache.textWithHighlighting = mHighlightingAnimation.createTextWithHighlighting(); } buildDisplayNameWithHighlighting(nameView, cursor, cache.nameBuffer, cache.highlightedTextBuffer, cache.textWithHighlighting); } else { nameView.setText(cache.nameBuffer.data, 0, size); } } else { nameView.setText(mUnknownNameText); } boolean hasPhone = cursor.getColumnCount() >= SUMMARY_HAS_PHONE_COLUMN_INDEX && cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0; // Make the call button visible if requested. if (mDisplayCallButton && hasPhone) { int pos = cursor.getPosition(); view.showCallButton(android.R.id.button1, pos); } else { view.hideCallButton(); } // Set the photo, if requested if (mDisplayPhotos) { boolean useQuickContact = (mMode & MODE_MASK_DISABLE_QUIKCCONTACT) == 0; long photoId = 0; if (!cursor.isNull(SUMMARY_PHOTO_ID_COLUMN_INDEX)) { photoId = cursor.getLong(SUMMARY_PHOTO_ID_COLUMN_INDEX); } ImageView viewToUse; if (useQuickContact) { // Build soft lookup reference final long contactId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX); final String lookupKey = cursor.getString(SUMMARY_LOOKUP_KEY_COLUMN_INDEX); QuickContactBadge quickContact = view.getQuickContact(); quickContact.assignContactUri(Contacts.getLookupUri(contactId, lookupKey)); viewToUse = quickContact; } else { viewToUse = view.getPhotoView(); } final int position = cursor.getPosition(); mPhotoLoader.loadPhoto(viewToUse, photoId); } if ((mMode & MODE_MASK_NO_PRESENCE) == 0) { // Set the proper icon (star or presence or nothing) int serverStatus; if (!cursor.isNull(SUMMARY_PRESENCE_STATUS_COLUMN_INDEX)) { serverStatus = cursor.getInt(SUMMARY_PRESENCE_STATUS_COLUMN_INDEX); Drawable icon = ContactPresenceIconUtil.getPresenceIcon(mContext, serverStatus); if (icon != null) { view.setPresence(icon); } else { view.setPresence(null); } } else { view.setPresence(null); } } else { view.setPresence(null); } if (mShowSearchSnippets) { boolean showSnippet = false; String snippetMimeType = cursor.getString(SUMMARY_SNIPPET_MIMETYPE_COLUMN_INDEX); if (Email.CONTENT_ITEM_TYPE.equals(snippetMimeType)) { String email = cursor.getString(SUMMARY_SNIPPET_DATA1_COLUMN_INDEX); if (!TextUtils.isEmpty(email)) { view.setSnippet(email); showSnippet = true; } } else if (Organization.CONTENT_ITEM_TYPE.equals(snippetMimeType)) { String company = cursor.getString(SUMMARY_SNIPPET_DATA1_COLUMN_INDEX); String title = cursor.getString(SUMMARY_SNIPPET_DATA4_COLUMN_INDEX); if (!TextUtils.isEmpty(company)) { if (!TextUtils.isEmpty(title)) { view.setSnippet(company + " / " + title); } else { view.setSnippet(company); } showSnippet = true; } else if (!TextUtils.isEmpty(title)) { view.setSnippet(title); showSnippet = true; } } else if (Nickname.CONTENT_ITEM_TYPE.equals(snippetMimeType)) { String nickname = cursor.getString(SUMMARY_SNIPPET_DATA1_COLUMN_INDEX); if (!TextUtils.isEmpty(nickname)) { view.setSnippet(nickname); showSnippet = true; } } if (!showSnippet) { view.setSnippet(null); } } if (!displayAdditionalData) { if (phoneticNameColumnIndex != -1) { // Set the name cursor.copyStringToBuffer(phoneticNameColumnIndex, cache.phoneticNameBuffer); int phoneticNameSize = cache.phoneticNameBuffer.sizeCopied; if (phoneticNameSize != 0) { view.setLabel(cache.phoneticNameBuffer.data, phoneticNameSize); } else { view.setLabel(null); } } else { view.setLabel(null); } return; } // Set the data. cursor.copyStringToBuffer(dataColumnIndex, cache.dataBuffer); size = cache.dataBuffer.sizeCopied; view.setData(cache.dataBuffer.data, size); // Set the label. if (!cursor.isNull(typeColumnIndex)) { final int type = cursor.getInt(typeColumnIndex); final String label = cursor.getString(labelColumnIndex); if (mMode == MODE_LEGACY_PICK_POSTAL || mMode == MODE_PICK_POSTAL) { // TODO cache view.setLabel(StructuredPostal.getTypeLabel(context.getResources(), type, label)); } else { // TODO cache view.setLabel(Phone.getTypeLabel(context.getResources(), type, label)); } } else { view.setLabel(null); } } /** * Computes the span of the display name that has highlighted parts and configures * the display name text view accordingly. */ private void buildDisplayNameWithHighlighting(TextView textView, Cursor cursor, CharArrayBuffer buffer1, CharArrayBuffer buffer2, TextWithHighlighting textWithHighlighting) { int oppositeDisplayOrderColumnIndex; if (mDisplayOrder == ContactsContract.Preferences.DISPLAY_ORDER_PRIMARY) { oppositeDisplayOrderColumnIndex = SUMMARY_DISPLAY_NAME_ALTERNATIVE_COLUMN_INDEX; } else { oppositeDisplayOrderColumnIndex = SUMMARY_DISPLAY_NAME_PRIMARY_COLUMN_INDEX; } cursor.copyStringToBuffer(oppositeDisplayOrderColumnIndex, buffer2); textWithHighlighting.setText(buffer1, buffer2); textView.setText(textWithHighlighting); } private void bindSectionHeader(View itemView, int position, boolean displaySectionHeaders) { final ContactListItemView view = (ContactListItemView)itemView; final ContactListItemCache cache = (ContactListItemCache) view.getTag(); if (!displaySectionHeaders) { view.setSectionHeader(null); view.setDividerVisible(true); } else { final int section = getSectionForPosition(position); if (getPositionForSection(section) == position) { String title = (String)mIndexer.getSections()[section]; view.setSectionHeader(title); } else { view.setDividerVisible(false); view.setSectionHeader(null); } // move the divider for the last item in a section if (getPositionForSection(section + 1) - 1 == position) { view.setDividerVisible(false); } else { view.setDividerVisible(true); } } } @Override public void changeCursor(Cursor cursor) { if (cursor != null) { setLoading(false); } // Get the split between starred and frequent items, if the mode is strequent mFrequentSeparatorPos = ListView.INVALID_POSITION; int cursorCount = 0; if (cursor != null && (cursorCount = cursor.getCount()) > 0 && mMode == MODE_STREQUENT) { cursor.move(-1); for (int i = 0; cursor.moveToNext(); i++) { int starred = cursor.getInt(SUMMARY_STARRED_COLUMN_INDEX); if (starred == 0) { if (i > 0) { // Only add the separator when there are starred items present mFrequentSeparatorPos = i; } break; } } } if (cursor != null && mSearchResultsMode) { TextView foundContactsText = (TextView)findViewById(R.id.search_results_found); String text = getQuantityText(cursor.getCount(), R.string.listFoundAllContactsZero, R.plurals.listFoundAllContacts); foundContactsText.setText(text); } super.changeCursor(cursor); // Update the indexer for the fast scroll widget updateIndexer(cursor); } private void updateIndexer(Cursor cursor) { if (cursor == null) { mIndexer = null; return; } Bundle bundle = cursor.getExtras(); if (bundle.containsKey(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_TITLES)) { String sections[] = bundle.getStringArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_TITLES); int counts[] = bundle.getIntArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_COUNTS); mIndexer = new ContactsSectionIndexer(sections, counts); } else { mIndexer = null; } } /** * Run the query on a helper thread. Beware that this code does not run * on the main UI thread! */ @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { return doFilter(constraint.toString()); } public Object [] getSections() { if (mIndexer == null) { return new String[] { " " }; } else { return mIndexer.getSections(); } } public int getPositionForSection(int sectionIndex) { if (mIndexer == null) { return -1; } return mIndexer.getPositionForSection(sectionIndex); } public int getSectionForPosition(int position) { if (mIndexer == null) { return -1; } return mIndexer.getSectionForPosition(position); } @Override public boolean areAllItemsEnabled() { return mMode != MODE_STARRED && !mShowNumberOfContacts && mSuggestionsCursorCount == 0; } @Override public boolean isEnabled(int position) { if (mShowNumberOfContacts) { if (position == 0) { return false; } position--; } if (mSuggestionsCursorCount > 0) { return position != 0 && position != mSuggestionsCursorCount + 1; } return position != mFrequentSeparatorPos; } @Override public int getCount() { if (!mDataValid) { return 0; } int superCount = super.getCount(); if (mShowNumberOfContacts && (mSearchMode || superCount > 0)) { // We don't want to count this header if it's the only thing visible, so that // the empty text will display. superCount++; } if (mSearchMode) { // Last element in the list is the "Find superCount++; } // We do not show the "Create New" button in Search mode if ((mMode & MODE_MASK_CREATE_NEW) != 0 && !mSearchMode) { // Count the "Create new contact" line superCount++; } if (mSuggestionsCursorCount != 0) { // When showing suggestions, we have 2 additional list items: the "Suggestions" // and "All contacts" headers. return mSuggestionsCursorCount + superCount + 2; } else if (mFrequentSeparatorPos != ListView.INVALID_POSITION) { // When showing strequent list, we have an additional list item - the separator. return superCount + 1; } else { return superCount; } } /** * Gets the actual count of contacts and excludes all the headers. */ public int getRealCount() { return super.getCount(); } private int getRealPosition(int pos) { if (mShowNumberOfContacts) { pos--; } if ((mMode & MODE_MASK_CREATE_NEW) != 0 && !mSearchMode) { return pos - 1; } else if (mSuggestionsCursorCount != 0) { // When showing suggestions, we have 2 additional list items: the "Suggestions" // and "All contacts" separators. if (pos < mSuggestionsCursorCount + 2) { // We are in the upper partition (Suggestions). Adjusting for the "Suggestions" // separator. return pos - 1; } else { // We are in the lower partition (All contacts). Adjusting for the size // of the upper partition plus the two separators. return pos - mSuggestionsCursorCount - 2; } } else if (mFrequentSeparatorPos == ListView.INVALID_POSITION) { // No separator, identity map return pos; } else if (pos <= mFrequentSeparatorPos) { // Before or at the separator, identity map return pos; } else { // After the separator, remove 1 from the pos to get the real underlying pos return pos - 1; } } @Override public Object getItem(int pos) { if (mSuggestionsCursorCount != 0 && pos <= mSuggestionsCursorCount) { mSuggestionsCursor.moveToPosition(getRealPosition(pos)); return mSuggestionsCursor; } else if (isSearchAllContactsItemPosition(pos)){ return null; } else { int realPosition = getRealPosition(pos); if (realPosition < 0) { return null; } return super.getItem(realPosition); } } @Override public long getItemId(int pos) { if (mSuggestionsCursorCount != 0 && pos < mSuggestionsCursorCount + 2) { if (mSuggestionsCursor.moveToPosition(pos - 1)) { return mSuggestionsCursor.getLong(mRowIDColumn); } else { return 0; } } else if (isSearchAllContactsItemPosition(pos)) { return 0; } int realPosition = getRealPosition(pos); if (realPosition < 0) { return 0; } return super.getItemId(realPosition); } public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (view instanceof PinnedHeaderListView) { ((PinnedHeaderListView)view).configureHeaderView(firstVisibleItem); } } public void onScrollStateChanged(AbsListView view, int scrollState) { if (mHighlightWhenScrolling) { if (scrollState != OnScrollListener.SCROLL_STATE_IDLE) { mHighlightingAnimation.startHighlighting(); } else { mHighlightingAnimation.stopHighlighting(); } } if (scrollState == OnScrollListener.SCROLL_STATE_FLING) { mPhotoLoader.pause(); } else if (mDisplayPhotos) { mPhotoLoader.resume(); } } /** * Computes the state of the pinned header. It can be invisible, fully * visible or partially pushed up out of the view. */ public int getPinnedHeaderState(int position) { if (mIndexer == null || mCursor == null || mCursor.getCount() == 0) { return PINNED_HEADER_GONE; } int realPosition = getRealPosition(position); if (realPosition < 0) { return PINNED_HEADER_GONE; } // The header should get pushed up if the top item shown // is the last item in a section for a particular letter. int section = getSectionForPosition(realPosition); int nextSectionPosition = getPositionForSection(section + 1); if (nextSectionPosition != -1 && realPosition == nextSectionPosition - 1) { return PINNED_HEADER_PUSHED_UP; } return PINNED_HEADER_VISIBLE; } /** * Configures the pinned header by setting the appropriate text label * and also adjusting color if necessary. The color needs to be * adjusted when the pinned header is being pushed up from the view. */ public void configurePinnedHeader(View header, int position, int alpha) { PinnedHeaderCache cache = (PinnedHeaderCache)header.getTag(); if (cache == null) { cache = new PinnedHeaderCache(); cache.titleView = (TextView)header.findViewById(R.id.header_text); cache.textColor = cache.titleView.getTextColors(); cache.background = header.getBackground(); header.setTag(cache); } int realPosition = getRealPosition(position); int section = getSectionForPosition(realPosition); String title = (String)mIndexer.getSections()[section]; cache.titleView.setText(title); if (alpha == 255) { // Opaque: use the default background, and the original text color header.setBackgroundDrawable(cache.background); cache.titleView.setTextColor(cache.textColor); } else { // Faded: use a solid color approximation of the background, and // a translucent text color header.setBackgroundColor(Color.rgb( Color.red(mPinnedHeaderBackgroundColor) * alpha / 255, Color.green(mPinnedHeaderBackgroundColor) * alpha / 255, Color.blue(mPinnedHeaderBackgroundColor) * alpha / 255)); int textColor = cache.textColor.getDefaultColor(); cache.titleView.setTextColor(Color.argb(alpha, Color.red(textColor), Color.green(textColor), Color.blue(textColor))); } } } }
false
true
protected void onCreate(Bundle icicle) { super.onCreate(icicle); mIconSize = getResources().getDimensionPixelSize(android.R.dimen.app_icon_size); mContactsPrefs = new ContactsPreferences(this); mPhotoLoader = new ContactPhotoLoader(this, R.drawable.ic_contact_list_picture); // Resolve the intent final Intent intent = getIntent(); // Allow the title to be set to a custom String using an extra on the intent String title = intent.getStringExtra(UI.TITLE_EXTRA_KEY); if (title != null) { setTitle(title); } String action = intent.getAction(); String component = intent.getComponent().getClassName(); // When we get a FILTER_CONTACTS_ACTION, it represents search in the context // of some other action. Let's retrieve the original action to provide proper // context for the search queries. if (UI.FILTER_CONTACTS_ACTION.equals(action)) { mSearchMode = true; mShowSearchSnippets = true; Bundle extras = intent.getExtras(); if (extras != null) { mInitialFilter = extras.getString(UI.FILTER_TEXT_EXTRA_KEY); String originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); if (originalAction != null) { action = originalAction; } String originalComponent = extras.getString(ContactsSearchManager.ORIGINAL_COMPONENT_EXTRA_KEY); if (originalComponent != null) { component = originalComponent; } } else { mInitialFilter = null; } } Log.i(TAG, "Called with action: " + action); mMode = MODE_UNKNOWN; if (UI.LIST_DEFAULT.equals(action) || UI.FILTER_CONTACTS_ACTION.equals(action)) { mMode = MODE_DEFAULT; // When mDefaultMode is true the mode is set in onResume(), since the preferneces // activity may change it whenever this activity isn't running } else if (UI.LIST_GROUP_ACTION.equals(action)) { mMode = MODE_GROUP; String groupName = intent.getStringExtra(UI.GROUP_NAME_EXTRA_KEY); if (TextUtils.isEmpty(groupName)) { finish(); return; } buildUserGroupUri(groupName); } else if (UI.LIST_ALL_CONTACTS_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = false; } else if (UI.LIST_STARRED_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STARRED; } else if (UI.LIST_FREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_FREQUENT; } else if (UI.LIST_STREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STREQUENT; } else if (UI.LIST_CONTACTS_WITH_PHONES_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = true; } else if (Intent.ACTION_PICK.equals(action)) { // XXX These should be showing the data from the URI given in // the Intent. final String type = intent.resolveType(this); if (Contacts.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_CONTACT; } else if (People.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PERSON; } else if (Phone.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } } else if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { if (component.equals("alias.DialShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_CALL; setTitle(R.string.callShortcutActivityTitle); } else if (component.equals("alias.MessageShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_SENDTO; setTitle(R.string.messageShortcutActivityTitle); } else if (mSearchMode) { mMode = MODE_PICK_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } else { mMode = MODE_PICK_OR_CREATE_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } } else if (Intent.ACTION_GET_CONTENT.equals(action)) { final String type = intent.resolveType(this); if (Contacts.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_PICK_OR_CREATE_CONTACT; } } else if (Phone.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } else if (People.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_LEGACY_PICK_PERSON; } else { mMode = MODE_LEGACY_PICK_OR_CREATE_PERSON; } } } else if (Intent.ACTION_INSERT_OR_EDIT.equals(action)) { mMode = MODE_INSERT_OR_EDIT_CONTACT; } else if (Intent.ACTION_SEARCH.equals(action)) { // See if the suggestion was clicked with a search action key (call button) if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG))) { String query = intent.getStringExtra(SearchManager.QUERY); if (!TextUtils.isEmpty(query)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", query, null)); startActivity(newIntent); } finish(); return; } // See if search request has extras to specify query if (intent.hasExtra(Insert.EMAIL)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_MAILTO; mInitialFilter = intent.getStringExtra(Insert.EMAIL); } else if (intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { // Otherwise handle the more normal search case mMode = MODE_QUERY; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; } else if (ACTION_SEARCH_INTERNAL.equals(action)) { String originalAction = null; Bundle extras = intent.getExtras(); if (extras != null) { originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); } mShortcutAction = intent.getStringExtra(SHORTCUT_ACTION_KEY); if (Intent.ACTION_INSERT_OR_EDIT.equals(originalAction)) { mMode = MODE_QUERY_PICK_TO_EDIT; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } else if (mShortcutAction != null && intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_PHONE; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { mMode = MODE_QUERY_PICK; mQueryMode = QUERY_MODE_NONE; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; // Since this is the filter activity it receives all intents // dispatched from the SearchManager for security reasons // so we need to re-dispatch from here to the intended target. } else if (Intents.SEARCH_SUGGESTION_CLICKED.equals(action)) { Uri data = intent.getData(); Uri telUri = null; if (sContactsIdMatcher.match(data) == CONTACTS_ID) { long contactId = Long.valueOf(data.getLastPathSegment()); final Cursor cursor = queryPhoneNumbers(contactId); if (cursor != null) { if (cursor.getCount() == 1 && cursor.moveToFirst()) { int phoneNumberIndex = cursor.getColumnIndex(Phone.NUMBER); String phoneNumber = cursor.getString(phoneNumberIndex); telUri = Uri.parse("tel:" + phoneNumber); } cursor.close(); } } // See if the suggestion was clicked with a search action key (call button) Intent newIntent; if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG)) && telUri != null) { newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, telUri); } else { newIntent = new Intent(Intent.ACTION_VIEW, data); } startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED.equals(action)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED.equals(action)) { // TODO actually support this in EditContactActivity. String number = intent.getData().getSchemeSpecificPart(); Intent newIntent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); newIntent.putExtra(Intents.Insert.PHONE, number); startActivity(newIntent); finish(); return; } if (JOIN_AGGREGATE.equals(action)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_JOIN_CONTACT; mQueryAggregateId = intent.getLongExtra(EXTRA_AGGREGATE_ID, -1); if (mQueryAggregateId == -1) { Log.e(TAG, "Intent " + action + " is missing required extra: " + EXTRA_AGGREGATE_ID); setResult(RESULT_CANCELED); finish(); } } } if (mMode == MODE_UNKNOWN) { mMode = MODE_DEFAULT; } if (((mMode & MODE_MASK_SHOW_NUMBER_OF_CONTACTS) != 0 || mSearchMode) && !mSearchResultsMode) { mShowNumberOfContacts = true; } if (mMode == MODE_JOIN_CONTACT) { setContentView(R.layout.contacts_list_content_join); TextView blurbView = (TextView)findViewById(R.id.join_contact_blurb); String blurb = getString(R.string.blurbJoinContactDataWith, getContactDisplayName(mQueryAggregateId)); blurbView.setText(blurb); mJoinModeShowAllContacts = true; } else if (mSearchMode) { setContentView(R.layout.contacts_search_content); } else if (mSearchResultsMode) { setContentView(R.layout.contacts_list_search_results); TextView titleText = (TextView)findViewById(R.id.search_results_for); titleText.setText(Html.fromHtml(getString(R.string.search_results_for, "<b>" + mInitialFilter + "</b>"))); } else { setContentView(R.layout.contacts_list_content); } setupListView(); if (mSearchMode) { setupSearchView(); } mQueryHandler = new QueryHandler(this); mJustCreated = true; mSyncEnabled = true; }
protected void onCreate(Bundle icicle) { super.onCreate(icicle); mIconSize = getResources().getDimensionPixelSize(android.R.dimen.app_icon_size); mContactsPrefs = new ContactsPreferences(this); mPhotoLoader = new ContactPhotoLoader(this, R.drawable.ic_contact_list_picture); // Resolve the intent final Intent intent = getIntent(); // Allow the title to be set to a custom String using an extra on the intent String title = intent.getStringExtra(UI.TITLE_EXTRA_KEY); if (title != null) { setTitle(title); } String action = intent.getAction(); String component = intent.getComponent().getClassName(); // When we get a FILTER_CONTACTS_ACTION, it represents search in the context // of some other action. Let's retrieve the original action to provide proper // context for the search queries. if (UI.FILTER_CONTACTS_ACTION.equals(action)) { mSearchMode = true; mShowSearchSnippets = true; Bundle extras = intent.getExtras(); if (extras != null) { mInitialFilter = extras.getString(UI.FILTER_TEXT_EXTRA_KEY); String originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); if (originalAction != null) { action = originalAction; } String originalComponent = extras.getString(ContactsSearchManager.ORIGINAL_COMPONENT_EXTRA_KEY); if (originalComponent != null) { component = originalComponent; } } else { mInitialFilter = null; } } Log.i(TAG, "Called with action: " + action); mMode = MODE_UNKNOWN; if (UI.LIST_DEFAULT.equals(action) || UI.FILTER_CONTACTS_ACTION.equals(action)) { mMode = MODE_DEFAULT; // When mDefaultMode is true the mode is set in onResume(), since the preferneces // activity may change it whenever this activity isn't running } else if (UI.LIST_GROUP_ACTION.equals(action)) { mMode = MODE_GROUP; String groupName = intent.getStringExtra(UI.GROUP_NAME_EXTRA_KEY); if (TextUtils.isEmpty(groupName)) { finish(); return; } buildUserGroupUri(groupName); } else if (UI.LIST_ALL_CONTACTS_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = false; } else if (UI.LIST_STARRED_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STARRED; } else if (UI.LIST_FREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_FREQUENT; } else if (UI.LIST_STREQUENT_ACTION.equals(action)) { mMode = mSearchMode ? MODE_DEFAULT : MODE_STREQUENT; } else if (UI.LIST_CONTACTS_WITH_PHONES_ACTION.equals(action)) { mMode = MODE_CUSTOM; mDisplayOnlyPhones = true; } else if (Intent.ACTION_PICK.equals(action)) { // XXX These should be showing the data from the URI given in // the Intent. final String type = intent.resolveType(this); if (Contacts.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_CONTACT; } else if (People.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PERSON; } else if (Phone.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } } else if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { if (component.equals("alias.DialShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_CALL; mShowSearchSnippets = false; setTitle(R.string.callShortcutActivityTitle); } else if (component.equals("alias.MessageShortcut")) { mMode = MODE_PICK_PHONE; mShortcutAction = Intent.ACTION_SENDTO; mShowSearchSnippets = false; setTitle(R.string.messageShortcutActivityTitle); } else if (mSearchMode) { mMode = MODE_PICK_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } else { mMode = MODE_PICK_OR_CREATE_CONTACT; mShortcutAction = Intent.ACTION_VIEW; setTitle(R.string.shortcutActivityTitle); } } else if (Intent.ACTION_GET_CONTENT.equals(action)) { final String type = intent.resolveType(this); if (Contacts.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_PICK_OR_CREATE_CONTACT; } } else if (Phone.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_PHONE; } else if (Phones.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_PHONE; } else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(type)) { mMode = MODE_PICK_POSTAL; } else if (ContactMethods.CONTENT_POSTAL_ITEM_TYPE.equals(type)) { mMode = MODE_LEGACY_PICK_POSTAL; } else if (People.CONTENT_ITEM_TYPE.equals(type)) { if (mSearchMode) { mMode = MODE_LEGACY_PICK_PERSON; } else { mMode = MODE_LEGACY_PICK_OR_CREATE_PERSON; } } } else if (Intent.ACTION_INSERT_OR_EDIT.equals(action)) { mMode = MODE_INSERT_OR_EDIT_CONTACT; } else if (Intent.ACTION_SEARCH.equals(action)) { // See if the suggestion was clicked with a search action key (call button) if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG))) { String query = intent.getStringExtra(SearchManager.QUERY); if (!TextUtils.isEmpty(query)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, Uri.fromParts("tel", query, null)); startActivity(newIntent); } finish(); return; } // See if search request has extras to specify query if (intent.hasExtra(Insert.EMAIL)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_MAILTO; mInitialFilter = intent.getStringExtra(Insert.EMAIL); } else if (intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_TO_VIEW; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { // Otherwise handle the more normal search case mMode = MODE_QUERY; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; } else if (ACTION_SEARCH_INTERNAL.equals(action)) { String originalAction = null; Bundle extras = intent.getExtras(); if (extras != null) { originalAction = extras.getString(ContactsSearchManager.ORIGINAL_ACTION_EXTRA_KEY); } mShortcutAction = intent.getStringExtra(SHORTCUT_ACTION_KEY); if (Intent.ACTION_INSERT_OR_EDIT.equals(originalAction)) { mMode = MODE_QUERY_PICK_TO_EDIT; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } else if (mShortcutAction != null && intent.hasExtra(Insert.PHONE)) { mMode = MODE_QUERY_PICK_PHONE; mQueryMode = QUERY_MODE_TEL; mInitialFilter = intent.getStringExtra(Insert.PHONE); } else { mMode = MODE_QUERY_PICK; mQueryMode = QUERY_MODE_NONE; mShowSearchSnippets = true; mInitialFilter = getIntent().getStringExtra(SearchManager.QUERY); } mSearchResultsMode = true; // Since this is the filter activity it receives all intents // dispatched from the SearchManager for security reasons // so we need to re-dispatch from here to the intended target. } else if (Intents.SEARCH_SUGGESTION_CLICKED.equals(action)) { Uri data = intent.getData(); Uri telUri = null; if (sContactsIdMatcher.match(data) == CONTACTS_ID) { long contactId = Long.valueOf(data.getLastPathSegment()); final Cursor cursor = queryPhoneNumbers(contactId); if (cursor != null) { if (cursor.getCount() == 1 && cursor.moveToFirst()) { int phoneNumberIndex = cursor.getColumnIndex(Phone.NUMBER); String phoneNumber = cursor.getString(phoneNumberIndex); telUri = Uri.parse("tel:" + phoneNumber); } cursor.close(); } } // See if the suggestion was clicked with a search action key (call button) Intent newIntent; if ("call".equals(intent.getStringExtra(SearchManager.ACTION_MSG)) && telUri != null) { newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, telUri); } else { newIntent = new Intent(Intent.ACTION_VIEW, data); } startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED.equals(action)) { Intent newIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData()); startActivity(newIntent); finish(); return; } else if (Intents.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED.equals(action)) { // TODO actually support this in EditContactActivity. String number = intent.getData().getSchemeSpecificPart(); Intent newIntent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI); newIntent.putExtra(Intents.Insert.PHONE, number); startActivity(newIntent); finish(); return; } if (JOIN_AGGREGATE.equals(action)) { if (mSearchMode) { mMode = MODE_PICK_CONTACT; } else { mMode = MODE_JOIN_CONTACT; mQueryAggregateId = intent.getLongExtra(EXTRA_AGGREGATE_ID, -1); if (mQueryAggregateId == -1) { Log.e(TAG, "Intent " + action + " is missing required extra: " + EXTRA_AGGREGATE_ID); setResult(RESULT_CANCELED); finish(); } } } if (mMode == MODE_UNKNOWN) { mMode = MODE_DEFAULT; } if (((mMode & MODE_MASK_SHOW_NUMBER_OF_CONTACTS) != 0 || mSearchMode) && !mSearchResultsMode) { mShowNumberOfContacts = true; } if (mMode == MODE_JOIN_CONTACT) { setContentView(R.layout.contacts_list_content_join); TextView blurbView = (TextView)findViewById(R.id.join_contact_blurb); String blurb = getString(R.string.blurbJoinContactDataWith, getContactDisplayName(mQueryAggregateId)); blurbView.setText(blurb); mJoinModeShowAllContacts = true; } else if (mSearchMode) { setContentView(R.layout.contacts_search_content); } else if (mSearchResultsMode) { setContentView(R.layout.contacts_list_search_results); TextView titleText = (TextView)findViewById(R.id.search_results_for); titleText.setText(Html.fromHtml(getString(R.string.search_results_for, "<b>" + mInitialFilter + "</b>"))); } else { setContentView(R.layout.contacts_list_content); } setupListView(); if (mSearchMode) { setupSearchView(); } mQueryHandler = new QueryHandler(this); mJustCreated = true; mSyncEnabled = true; }
diff --git a/org.maven.ide.eclipse.editor.tests/src/org/maven/ide/eclipse/editor/pom/PomEditorTest.java b/org.maven.ide.eclipse.editor.tests/src/org/maven/ide/eclipse/editor/pom/PomEditorTest.java index 96a80d21..890e83f7 100644 --- a/org.maven.ide.eclipse.editor.tests/src/org/maven/ide/eclipse/editor/pom/PomEditorTest.java +++ b/org.maven.ide.eclipse.editor.tests/src/org/maven/ide/eclipse/editor/pom/PomEditorTest.java @@ -1,382 +1,382 @@ /******************************************************************************* * Copyright (c) 2008 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.maven.ide.eclipse.editor.pom; import java.io.File; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Label; import com.windowtester.runtime.WT; import com.windowtester.runtime.swt.condition.SWTIdleCondition; import com.windowtester.runtime.swt.condition.eclipse.FileExistsCondition; import com.windowtester.runtime.swt.condition.shell.ShellDisposedCondition; import com.windowtester.runtime.swt.condition.shell.ShellShowingCondition; import com.windowtester.runtime.swt.internal.condition.NotCondition; import com.windowtester.runtime.swt.internal.condition.eclipse.DirtyEditorCondition; import com.windowtester.runtime.swt.locator.ButtonLocator; import com.windowtester.runtime.swt.locator.CTabItemLocator; import com.windowtester.runtime.swt.locator.NamedWidgetLocator; import com.windowtester.runtime.swt.locator.SWTWidgetLocator; import com.windowtester.runtime.swt.locator.TableItemLocator; import com.windowtester.runtime.swt.locator.TreeItemLocator; import com.windowtester.runtime.swt.locator.eclipse.ViewLocator; import com.windowtester.runtime.util.ScreenCapture; /** * @author Eugene Kuleshov * @author Anton Kraev */ public class PomEditorTest extends PomEditorTestBase { public void testUpdatingArtifactIdInXmlPropagatedToForm() throws Exception { openPomFile(TEST_POM_POM_XML); selectEditorTab(TAB_POM_XML); replaceText("test-pom", "test-pom1"); selectEditorTab(TAB_OVERVIEW); assertTextValue("artifactId", "test-pom1"); } public void testFormToXmlAndXmlToFormInParentArtifactId() throws Exception { openPomFile(TEST_POM_POM_XML); // test FORM->XML and XML->FORM update of parentArtifactId selectEditorTab(TAB_OVERVIEW); getUI().click(new SWTWidgetLocator(Label.class, "Parent")); setTextValue("parentArtifactId", "parent2"); selectEditorTab(TAB_POM_XML); replaceText("parent2", "parent3"); selectEditorTab(TAB_OVERVIEW); assertTextValue("parentArtifactId", "parent3"); } public void testNewSectionCreation() throws Exception { openPomFile(TEST_POM_POM_XML); ScreenCapture.createScreenCapture(); ScreenCapture.createScreenCapture(); expandSectionIfRequired("organizationSection", "Organization"); ScreenCapture.createScreenCapture(); getUI().click(new NamedWidgetLocator("organizationName")); ScreenCapture.createScreenCapture(); getUI().enterText("org.foo"); ScreenCapture.createScreenCapture(); selectEditorTab(TAB_POM_XML); replaceText("org.foo", "orgfoo1"); selectEditorTab(TAB_OVERVIEW); assertTextValue("organizationName", "orgfoo1"); } public void testUndoRedo() throws Exception { openPomFile(TEST_POM_POM_XML); getUI().click(new NamedWidgetLocator("organizationName")); getUI().keyClick(SWT.CTRL, 'a'); getUI().enterText("orgfoo"); getUI().click(new NamedWidgetLocator("organizationUrl")); getUI().click(new NamedWidgetLocator("organizationName")); getUI().keyClick(SWT.CTRL, 'a'); getUI().enterText("orgfoo1"); // test undo getUI().keyClick(SWT.CTRL, 'z'); assertTextValue("organizationName", "orgfoo"); // test redo getUI().keyClick(SWT.CTRL, 'y'); assertTextValue("organizationName", "orgfoo1"); } public void testDeletingScmSectionInXmlPropagatedToForm() throws Exception { openPomFile(TEST_POM_POM_XML); selectEditorTab(TAB_OVERVIEW); getUI().click(new SWTWidgetLocator(Label.class, "SCM")); // XXX can't use "." in the url due to issue on Linux in WindowTester setTextValue("scmUrl", "http://m2eclipse"); assertTextValue("scmUrl", "http://m2eclipse"); selectEditorTab(TAB_POM_XML); delete("<scm>", "</scm>"); selectEditorTab(TAB_OVERVIEW); getUI().wait(new SWTIdleCondition()); assertTextValue("scmUrl", ""); selectEditorTab(TAB_POM_XML); delete("<organization>", "</organization>"); selectEditorTab(TAB_OVERVIEW); assertTextValue("organizationName", ""); setTextValue("scmUrl", "http://m2eclipse"); assertTextValue("scmUrl", "http://m2eclipse"); } public void testExternalModificationEditorClean() throws Exception { openPomFile(TEST_POM_POM_XML); // externally replace file contents IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile file = root.getFile(new Path(TEST_POM_POM_XML)); File f = new File(file.getLocation().toOSString()); String text = getContents(f); setContents(f, text.replace("parent3", "parent4")); // reload the file getUI().click(new CTabItemLocator("Package Explorer")); getUI().click(new CTabItemLocator(TEST_POM_POM_XML)); getUI().wait(new ShellShowingCondition("File Changed")); getUI().click(new ButtonLocator("&Yes")); assertTextValue("parentArtifactId", "parent4"); // verify that value changed in xml and in the form selectEditorTab(TAB_POM_XML); String editorText = getEditorText(); assertTrue(editorText, editorText.contains("<artifactId>parent4</artifactId>")); // XXX verify that value changed on a page haven't been active before } // test that form and xml is not updated when refused to pickup external changes // public void testExternalModificationNotUpdate() throws Exception { // // XXX test that form and xml are not updated when refused to pickup external changes // } // XXX update for new modification code public void testExternalModificationEditorDirty() throws Exception { openPomFile(TEST_POM_POM_XML); // make editor dirty getUI().click(new CTabItemLocator(TEST_POM_POM_XML)); selectEditorTab(TAB_POM_XML); replaceText("parent4", "parent5"); selectEditorTab(TAB_OVERVIEW); // externally replace file contents IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(TEST_POM_POM_XML)); File f = new File(file.getLocation().toOSString()); String text = getContents(f); setContents(f, text.replace("parent4", "parent6")); // reload the file getUI().click(new CTabItemLocator("Package Explorer")); getUI().keyClick(SWT.F12); getUI().wait(new ShellShowingCondition("File Changed")); getUI().click(new ButtonLocator("&Yes")); assertTextValue("parentArtifactId", "parent6"); // verify that value changed in xml and in the form selectEditorTab(TAB_POM_XML); String editorText = getEditorText(); assertTrue(editorText, editorText.contains("<artifactId>parent6</artifactId>")); // XXX verify that value changed on a page haven't been active before } public void testNewEditorIsClean() throws Exception { openPomFile(TEST_POM_POM_XML); // close/open the file getUI().close(new CTabItemLocator(TEST_POM_POM_XML)); // ui.click(2, new TreeItemLocator(TEST_POM_POM_XML, new ViewLocator("org.eclipse.jdt.ui.PackageExplorer"))); openPomFile(TEST_POM_POM_XML); // test the editor is clean getUI().assertThat(new NotCondition(new DirtyEditorCondition())); } //MNGECLIPSE-874 public void testUndoAfterSave() throws Exception { openPomFile(TEST_POM_POM_XML); // make a change getUI().click(new CTabItemLocator(TEST_POM_POM_XML)); selectEditorTab(TAB_POM_XML); replaceText("parent6", "parent7"); selectEditorTab(TAB_OVERVIEW); //save file getUI().keyClick(SWT.CTRL, 's'); // test the editor is clean getUI().assertThat(new NotCondition(new DirtyEditorCondition())); // undo change getUI().keyClick(SWT.CTRL, 'z'); // test the editor is dirty getUI().assertThat(new DirtyEditorCondition()); //test the value assertTextValue("parentArtifactId", "parent6"); //save file //ui.keyClick(SWT.CTRL, 's'); } public void testAfterUndoEditorIsClean() throws Exception { openPomFile(TEST_POM_POM_XML); // make a change getUI().click(new CTabItemLocator(TEST_POM_POM_XML)); selectEditorTab(TAB_POM_XML); replaceText("parent6", "parent7"); selectEditorTab(TAB_OVERVIEW); // undo change getUI().keyClick(SWT.CTRL, 'z'); // test the editor is clean getUI().assertThat(new NotCondition(new DirtyEditorCondition())); } public void testEmptyFile() throws Exception { String name = PROJECT_NAME + "/test.pom"; createFile(name, ""); openPomFile(name); assertTextValue("artifactId", ""); setTextValue("artifactId", "artf1"); selectEditorTab(TAB_POM_XML); replaceText("artf1", "artf2"); selectEditorTab(TAB_OVERVIEW); assertTextValue("artifactId", "artf2"); } public void testDiscardedFileDeletion() throws Exception { String name = PROJECT_NAME + "/another.pom"; createFile(name, ""); openPomFile(name); // ui.contextClick(new TreeItemLocator(PROJECT_NAME, new ViewLocator( // "org.eclipse.jdt.ui.PackageExplorer")), "New/File"); // ui.wait(new ShellShowingCondition("New File")); // ui.enterText("another.pom"); // ui.click(new ButtonLocator("&Finish")); // // ui.keyClick(WT.CR); // ui.wait(new ShellDisposedCondition("Progress Information")); // ui.wait(new ShellDisposedCondition("New File")); getUI().keyClick(SWT.CTRL, 's'); getUI().close(new CTabItemLocator(name)); - // getUI().click(2, new TreeItemLocator(name, new ViewLocator("org.eclipse.jdt.getUI().PackageExplorer"))); + // getUI().click(2, new TreeItemLocator(name, new ViewLocator("org.eclipse.jdt.ui.PackageExplorer"))); openPomFile(name); getUI().click(new NamedWidgetLocator("groupId")); getUI().enterText("1"); getUI().close(new CTabItemLocator("*" + name)); getUI().wait(new ShellDisposedCondition("Progress Information")); getUI().wait(new ShellShowingCondition("Save Resource")); getUI().click(new ButtonLocator("&No")); ScreenCapture.createScreenCapture(); - getUI().click(new TreeItemLocator(PROJECT_NAME, new ViewLocator("org.eclipse.jdt.getUI().PackageExplorer"))); + getUI().click(new TreeItemLocator(PROJECT_NAME, new ViewLocator("org.eclipse.jdt.ui.PackageExplorer"))); ScreenCapture.createScreenCapture(); getUI().contextClick(new TreeItemLocator(name, // - new ViewLocator("org.eclipse.jdt.getUI().PackageExplorer")), "Delete"); + new ViewLocator("org.eclipse.jdt.ui.PackageExplorer")), "Delete"); ScreenCapture.createScreenCapture(); getUI().wait(new ShellDisposedCondition("Progress Information")); getUI().wait(new ShellShowingCondition("Confirm Delete")); getUI().keyClick(WT.CR); IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(name)); getUI().wait(new FileExistsCondition(file, false)); } // MNGECLIPSE-833 public void testSaveAfterPaste() throws Exception { String name = PROJECT_NAME + "/another2.pom"; String str = "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" " // + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " // + "xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">" // + "<modelVersion>4.0.0</modelVersion>" // + "<groupId>test</groupId>" // + "<artifactId>parent</artifactId>" // + "<packaging>pom</packaging>" // + "<version>0.0.1-SNAPSHOT</version>" // + "</project>"; createFile(name, str); // IFile file = root.getFile(new Path(name)); // file.create(new ByteArrayInputStream(str.getBytes()), true, null); openPomFile(name); selectEditorTab(TAB_POM_XML); getUI().wait(new NotCondition(new DirtyEditorCondition())); findText("</project>"); getUI().keyClick(WT.ARROW_LEFT); putIntoClipboard("<properties><sample>sample</sample></properties>"); getUI().keyClick(SWT.CTRL, 'v'); getUI().wait(new DirtyEditorCondition()); getUI().keyClick(SWT.CTRL, 's'); getUI().wait(new NotCondition(new DirtyEditorCondition())); getUI().keyClick(SWT.CTRL, 'w'); } // MNGECLIPSE-835 public void testModulesEditorActivation() throws Exception { openPomFile(TEST_POM_POM_XML); getUI().keyClick(SWT.CTRL, 'm'); getUI().click(new SWTWidgetLocator(Label.class, "Parent")); // getUI().click(new SWTWidgetLocator(Label.class, "Properties")); selectEditorTab(TAB_OVERVIEW); ScreenCapture.createScreenCapture(); getUI().click(new ButtonLocator("Add...")); ScreenCapture.createScreenCapture(); getUI().click(new TableItemLocator("?")); ScreenCapture.createScreenCapture(); getUI().enterText("foo1"); getUI().keyClick(WT.CR); getUI().keyClick(WT.CR); getUI().click(new ButtonLocator("Add...")); getUI().click(new TableItemLocator("?")); getUI().enterText("foo2"); getUI().keyClick(WT.CR); getUI().keyClick(WT.CR); // save getUI().keyClick(SWT.CTRL, 's'); getUI().click(new TableItemLocator("foo1")); getUI().click(new TableItemLocator("foo2")); getUI().keyClick(SWT.CTRL, 'm'); // test the editor is clean getUI().assertThat(new NotCondition(new DirtyEditorCondition())); } }
false
true
public void testDiscardedFileDeletion() throws Exception { String name = PROJECT_NAME + "/another.pom"; createFile(name, ""); openPomFile(name); // ui.contextClick(new TreeItemLocator(PROJECT_NAME, new ViewLocator( // "org.eclipse.jdt.ui.PackageExplorer")), "New/File"); // ui.wait(new ShellShowingCondition("New File")); // ui.enterText("another.pom"); // ui.click(new ButtonLocator("&Finish")); // // ui.keyClick(WT.CR); // ui.wait(new ShellDisposedCondition("Progress Information")); // ui.wait(new ShellDisposedCondition("New File")); getUI().keyClick(SWT.CTRL, 's'); getUI().close(new CTabItemLocator(name)); // getUI().click(2, new TreeItemLocator(name, new ViewLocator("org.eclipse.jdt.getUI().PackageExplorer"))); openPomFile(name); getUI().click(new NamedWidgetLocator("groupId")); getUI().enterText("1"); getUI().close(new CTabItemLocator("*" + name)); getUI().wait(new ShellDisposedCondition("Progress Information")); getUI().wait(new ShellShowingCondition("Save Resource")); getUI().click(new ButtonLocator("&No")); ScreenCapture.createScreenCapture(); getUI().click(new TreeItemLocator(PROJECT_NAME, new ViewLocator("org.eclipse.jdt.getUI().PackageExplorer"))); ScreenCapture.createScreenCapture(); getUI().contextClick(new TreeItemLocator(name, // new ViewLocator("org.eclipse.jdt.getUI().PackageExplorer")), "Delete"); ScreenCapture.createScreenCapture(); getUI().wait(new ShellDisposedCondition("Progress Information")); getUI().wait(new ShellShowingCondition("Confirm Delete")); getUI().keyClick(WT.CR); IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(name)); getUI().wait(new FileExistsCondition(file, false)); }
public void testDiscardedFileDeletion() throws Exception { String name = PROJECT_NAME + "/another.pom"; createFile(name, ""); openPomFile(name); // ui.contextClick(new TreeItemLocator(PROJECT_NAME, new ViewLocator( // "org.eclipse.jdt.ui.PackageExplorer")), "New/File"); // ui.wait(new ShellShowingCondition("New File")); // ui.enterText("another.pom"); // ui.click(new ButtonLocator("&Finish")); // // ui.keyClick(WT.CR); // ui.wait(new ShellDisposedCondition("Progress Information")); // ui.wait(new ShellDisposedCondition("New File")); getUI().keyClick(SWT.CTRL, 's'); getUI().close(new CTabItemLocator(name)); // getUI().click(2, new TreeItemLocator(name, new ViewLocator("org.eclipse.jdt.ui.PackageExplorer"))); openPomFile(name); getUI().click(new NamedWidgetLocator("groupId")); getUI().enterText("1"); getUI().close(new CTabItemLocator("*" + name)); getUI().wait(new ShellDisposedCondition("Progress Information")); getUI().wait(new ShellShowingCondition("Save Resource")); getUI().click(new ButtonLocator("&No")); ScreenCapture.createScreenCapture(); getUI().click(new TreeItemLocator(PROJECT_NAME, new ViewLocator("org.eclipse.jdt.ui.PackageExplorer"))); ScreenCapture.createScreenCapture(); getUI().contextClick(new TreeItemLocator(name, // new ViewLocator("org.eclipse.jdt.ui.PackageExplorer")), "Delete"); ScreenCapture.createScreenCapture(); getUI().wait(new ShellDisposedCondition("Progress Information")); getUI().wait(new ShellShowingCondition("Confirm Delete")); getUI().keyClick(WT.CR); IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(name)); getUI().wait(new FileExistsCondition(file, false)); }
diff --git a/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/Conversions.java b/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/Conversions.java index c9af08f15..9546d29f2 100644 --- a/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/Conversions.java +++ b/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/Conversions.java @@ -1,855 +1,857 @@ /******************************************************************************* * Copyright (c) 2004, 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 - Initial API and implementation * Markus Schorn (Wind River Systems) * Bryan Wilkinson (QNX) * Andrew Ferguson (Symbian) * Sergey Prigogin (Google) *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.parser.cpp.semantics; import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getUltimateType; import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getUltimateTypeViaTypedefs; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ast.DOMException; import org.eclipse.cdt.core.dom.ast.IASTExpression; import org.eclipse.cdt.core.dom.ast.IASTLiteralExpression; import org.eclipse.cdt.core.dom.ast.IArrayType; import org.eclipse.cdt.core.dom.ast.IBasicType; import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.dom.ast.IEnumeration; import org.eclipse.cdt.core.dom.ast.IFunctionType; import org.eclipse.cdt.core.dom.ast.IPointerType; import org.eclipse.cdt.core.dom.ast.IProblemBinding; import org.eclipse.cdt.core.dom.ast.IQualifierType; import org.eclipse.cdt.core.dom.ast.IType; import org.eclipse.cdt.core.dom.ast.ITypedef; import org.eclipse.cdt.core.dom.ast.cpp.ICPPBase; import org.eclipse.cdt.core.dom.ast.cpp.ICPPBasicType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPConstructor; import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod; import org.eclipse.cdt.core.dom.ast.cpp.ICPPPointerToMemberType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPReferenceType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPSpecialization; import org.eclipse.cdt.core.dom.ast.cpp.ICPPTemplateTemplateParameter; import org.eclipse.cdt.core.dom.ast.cpp.ICPPTemplateTypeParameter; import org.eclipse.cdt.internal.core.dom.parser.ITypeContainer; import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPPointerType; import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPDeferredClassInstance; import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPInternalBinding; import org.eclipse.cdt.internal.core.index.IIndexFragmentBinding; import org.eclipse.core.runtime.CoreException; /** * Routines for calculating the cost of conversions. */ public class Conversions { /** * Computes the cost of an implicit conversion sequence * [over.best.ics] 13.3.3.1 * * @param allowUDC whether a user-defined conversion is allowed during the sequence * @param sourceExp the expression behind the source type * @param source the source (argument) type * @param target the target (parameter) type * @param isImpliedObject * @return the cost of converting from source to target * @throws DOMException */ public static Cost checkImplicitConversionSequence(boolean allowUDC, IASTExpression sourceExp, IType source, IType target, boolean isImpliedObject) throws DOMException { Cost cost; allowUDC &= !isImpliedObject; + target= getUltimateTypeViaTypedefs(target); + source= getUltimateTypeViaTypedefs(source); if (target instanceof ICPPReferenceType) { // [13.3.3.3.1] Reference binding - IType cv1T1= ((ICPPReferenceType)target).getType(); + IType cv1T1= getUltimateTypeViaTypedefs(((ICPPReferenceType)target).getType()); cost= new Cost(source, cv1T1); cost.targetHadReference= true; boolean lvalue= sourceExp == null || !CPPVisitor.isRValue(sourceExp); - IType T2= source instanceof IQualifierType ? ((IQualifierType)source).getType() : source; + IType T2= source instanceof IQualifierType ? getUltimateTypeViaTypedefs(((IQualifierType)source).getType()) : source; if (lvalue && isReferenceCompatible(cv1T1, source)) { /* Direct reference binding */ // [13.3.3.1.4] if (cost.source.isSameType(cost.target) || // 7.3.3.13 for overload resolution the implicit this pointer is treated as if // it were a pointer to the derived class (isImpliedObject && cost.source instanceof ICPPClassType && cost.target instanceof ICPPClassType)) { cost.rank = Cost.IDENTITY_RANK; return cost; } /* * is an lvalue (but is not a bit-field), and "cv1 T1" is reference-compatible with "cv2 T2," */ // [13.3.3.1.4-1] direct binding // [8.5.3-5] qualificationConversion(cost); derivedToBaseConversion(cost); } else if (T2 instanceof ICPPClassType) { if(allowUDC) { /* * or has a class type (i.e., T2 is a class type) and can be implicitly converted to * an lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible with "cv3 T3" 92) * (this conversion is selected by enumerating the applicable conversion functions (13.3.1.6) * and choosing the best one through overload resolution (13.3)). */ ICPPMethod[] fcns= SemanticUtil.getConversionOperators((ICPPClassType)T2); Cost operatorCost= null; ICPPMethod conv= null; boolean ambiguousConversionOperator= false; if (fcns.length > 0 && fcns[0] instanceof IProblemBinding == false) { for (final ICPPMethod op : fcns) { Cost cost2 = checkStandardConversionSequence(op.getType().getReturnType(), target, false); if (cost2.rank != Cost.NO_MATCH_RANK) { if (operatorCost == null) { operatorCost= cost2; conv= op; } else { int cmp= operatorCost.compare(cost2); if (cmp >= 0) { ambiguousConversionOperator= cmp == 0; operatorCost= cost2; conv= op; } } } } } if (conv!= null && !ambiguousConversionOperator) { IType newSource= conv.getType().getReturnType(); boolean isNewSourceLValue= newSource instanceof ICPPReferenceType; if (isNewSourceLValue && isReferenceCompatible(cv1T1, newSource)) { cost= new Cost(cv1T1, newSource); qualificationConversion(cost); derivedToBaseConversion(cost); } } } } /* Direct binding failed */ if (cost.rank == Cost.NO_MATCH_RANK) { // 8.5.3-5 - Otherwise boolean cv1isConst= false; if (cv1T1 instanceof IQualifierType) { cv1isConst= ((IQualifierType)cv1T1).isConst() && !((IQualifierType)cv1T1).isVolatile(); } else if (cv1T1 instanceof IPointerType) { cv1isConst= ((IPointerType)cv1T1).isConst() && !((IPointerType)cv1T1).isVolatile(); } if (cv1isConst) { if (!lvalue && source instanceof ICPPClassType) { cost= new Cost(source, target); cost.rank= Cost.IDENTITY_RANK; } else { // 5 - Otherwise // Otherwise, a temporary of type "cv1 T1" is created and initialized from the initializer expression // using the rules for a non-reference copy initialization (8.5). The reference is then bound to the temporary. // If T1 is reference-related to T2, cv1 must be the same cv-qualification as, or greater cvqualification // than, cv2; otherwise, the program is ill-formed. [Example boolean illformed= false; if (isReferenceRelated(cv1T1, source)) { Integer cmp= compareQualifications(cv1T1, source); if (cmp == null || cmp < 0) { illformed= true; } } // we must do a non-reference initialization if (!illformed) { cost= checkStandardConversionSequence(source, cv1T1, isImpliedObject); // 12.3-4 At most one user-defined conversion is implicitly applied to // a single value. (also prevents infinite loop) if (allowUDC && (cost.rank == Cost.NO_MATCH_RANK || cost.rank == Cost.FUZZY_TEMPLATE_PARAMETERS)) { Cost temp = checkUserDefinedConversionSequence(source, cv1T1); if (temp != null) { cost = temp; } } } } } } } else { // Non-reference binding cost= checkStandardConversionSequence(source, target, isImpliedObject); if (allowUDC && (cost.rank == Cost.NO_MATCH_RANK || cost.rank == Cost.FUZZY_TEMPLATE_PARAMETERS)) { Cost temp = checkUserDefinedConversionSequence(source, target); if (temp != null) { cost = temp; } } } return cost; } /** * [3.9.3-4] Implements cv-ness (partial) comparison. There is a (partial) * ordering on cv-qualifiers, so that a type can be said to be more * cv-qualified than another. * @param cv1 * @param cv2 * @return <ul> * <li>GT 1 if cv1 is more qualified than cv2 * <li>EQ 0 if cv1 and cv2 are equally qualified * <li>LT -1 if cv1 is less qualified than cv2 * <li>NC null if cv1 and cv2 are not comparable * </ul> * @throws DOMException */ private static final Integer compareQualifications(IType cv1, IType cv2) throws DOMException { boolean cv1Const= false, cv2Const= false, cv1Volatile= false, cv2Volatile= false; if (cv1 instanceof IQualifierType) { IQualifierType qt1= (IQualifierType) cv1; cv1Const= qt1.isConst(); cv1Volatile= qt1.isVolatile(); } else if (cv1 instanceof IPointerType) { IPointerType pt1= (IPointerType) cv1; cv1Const= pt1.isConst(); cv1Volatile= pt1.isVolatile(); } if (cv2 instanceof IQualifierType) { IQualifierType qt2= (IQualifierType) cv2; cv2Const= qt2.isConst(); cv2Volatile= qt2.isVolatile(); } else if (cv2 instanceof IPointerType) { IPointerType pt2= (IPointerType) cv2; cv1Const= pt2.isConst(); cv1Volatile= pt2.isVolatile(); } int cmpConst= cv1Const ? (cv2Const ? 0 : 1) : (!cv2Const ? 0 : -1); int cmpVolatile= cv1Volatile ? (cv2Volatile ? 0 : 1) : (!cv2Volatile ? 0 : -1); if (cmpConst == cmpVolatile) { return cmpConst; } else if (cmpConst != 0 && cmpVolatile == 0) { return cmpConst; } else if (cmpConst == 0 && cmpVolatile != 0) { return cmpVolatile; } return null; } /** * [8.5.3] "cv1 T1" is reference-related to "cv2 T2" if T1 is the same type as T2, or T1 is a base class of T2. * Note this is not a symmetric relation. * @param cv1t1 * @param cv2t2 * @return whether <code>cv1t1</code> is reference-related to <code>cv2t2</code> * @throws DOMException */ private static final boolean isReferenceRelated(IType cv1t1, IType cv2t2) throws DOMException { // I've not found anything in the spec to justify unrolling cv1t1 or cv1t2 so far IType t1= SemanticUtil.getUltimateTypeUptoPointers(cv1t1); IType t2= SemanticUtil.getUltimateTypeUptoPointers(cv2t2); // The way cv-qualification is currently modeled means // we must cope with IPointerType objects separately. if (t1 instanceof IPointerType && t2 instanceof IPointerType) { IType ptt1= ((IPointerType)t1).getType(); IType ptt2= ((IPointerType)t2).getType(); return ptt1 != null && ptt2 != null ? ptt1.isSameType(ptt2) : ptt1 == ptt2; } t1= t1 instanceof IQualifierType ? ((IQualifierType)t1).getType() : t1; t2= t2 instanceof IQualifierType ? ((IQualifierType)t2).getType() : t2; if (t1 instanceof ICPPClassType && t2 instanceof ICPPClassType) { return calculateInheritanceDepth(CPPSemantics.MAX_INHERITANCE_DEPTH, t2, t1) >= 0; } return t1 != null && t2 != null ? t1.isSameType(t2) : t1 == t2; } /** * [8.5.3] "cv1 T1" is reference-compatible with "cv2 T2" if T1 is reference-related * to T2 and cv1 is the same cv-qualification as, or greater cv-qualification than, cv2. * Note this is not a symmetric relation. * @param cv1t1 * @param cv2t2 * @return whether <code>cv1t1</code> is reference-compatible with <code>cv2t2</code> * @throws DOMException */ private static final boolean isReferenceCompatible(IType cv1t1, IType cv2t2) throws DOMException { if (isReferenceRelated(cv1t1, cv2t2)) { Integer cmp= compareQualifications(cv1t1, cv2t2); return cmp != null && cmp >= 0; } return false; } /** * [4] Standard Conversions * Computes the cost of using the standard conversion sequence from source to target. * @param isImplicitThis handles the special case when members of different * classes are nominated via using-declarations. In such a situation the derived to * base conversion does not cause any costs. * @throws DOMException */ protected static final Cost checkStandardConversionSequence(IType source, IType target, boolean isImplicitThis) throws DOMException { Cost cost = lvalue_to_rvalue(source, target); if (cost.source == null || cost.target == null) { return cost; } if (cost.source.isSameType(cost.target) || // 7.3.3.13 for overload resolution the implicit this pointer is treated as if // it were a pointer to the derived class (isImplicitThis && cost.source instanceof ICPPClassType && cost.target instanceof ICPPClassType)) { cost.rank = Cost.IDENTITY_RANK; return cost; } qualificationConversion(cost); //if we can't convert the qualifications, then we can't do anything if (cost.qualification == Cost.NO_MATCH_RANK) { return cost; } //was the qualification conversion enough? IType s = getUltimateType(cost.source, true); IType t = getUltimateType(cost.target, true); if (s == null || t == null) { cost.rank = Cost.NO_MATCH_RANK; return cost; } if (s.isSameType(t) || // 7.3.3.13 for overload resolution the implicit this pointer is treated as if // it were a pointer to the derived class (isImplicitThis && s instanceof ICPPClassType && t instanceof ICPPClassType)) { return cost; } promotion(cost); if (cost.promotion > 0 || cost.rank > -1) { return cost; } conversion(cost); if (cost.rank > -1) return cost; derivedToBaseConversion(cost); if (cost.rank == -1) { relaxTemplateParameters(cost); } return cost; } /** * [13.3.3.1.2] User-defined conversions * @param source * @param target * @return * @throws DOMException */ private static final Cost checkUserDefinedConversionSequence(IType source, IType target) throws DOMException { Cost constructorCost= null; Cost operatorCost= null; IType s= getUltimateType(source, true); IType t= getUltimateType(target, true); //constructors if (t instanceof ICPPClassType) { ICPPConstructor [] constructors= ((ICPPClassType)t).getConstructors(); if (constructors.length > 0 && constructors[0] instanceof IProblemBinding == false) { LookupData data= new LookupData(); data.forUserDefinedConversion= true; data.functionParameters= new IType [] { source }; IBinding binding = CPPSemantics.resolveFunction(data, constructors); if (binding instanceof ICPPConstructor) { ICPPConstructor constructor= (ICPPConstructor) binding; if (!constructor.isExplicit()) { constructorCost = checkStandardConversionSequence(t, target, false); if (constructorCost.rank == Cost.NO_MATCH_RANK) { constructorCost= null; } } } } } //conversion operators boolean ambiguousConversionOperator= false; if (s instanceof ICPPClassType) { ICPPMethod [] ops = SemanticUtil.getConversionOperators((ICPPClassType)s); if (ops.length > 0 && ops[0] instanceof IProblemBinding == false) { for (final ICPPMethod op : ops) { Cost cost= checkStandardConversionSequence(op.getType().getReturnType(), target, false); if (cost.rank != Cost.NO_MATCH_RANK) { if (operatorCost == null) { operatorCost= cost; } else { int cmp= operatorCost.compare(cost); if (cmp >= 0) { ambiguousConversionOperator= cmp == 0; operatorCost= cost; } } } } } } if (constructorCost != null) { if (operatorCost == null || ambiguousConversionOperator) { constructorCost.userDefined = Cost.USERDEFINED_CONVERSION; constructorCost.rank = Cost.USERDEFINED_CONVERSION_RANK; } else { //if both are valid, then the conversion is ambiguous constructorCost.userDefined = Cost.AMBIGUOUS_USERDEFINED_CONVERSION; constructorCost.rank = Cost.USERDEFINED_CONVERSION_RANK; } return constructorCost; } if (operatorCost != null) { operatorCost.rank = Cost.USERDEFINED_CONVERSION_RANK; if (ambiguousConversionOperator) { operatorCost.userDefined = Cost.AMBIGUOUS_USERDEFINED_CONVERSION; } else { operatorCost.userDefined = Cost.USERDEFINED_CONVERSION; } return operatorCost; } return null; } /** * Calculates the number of edges in the inheritance path of <code>clazz</code> to * <code>ancestorToFind</code>, returning -1 if no inheritance relationship is found. * @param clazz the class to search upwards from * @param ancestorToFind the class to find in the inheritance graph * @return the number of edges in the inheritance graph, or -1 if the specified classes have * no inheritance relation * @throws DOMException */ private static final int calculateInheritanceDepth(int maxdepth, IType type, IType ancestorToFind) throws DOMException { if (type == ancestorToFind || type.isSameType(ancestorToFind)) { return 0; } if (maxdepth > 0 && type instanceof ICPPClassType && ancestorToFind instanceof ICPPClassType) { ICPPClassType clazz = (ICPPClassType) type; if(clazz instanceof ICPPDeferredClassInstance) { clazz= (ICPPClassType) ((ICPPDeferredClassInstance)clazz).getSpecializedBinding(); } for (ICPPBase cppBase : clazz.getBases()) { IBinding base= cppBase.getBaseClass(); if (base instanceof IType) { IType tbase= (IType) base; if (tbase.isSameType(ancestorToFind) || (ancestorToFind instanceof ICPPSpecialization && /*allow some flexibility with templates*/ ((IType)((ICPPSpecialization)ancestorToFind).getSpecializedBinding()).isSameType(tbase))) { return 1; } tbase= getUltimateTypeViaTypedefs(tbase); if (tbase instanceof ICPPClassType) { int n= calculateInheritanceDepth(maxdepth-1, tbase, ancestorToFind); if (n > 0) return n + 1; } } } } return -1; } /** * [4.1] Lvalue-to-rvalue conversion * [4.2] array-to-ptr * [4.3] function-to-ptr * * @param source * @param target * @return * @throws DOMException */ private static final Cost lvalue_to_rvalue(IType source, IType target) throws DOMException { Cost cost = new Cost(source, target); if (!isCompleteType(source)) { cost.rank= Cost.NO_MATCH_RANK; return cost; } if (source instanceof ICPPReferenceType) { source= ((ICPPReferenceType) source).getType(); } if (target instanceof ICPPReferenceType) { target= ((ICPPReferenceType) target).getType(); cost.targetHadReference = true; } //4.3 function to pointer conversion if (target instanceof IPointerType && ((IPointerType)target).getType() instanceof IFunctionType && source instanceof IFunctionType) { source = new CPPPointerType(source); } else if (target instanceof IPointerType && source instanceof IArrayType) { //4.2 Array-To-Pointer conversion source = new CPPPointerType(((IArrayType)source).getType()); } //4.1 if T is a non-class type, the type of the rvalue is the cv-unqualified version of T if (source instanceof IQualifierType) { IType t = ((IQualifierType)source).getType(); while (t instanceof ITypedef) t = ((ITypedef)t).getType(); if (!(t instanceof ICPPClassType)) { source = t; } } else if (source instanceof IPointerType && (((IPointerType)source).isConst() || ((IPointerType)source).isVolatile())) { IType t= ((IPointerType) source).getType(); while (t instanceof ITypedef) t= ((ITypedef) t).getType(); if (!(t instanceof ICPPClassType)) { source= new CPPPointerType(t); } } cost.source = source; cost.target = target; return cost; } /** * [4.4] Qualifications * @param cost * @throws DOMException */ private static final void qualificationConversion(Cost cost) throws DOMException{ boolean canConvert = true; int requiredConversion = Cost.IDENTITY_RANK; IType s = cost.source, t = cost.target; boolean constInEveryCV2k = true; boolean firstPointer= true; while (true) { s= getUltimateTypeViaTypedefs(s); t= getUltimateTypeViaTypedefs(t); final boolean sourceIsPointer= s instanceof IPointerType; final boolean targetIsPointer= t instanceof IPointerType; if (!targetIsPointer) { if (!sourceIsPointer) break; if (t instanceof ICPPBasicType) { if (((ICPPBasicType)t).getType() == ICPPBasicType.t_bool) { canConvert= true; requiredConversion = Cost.CONVERSION_RANK; break; } } canConvert = false; break; } else if (!sourceIsPointer) { canConvert = false; break; } else if (s instanceof ICPPPointerToMemberType ^ t instanceof ICPPPointerToMemberType) { canConvert = false; break; } // both are pointers IPointerType op1= (IPointerType) s; IPointerType op2= (IPointerType) t; //if const is in cv1,j then const is in cv2,j. Similary for volatile if ((op1.isConst() && !op2.isConst()) || (op1.isVolatile() && !op2.isVolatile())) { canConvert = false; requiredConversion = Cost.NO_MATCH_RANK; break; } //if cv1,j and cv2,j are different then const is in every cv2,k for 0<k<j if (!constInEveryCV2k && (op1.isConst() != op2.isConst() || op1.isVolatile() != op2.isVolatile())) { canConvert = false; requiredConversion = Cost.NO_MATCH_RANK; break; } constInEveryCV2k &= (firstPointer || op2.isConst()); s = op1.getType(); t = op2.getType(); firstPointer= false; } if (s instanceof IQualifierType ^ t instanceof IQualifierType) { if (t instanceof IQualifierType) { if (!constInEveryCV2k) { canConvert= false; requiredConversion= Cost.NO_MATCH_RANK; } else { canConvert = true; requiredConversion = Cost.CONVERSION_RANK; } } else { //4.2-2 a string literal can be converted to pointer to char if (t instanceof IBasicType && ((IBasicType)t).getType() == IBasicType.t_char && s instanceof IQualifierType) { IType qt = ((IQualifierType)s).getType(); if (qt instanceof IBasicType) { IASTExpression val = ((IBasicType)qt).getValue(); canConvert = (val != null && val instanceof IASTLiteralExpression && ((IASTLiteralExpression)val).getKind() == IASTLiteralExpression.lk_string_literal); } else { canConvert = false; requiredConversion = Cost.NO_MATCH_RANK; } } else { canConvert = false; requiredConversion = Cost.NO_MATCH_RANK; } } } else if (s instanceof IQualifierType && t instanceof IQualifierType) { IQualifierType qs = (IQualifierType) s, qt = (IQualifierType) t; if (qs.isConst() == qt.isConst() && qs.isVolatile() == qt.isVolatile()) { requiredConversion = Cost.IDENTITY_RANK; } else if ((qs.isConst() && !qt.isConst()) || (qs.isVolatile() && !qt.isVolatile()) || !constInEveryCV2k) { requiredConversion = Cost.NO_MATCH_RANK; canConvert= false; } else { requiredConversion = Cost.CONVERSION_RANK; } } else if (constInEveryCV2k && !canConvert) { canConvert = true; requiredConversion = Cost.CONVERSION_RANK; int i = 1; for (IType type = s; canConvert == true && i == 1; type = t, i++) { while (type instanceof ITypeContainer) { if (type instanceof IQualifierType) { canConvert = false; } else if (type instanceof IPointerType) { canConvert = !((IPointerType)type).isConst() && !((IPointerType)type).isVolatile(); } if (!canConvert) { requiredConversion = Cost.NO_MATCH_RANK; break; } type = ((ITypeContainer)type).getType(); } } } cost.qualification = requiredConversion; if (canConvert == true) { cost.rank = Cost.LVALUE_OR_QUALIFICATION_RANK; } } /** * [4.5] [4.6] Promotion * * 4.5-1 char, signed char, unsigned char, short int or unsigned short int * can be converted to int if int can represent all the values of the source * type, otherwise they can be converted to unsigned int. * 4.5-2 wchar_t or an enumeration can be converted to the first of the * following that can hold it: int, unsigned int, long unsigned long. * 4.5-4 bool can be promoted to int * 4.6 float can be promoted to double * @throws DOMException */ private static final void promotion(Cost cost) throws DOMException{ IType src = cost.source; IType trg = cost.target; if (src.isSameType(trg)) return; if (src instanceof IBasicType && trg instanceof IBasicType) { int sType = ((IBasicType)src).getType(); int tType = ((IBasicType)trg).getType(); if ((tType == IBasicType.t_int && (sType == IBasicType.t_int || //short, long , unsigned etc sType == IBasicType.t_char || sType == ICPPBasicType.t_bool || sType == ICPPBasicType.t_wchar_t || sType == IBasicType.t_unspecified)) || //treat unspecified as int (tType == IBasicType.t_double && sType == IBasicType.t_float)) { cost.promotion = 1; } } else if (src instanceof IEnumeration && trg instanceof IBasicType && (((IBasicType)trg).getType() == IBasicType.t_int || ((IBasicType)trg).getType() == IBasicType.t_unspecified)) { cost.promotion = 1; } cost.rank = (cost.promotion > 0) ? Cost.PROMOTION_RANK : Cost.NO_MATCH_RANK; } /** * [4.7] Integral conversions * [4.8] Floating point conversions * [4.9] Floating-integral conversions * [4.10] Pointer conversions * [4.11] Pointer to member conversions * @param cost * @throws DOMException */ private static final void conversion(Cost cost) throws DOMException{ final IType src = cost.source; final IType trg = cost.target; cost.conversion = 0; cost.detail = 0; IType[] sHolder= new IType[1], tHolder= new IType[1]; IType s = getUltimateType(src, sHolder, true); IType t = getUltimateType(trg, tHolder, true); IType sPrev= sHolder[0], tPrev= tHolder[0]; if (src instanceof IBasicType && trg instanceof IPointerType) { //4.10-1 an integral constant expression of integer type that evaluates to 0 can be converted to a pointer type IASTExpression exp = ((IBasicType)src).getValue(); if (exp instanceof IASTLiteralExpression && ((IASTLiteralExpression)exp).getKind() == IASTLiteralExpression.lk_integer_constant) { try { String val = exp.toString().toLowerCase().replace('u', '0'); val.replace('l', '0'); if (Integer.decode(val).intValue() == 0) { cost.rank = Cost.CONVERSION_RANK; cost.conversion = 1; } } catch(NumberFormatException e) { } } } else if (sPrev instanceof IPointerType) { //4.10-2 an rvalue of type "pointer to cv T", where T is an object type can be //converted to an rvalue of type "pointer to cv void" if (tPrev instanceof IPointerType && t instanceof IBasicType && ((IBasicType)t).getType() == IBasicType.t_void) { cost.rank = Cost.CONVERSION_RANK; cost.conversion = 1; cost.detail = 2; return; } //4.10-3 An rvalue of type "pointer to cv D", where D is a class type can be converted //to an rvalue of type "pointer to cv B", where B is a base class of D. else if (s instanceof ICPPClassType && tPrev instanceof IPointerType && t instanceof ICPPClassType) { int depth= calculateInheritanceDepth(CPPSemantics.MAX_INHERITANCE_DEPTH, s, t); cost.rank= (depth > -1) ? Cost.CONVERSION_RANK : Cost.NO_MATCH_RANK; cost.conversion= (depth > -1) ? depth : 0; cost.detail= 1; return; } // 4.12 if the target is a bool, we can still convert else if (!(trg instanceof IBasicType && ((IBasicType)trg).getType() == ICPPBasicType.t_bool)) { return; } } if (t instanceof IBasicType && s instanceof IBasicType || s instanceof IEnumeration) { //4.7 An rvalue of an integer type can be converted to an rvalue of another integer type. //An rvalue of an enumeration type can be converted to an rvalue of an integer type. cost.rank = Cost.CONVERSION_RANK; cost.conversion = 1; } else if (trg instanceof IBasicType && ((IBasicType)trg).getType() == ICPPBasicType.t_bool && s instanceof IPointerType) { //4.12 pointer or pointer to member type can be converted to an rvalue of type bool cost.rank = Cost.CONVERSION_RANK; cost.conversion = 1; } else if (s instanceof ICPPPointerToMemberType && t instanceof ICPPPointerToMemberType) { //4.11-2 An rvalue of type "pointer to member of B of type cv T", where B is a class type, //can be converted to an rvalue of type "pointer to member of D of type cv T" where D is a //derived class of B ICPPPointerToMemberType spm = (ICPPPointerToMemberType) s; ICPPPointerToMemberType tpm = (ICPPPointerToMemberType) t; IType st = spm.getType(); IType tt = tpm.getType(); if (st != null && tt != null && st.isSameType(tt)) { int depth= calculateInheritanceDepth(CPPSemantics.MAX_INHERITANCE_DEPTH, tpm.getMemberOfClass(), spm.getMemberOfClass()); cost.rank= (depth > -1) ? Cost.CONVERSION_RANK : Cost.NO_MATCH_RANK; cost.conversion= (depth > -1) ? depth : 0; cost.detail= 1; } } } /** * [13.3.3.1-6] Derived to base conversion * @param cost * @throws DOMException */ private static final void derivedToBaseConversion(Cost cost) throws DOMException { IType s = getUltimateType(cost.source, true); IType t = getUltimateType(cost.target, true); if (cost.targetHadReference && s instanceof ICPPClassType && t instanceof ICPPClassType) { int depth= calculateInheritanceDepth(CPPSemantics.MAX_INHERITANCE_DEPTH, s, t); if (depth > -1) { cost.rank = Cost.DERIVED_TO_BASE_CONVERSION; cost.conversion = depth; } } } /** * @param type * @return whether the specified type has an associated definition */ private static final boolean isCompleteType(IType type) { type= getUltimateType(type, false); if (type instanceof ICPPClassType) { if (type instanceof ICPPInternalBinding) { return (((ICPPInternalBinding)type).getDefinition() != null); } if (type instanceof IIndexFragmentBinding) { try { return ((IIndexFragmentBinding)type).hasDefinition(); } catch(CoreException ce) { CCorePlugin.log(ce); } } } return true; } /** * Allows any very loose matching between template parameters. * @param cost */ private static final void relaxTemplateParameters(Cost cost) { IType s = getUltimateType(cost.source, false); IType t = getUltimateType(cost.target, false); if ((s instanceof ICPPTemplateTypeParameter && t instanceof ICPPTemplateTypeParameter) || (s instanceof ICPPTemplateTemplateParameter && t instanceof ICPPTemplateTemplateParameter)) { cost.rank = Cost.FUZZY_TEMPLATE_PARAMETERS; } } }
false
true
public static Cost checkImplicitConversionSequence(boolean allowUDC, IASTExpression sourceExp, IType source, IType target, boolean isImpliedObject) throws DOMException { Cost cost; allowUDC &= !isImpliedObject; if (target instanceof ICPPReferenceType) { // [13.3.3.3.1] Reference binding IType cv1T1= ((ICPPReferenceType)target).getType(); cost= new Cost(source, cv1T1); cost.targetHadReference= true; boolean lvalue= sourceExp == null || !CPPVisitor.isRValue(sourceExp); IType T2= source instanceof IQualifierType ? ((IQualifierType)source).getType() : source; if (lvalue && isReferenceCompatible(cv1T1, source)) { /* Direct reference binding */ // [13.3.3.1.4] if (cost.source.isSameType(cost.target) || // 7.3.3.13 for overload resolution the implicit this pointer is treated as if // it were a pointer to the derived class (isImpliedObject && cost.source instanceof ICPPClassType && cost.target instanceof ICPPClassType)) { cost.rank = Cost.IDENTITY_RANK; return cost; } /* * is an lvalue (but is not a bit-field), and "cv1 T1" is reference-compatible with "cv2 T2," */ // [13.3.3.1.4-1] direct binding // [8.5.3-5] qualificationConversion(cost); derivedToBaseConversion(cost); } else if (T2 instanceof ICPPClassType) { if(allowUDC) { /* * or has a class type (i.e., T2 is a class type) and can be implicitly converted to * an lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible with "cv3 T3" 92) * (this conversion is selected by enumerating the applicable conversion functions (13.3.1.6) * and choosing the best one through overload resolution (13.3)). */ ICPPMethod[] fcns= SemanticUtil.getConversionOperators((ICPPClassType)T2); Cost operatorCost= null; ICPPMethod conv= null; boolean ambiguousConversionOperator= false; if (fcns.length > 0 && fcns[0] instanceof IProblemBinding == false) { for (final ICPPMethod op : fcns) { Cost cost2 = checkStandardConversionSequence(op.getType().getReturnType(), target, false); if (cost2.rank != Cost.NO_MATCH_RANK) { if (operatorCost == null) { operatorCost= cost2; conv= op; } else { int cmp= operatorCost.compare(cost2); if (cmp >= 0) { ambiguousConversionOperator= cmp == 0; operatorCost= cost2; conv= op; } } } } } if (conv!= null && !ambiguousConversionOperator) { IType newSource= conv.getType().getReturnType(); boolean isNewSourceLValue= newSource instanceof ICPPReferenceType; if (isNewSourceLValue && isReferenceCompatible(cv1T1, newSource)) { cost= new Cost(cv1T1, newSource); qualificationConversion(cost); derivedToBaseConversion(cost); } } } } /* Direct binding failed */ if (cost.rank == Cost.NO_MATCH_RANK) { // 8.5.3-5 - Otherwise boolean cv1isConst= false; if (cv1T1 instanceof IQualifierType) { cv1isConst= ((IQualifierType)cv1T1).isConst() && !((IQualifierType)cv1T1).isVolatile(); } else if (cv1T1 instanceof IPointerType) { cv1isConst= ((IPointerType)cv1T1).isConst() && !((IPointerType)cv1T1).isVolatile(); } if (cv1isConst) { if (!lvalue && source instanceof ICPPClassType) { cost= new Cost(source, target); cost.rank= Cost.IDENTITY_RANK; } else { // 5 - Otherwise // Otherwise, a temporary of type "cv1 T1" is created and initialized from the initializer expression // using the rules for a non-reference copy initialization (8.5). The reference is then bound to the temporary. // If T1 is reference-related to T2, cv1 must be the same cv-qualification as, or greater cvqualification // than, cv2; otherwise, the program is ill-formed. [Example boolean illformed= false; if (isReferenceRelated(cv1T1, source)) { Integer cmp= compareQualifications(cv1T1, source); if (cmp == null || cmp < 0) { illformed= true; } } // we must do a non-reference initialization if (!illformed) { cost= checkStandardConversionSequence(source, cv1T1, isImpliedObject); // 12.3-4 At most one user-defined conversion is implicitly applied to // a single value. (also prevents infinite loop) if (allowUDC && (cost.rank == Cost.NO_MATCH_RANK || cost.rank == Cost.FUZZY_TEMPLATE_PARAMETERS)) { Cost temp = checkUserDefinedConversionSequence(source, cv1T1); if (temp != null) { cost = temp; } } } } } } } else { // Non-reference binding cost= checkStandardConversionSequence(source, target, isImpliedObject); if (allowUDC && (cost.rank == Cost.NO_MATCH_RANK || cost.rank == Cost.FUZZY_TEMPLATE_PARAMETERS)) { Cost temp = checkUserDefinedConversionSequence(source, target); if (temp != null) { cost = temp; } } } return cost; }
public static Cost checkImplicitConversionSequence(boolean allowUDC, IASTExpression sourceExp, IType source, IType target, boolean isImpliedObject) throws DOMException { Cost cost; allowUDC &= !isImpliedObject; target= getUltimateTypeViaTypedefs(target); source= getUltimateTypeViaTypedefs(source); if (target instanceof ICPPReferenceType) { // [13.3.3.3.1] Reference binding IType cv1T1= getUltimateTypeViaTypedefs(((ICPPReferenceType)target).getType()); cost= new Cost(source, cv1T1); cost.targetHadReference= true; boolean lvalue= sourceExp == null || !CPPVisitor.isRValue(sourceExp); IType T2= source instanceof IQualifierType ? getUltimateTypeViaTypedefs(((IQualifierType)source).getType()) : source; if (lvalue && isReferenceCompatible(cv1T1, source)) { /* Direct reference binding */ // [13.3.3.1.4] if (cost.source.isSameType(cost.target) || // 7.3.3.13 for overload resolution the implicit this pointer is treated as if // it were a pointer to the derived class (isImpliedObject && cost.source instanceof ICPPClassType && cost.target instanceof ICPPClassType)) { cost.rank = Cost.IDENTITY_RANK; return cost; } /* * is an lvalue (but is not a bit-field), and "cv1 T1" is reference-compatible with "cv2 T2," */ // [13.3.3.1.4-1] direct binding // [8.5.3-5] qualificationConversion(cost); derivedToBaseConversion(cost); } else if (T2 instanceof ICPPClassType) { if(allowUDC) { /* * or has a class type (i.e., T2 is a class type) and can be implicitly converted to * an lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible with "cv3 T3" 92) * (this conversion is selected by enumerating the applicable conversion functions (13.3.1.6) * and choosing the best one through overload resolution (13.3)). */ ICPPMethod[] fcns= SemanticUtil.getConversionOperators((ICPPClassType)T2); Cost operatorCost= null; ICPPMethod conv= null; boolean ambiguousConversionOperator= false; if (fcns.length > 0 && fcns[0] instanceof IProblemBinding == false) { for (final ICPPMethod op : fcns) { Cost cost2 = checkStandardConversionSequence(op.getType().getReturnType(), target, false); if (cost2.rank != Cost.NO_MATCH_RANK) { if (operatorCost == null) { operatorCost= cost2; conv= op; } else { int cmp= operatorCost.compare(cost2); if (cmp >= 0) { ambiguousConversionOperator= cmp == 0; operatorCost= cost2; conv= op; } } } } } if (conv!= null && !ambiguousConversionOperator) { IType newSource= conv.getType().getReturnType(); boolean isNewSourceLValue= newSource instanceof ICPPReferenceType; if (isNewSourceLValue && isReferenceCompatible(cv1T1, newSource)) { cost= new Cost(cv1T1, newSource); qualificationConversion(cost); derivedToBaseConversion(cost); } } } } /* Direct binding failed */ if (cost.rank == Cost.NO_MATCH_RANK) { // 8.5.3-5 - Otherwise boolean cv1isConst= false; if (cv1T1 instanceof IQualifierType) { cv1isConst= ((IQualifierType)cv1T1).isConst() && !((IQualifierType)cv1T1).isVolatile(); } else if (cv1T1 instanceof IPointerType) { cv1isConst= ((IPointerType)cv1T1).isConst() && !((IPointerType)cv1T1).isVolatile(); } if (cv1isConst) { if (!lvalue && source instanceof ICPPClassType) { cost= new Cost(source, target); cost.rank= Cost.IDENTITY_RANK; } else { // 5 - Otherwise // Otherwise, a temporary of type "cv1 T1" is created and initialized from the initializer expression // using the rules for a non-reference copy initialization (8.5). The reference is then bound to the temporary. // If T1 is reference-related to T2, cv1 must be the same cv-qualification as, or greater cvqualification // than, cv2; otherwise, the program is ill-formed. [Example boolean illformed= false; if (isReferenceRelated(cv1T1, source)) { Integer cmp= compareQualifications(cv1T1, source); if (cmp == null || cmp < 0) { illformed= true; } } // we must do a non-reference initialization if (!illformed) { cost= checkStandardConversionSequence(source, cv1T1, isImpliedObject); // 12.3-4 At most one user-defined conversion is implicitly applied to // a single value. (also prevents infinite loop) if (allowUDC && (cost.rank == Cost.NO_MATCH_RANK || cost.rank == Cost.FUZZY_TEMPLATE_PARAMETERS)) { Cost temp = checkUserDefinedConversionSequence(source, cv1T1); if (temp != null) { cost = temp; } } } } } } } else { // Non-reference binding cost= checkStandardConversionSequence(source, target, isImpliedObject); if (allowUDC && (cost.rank == Cost.NO_MATCH_RANK || cost.rank == Cost.FUZZY_TEMPLATE_PARAMETERS)) { Cost temp = checkUserDefinedConversionSequence(source, target); if (temp != null) { cost = temp; } } } return cost; }
diff --git a/src/test/java/com/munzenberger/feed/handler/DownloadEnclosuresTest.java b/src/test/java/com/munzenberger/feed/handler/DownloadEnclosuresTest.java index 61bb12d..7344890 100644 --- a/src/test/java/com/munzenberger/feed/handler/DownloadEnclosuresTest.java +++ b/src/test/java/com/munzenberger/feed/handler/DownloadEnclosuresTest.java @@ -1,33 +1,33 @@ package com.munzenberger.feed.handler; import java.io.File; import junit.framework.TestCase; public class DownloadEnclosuresTest extends TestCase { public void testGetLocalFile() throws Exception { DownloadEnclosures handler = new DownloadEnclosures(); String url = "http://www.test.com/download.mp3?id=1"; File f1 = handler.getLocalFile(url); assertNotNull(f1); f1.deleteOnExit(); final String separator = System.getProperty("file.separator"); assertEquals("." + separator + "download.mp3", f1.getPath()); url = "http://www.test.com/download.mp3?id=2"; File f2 = handler.getLocalFile(url); assertNotNull(f2); f2.deleteOnExit(); - assertEquals("." + separator + "download-61407919.mp3", f2.getPath()); + assertEquals("." + separator + "download-1594842180.mp3", f2.getPath()); } }
true
true
public void testGetLocalFile() throws Exception { DownloadEnclosures handler = new DownloadEnclosures(); String url = "http://www.test.com/download.mp3?id=1"; File f1 = handler.getLocalFile(url); assertNotNull(f1); f1.deleteOnExit(); final String separator = System.getProperty("file.separator"); assertEquals("." + separator + "download.mp3", f1.getPath()); url = "http://www.test.com/download.mp3?id=2"; File f2 = handler.getLocalFile(url); assertNotNull(f2); f2.deleteOnExit(); assertEquals("." + separator + "download-61407919.mp3", f2.getPath()); }
public void testGetLocalFile() throws Exception { DownloadEnclosures handler = new DownloadEnclosures(); String url = "http://www.test.com/download.mp3?id=1"; File f1 = handler.getLocalFile(url); assertNotNull(f1); f1.deleteOnExit(); final String separator = System.getProperty("file.separator"); assertEquals("." + separator + "download.mp3", f1.getPath()); url = "http://www.test.com/download.mp3?id=2"; File f2 = handler.getLocalFile(url); assertNotNull(f2); f2.deleteOnExit(); assertEquals("." + separator + "download-1594842180.mp3", f2.getPath()); }
diff --git a/java/src/com/teamten/mario/World.java b/java/src/com/teamten/mario/World.java index 322d9df..8340a2f 100644 --- a/java/src/com/teamten/mario/World.java +++ b/java/src/com/teamten/mario/World.java @@ -1,137 +1,140 @@ // Copyright 2011 Lawrence Kesteloot package com.teamten.mario; import java.awt.Graphics; /** * The environment and the characters within it. */ public class World { public static final int GRAVITY = 8; public static final int FRICTION = 4; private static final boolean IS_PERSON = true; private final Env mEnv; private final Player mPlayer; public World(Env env, Player player) { mEnv = env; mPlayer = player; } public void draw(Graphics g) { getEnv().draw(g); getPlayer().draw(g); } public Env getEnv() { return mEnv; } public Player getPlayer() { return mPlayer; } public World step(Input input) { Env env = getEnv(); Player player = getPlayer(); boolean touchingFloor = env.isTouchingFloor(player); int ax = 0; int ay = 0; if (touchingFloor) { if (input.isJumpPressed()) { ay -= Player.JUMP; } if (input.isLeftPressed()) { ax -= 1; } if (input.isRightPressed()) { ax += 1; } } + // Compute new velocity. int vx; int vy = player.getVy() + ay*Player.VELOCITY_SCALE; if (IS_PERSON) { if (touchingFloor) { - vx = 5*ax*Player.VELOCITY_SCALE; + vx = 3*ax*Player.VELOCITY_SCALE; } else { vx = player.getVx(); } } else { vx = player.getVx() + ax*Player.VELOCITY_SCALE; } + // Friction and gravity. if (touchingFloor) { if (!IS_PERSON) { vx -= Integer.signum(vx)*FRICTION; } } else { vy += GRAVITY; } // Move player by its velocity. int dx = (int) Math.round((double) vx/Player.VELOCITY_SCALE); int x = player.getX() + dx; int y = player.getY() + (int) Math.round((double) vy/Player.VELOCITY_SCALE); // Roll the ball. int angle = player.getAngle() - 360*dx/player.getCircumference(); // Increase radius if we're on toy. double radius = player.getRealRadius(); int toyIndex = env.getToyIndex(player); if (toyIndex >= 0) { // Increase area. Toy toy = env.getToy(toyIndex); radius += 2.0*toy.getRadius()*toy.getRadius()/(radius*radius); env = env.withoutToy(toyIndex); } + // Push off the walls and floors. Integer pushBack = env.getPushBack(player, x, y, vx, vy); if (pushBack != null) { int dy = pushBack.intValue(); y -= dy; if ((vy > 0) == (dy > 0)) { vy = 0; } } /* System.out.printf("(%d,%d,%d,%d) -> (%d,%d) -> (%d,%d,%d,%d)%n", mX, mY, player.getVx(), mVy, ax, ay, x, y, vx, vy); */ // Check if we died. if (y > Env.HEIGHT) { x = Env.WIDTH/2; y = Env.HEIGHT/3; vx = 0; vy = 0; // radius = Player.INITIAL_RADIUS; } Player newPlayer = new Player(x, y, angle, vx, vy, radius); return new World(env, newPlayer); } @Override // Object public int hashCode() { return getEnv().hashCode() + 31*getPlayer().hashCode(); } @Override // Object public boolean equals(Object other) { if (!(other instanceof World)) { return false; } World otherWorld = (World) other; return getEnv().equals(otherWorld.getEnv()) && getPlayer().equals(otherWorld.getPlayer()); } }
false
true
public World step(Input input) { Env env = getEnv(); Player player = getPlayer(); boolean touchingFloor = env.isTouchingFloor(player); int ax = 0; int ay = 0; if (touchingFloor) { if (input.isJumpPressed()) { ay -= Player.JUMP; } if (input.isLeftPressed()) { ax -= 1; } if (input.isRightPressed()) { ax += 1; } } int vx; int vy = player.getVy() + ay*Player.VELOCITY_SCALE; if (IS_PERSON) { if (touchingFloor) { vx = 5*ax*Player.VELOCITY_SCALE; } else { vx = player.getVx(); } } else { vx = player.getVx() + ax*Player.VELOCITY_SCALE; } if (touchingFloor) { if (!IS_PERSON) { vx -= Integer.signum(vx)*FRICTION; } } else { vy += GRAVITY; } // Move player by its velocity. int dx = (int) Math.round((double) vx/Player.VELOCITY_SCALE); int x = player.getX() + dx; int y = player.getY() + (int) Math.round((double) vy/Player.VELOCITY_SCALE); // Roll the ball. int angle = player.getAngle() - 360*dx/player.getCircumference(); // Increase radius if we're on toy. double radius = player.getRealRadius(); int toyIndex = env.getToyIndex(player); if (toyIndex >= 0) { // Increase area. Toy toy = env.getToy(toyIndex); radius += 2.0*toy.getRadius()*toy.getRadius()/(radius*radius); env = env.withoutToy(toyIndex); } Integer pushBack = env.getPushBack(player, x, y, vx, vy); if (pushBack != null) { int dy = pushBack.intValue(); y -= dy; if ((vy > 0) == (dy > 0)) { vy = 0; } } /* System.out.printf("(%d,%d,%d,%d) -> (%d,%d) -> (%d,%d,%d,%d)%n", mX, mY, player.getVx(), mVy, ax, ay, x, y, vx, vy); */ // Check if we died. if (y > Env.HEIGHT) { x = Env.WIDTH/2; y = Env.HEIGHT/3; vx = 0; vy = 0; // radius = Player.INITIAL_RADIUS; } Player newPlayer = new Player(x, y, angle, vx, vy, radius); return new World(env, newPlayer); }
public World step(Input input) { Env env = getEnv(); Player player = getPlayer(); boolean touchingFloor = env.isTouchingFloor(player); int ax = 0; int ay = 0; if (touchingFloor) { if (input.isJumpPressed()) { ay -= Player.JUMP; } if (input.isLeftPressed()) { ax -= 1; } if (input.isRightPressed()) { ax += 1; } } // Compute new velocity. int vx; int vy = player.getVy() + ay*Player.VELOCITY_SCALE; if (IS_PERSON) { if (touchingFloor) { vx = 3*ax*Player.VELOCITY_SCALE; } else { vx = player.getVx(); } } else { vx = player.getVx() + ax*Player.VELOCITY_SCALE; } // Friction and gravity. if (touchingFloor) { if (!IS_PERSON) { vx -= Integer.signum(vx)*FRICTION; } } else { vy += GRAVITY; } // Move player by its velocity. int dx = (int) Math.round((double) vx/Player.VELOCITY_SCALE); int x = player.getX() + dx; int y = player.getY() + (int) Math.round((double) vy/Player.VELOCITY_SCALE); // Roll the ball. int angle = player.getAngle() - 360*dx/player.getCircumference(); // Increase radius if we're on toy. double radius = player.getRealRadius(); int toyIndex = env.getToyIndex(player); if (toyIndex >= 0) { // Increase area. Toy toy = env.getToy(toyIndex); radius += 2.0*toy.getRadius()*toy.getRadius()/(radius*radius); env = env.withoutToy(toyIndex); } // Push off the walls and floors. Integer pushBack = env.getPushBack(player, x, y, vx, vy); if (pushBack != null) { int dy = pushBack.intValue(); y -= dy; if ((vy > 0) == (dy > 0)) { vy = 0; } } /* System.out.printf("(%d,%d,%d,%d) -> (%d,%d) -> (%d,%d,%d,%d)%n", mX, mY, player.getVx(), mVy, ax, ay, x, y, vx, vy); */ // Check if we died. if (y > Env.HEIGHT) { x = Env.WIDTH/2; y = Env.HEIGHT/3; vx = 0; vy = 0; // radius = Player.INITIAL_RADIUS; } Player newPlayer = new Player(x, y, angle, vx, vy, radius); return new World(env, newPlayer); }
diff --git a/src/fr/adrienbrault/idea/symfony2plugin/Symfony2CachedInterfacesUtil.java b/src/fr/adrienbrault/idea/symfony2plugin/Symfony2CachedInterfacesUtil.java index 420a49a7..adb732aa 100644 --- a/src/fr/adrienbrault/idea/symfony2plugin/Symfony2CachedInterfacesUtil.java +++ b/src/fr/adrienbrault/idea/symfony2plugin/Symfony2CachedInterfacesUtil.java @@ -1,61 +1,64 @@ package fr.adrienbrault.idea.symfony2plugin; import com.intellij.psi.PsiElement; import com.jetbrains.php.lang.psi.elements.Method; import com.jetbrains.php.lang.psi.elements.PhpClass; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * @author Adrien Brault <[email protected]> */ public class Symfony2CachedInterfacesUtil extends Symfony2InterfacesUtil { private Map<PsiElement, Map<String, Boolean>> isCallToCache = new HashMap<PsiElement, Map<String, Boolean>>(); private Map<String, Boolean> isInstanceOfCache = new HashMap<String, Boolean>(); protected boolean isCallTo(PsiElement e, Method[] expectedMethods) { StringBuilder stringBuilder = new StringBuilder(); for (Method method : Arrays.asList(expectedMethods)) { - stringBuilder.append(method.getFQN()).append("_"); + if (null != method) { + stringBuilder.append(method.getFQN()); + stringBuilder.append("_"); + } } Map<String, Boolean> elementCache = isCallToCache.get(e); Boolean cachedValue = null; if (null != elementCache) { cachedValue = elementCache.get(stringBuilder.toString()); } if (null != cachedValue) { return cachedValue; } boolean result = super.isCallTo(e, expectedMethods); if (null == elementCache) { elementCache = new HashMap<String, Boolean>(); isCallToCache.put(e, elementCache); } elementCache.put(stringBuilder.toString(), result); return result; } protected boolean isInstanceOf(PhpClass subjectClass, PhpClass expectedClass) { String cacheKey = subjectClass.getFQN() + "@@@" + expectedClass.getFQN(); Boolean cachedValue = isInstanceOfCache.get(cacheKey); if (null != cachedValue) { return cachedValue; } boolean result = super.isInstanceOf(subjectClass, expectedClass); isInstanceOfCache.put(cacheKey, true); return result; } }
true
true
protected boolean isCallTo(PsiElement e, Method[] expectedMethods) { StringBuilder stringBuilder = new StringBuilder(); for (Method method : Arrays.asList(expectedMethods)) { stringBuilder.append(method.getFQN()).append("_"); } Map<String, Boolean> elementCache = isCallToCache.get(e); Boolean cachedValue = null; if (null != elementCache) { cachedValue = elementCache.get(stringBuilder.toString()); } if (null != cachedValue) { return cachedValue; } boolean result = super.isCallTo(e, expectedMethods); if (null == elementCache) { elementCache = new HashMap<String, Boolean>(); isCallToCache.put(e, elementCache); } elementCache.put(stringBuilder.toString(), result); return result; }
protected boolean isCallTo(PsiElement e, Method[] expectedMethods) { StringBuilder stringBuilder = new StringBuilder(); for (Method method : Arrays.asList(expectedMethods)) { if (null != method) { stringBuilder.append(method.getFQN()); stringBuilder.append("_"); } } Map<String, Boolean> elementCache = isCallToCache.get(e); Boolean cachedValue = null; if (null != elementCache) { cachedValue = elementCache.get(stringBuilder.toString()); } if (null != cachedValue) { return cachedValue; } boolean result = super.isCallTo(e, expectedMethods); if (null == elementCache) { elementCache = new HashMap<String, Boolean>(); isCallToCache.put(e, elementCache); } elementCache.put(stringBuilder.toString(), result); return result; }
diff --git a/src/org/opensolaris/opengrok/web/Util.java b/src/org/opensolaris/opengrok/web/Util.java index 3de03e2..44e3989 100644 --- a/src/org/opensolaris/opengrok/web/Util.java +++ b/src/org/opensolaris/opengrok/web/Util.java @@ -1,456 +1,458 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ package org.opensolaris.opengrok.web; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.logging.Level; import org.opensolaris.opengrok.OpenGrokLogger; import org.opensolaris.opengrok.configuration.RuntimeEnvironment; import org.opensolaris.opengrok.history.Annotation; /** * File for useful functions */ public final class Util { /** * Return a string which represents a <code>CharSequence</code> in HTML. * * @param q a character sequence * @return a string representing the character sequence in HTML */ private Util() { // Util class, should not be constructed } public static String htmlize(CharSequence q) { StringBuilder sb = new StringBuilder(q.length() * 2); htmlize(q, sb); return sb.toString(); } /** * Append a character sequence to an <code>Appendable</code> object. Escape * special characters for HTML. * * @param q a character sequence * @param out the object to append the character sequence to * @exception IOException if an I/O error occurs */ public static void htmlize(CharSequence q, Appendable out) throws IOException { for (int i = 0; i < q.length(); i++) { htmlize(q.charAt(i), out); } } /** * Append a character sequence to a <code>StringBuilder</code> * object. Escape special characters for HTML. This method is identical to * <code>htmlize(CharSequence,Appendable)</code>, except that it is * guaranteed not to throw <code>IOException</code> because it uses a * <code>StringBuilder</code>. * * @param q a character sequence * @param out the object to append the character sequence to * @see #htmlize(CharSequence, Appendable) */ @SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes") public static void htmlize(CharSequence q, StringBuilder out) { try { htmlize(q, (Appendable) out); } catch (IOException ioe) { // StringBuilder's append methods are not declared to throw // IOException, so this should never happen. throw new RuntimeException("StringBuilder should not throw IOException", ioe); } } public static void htmlize(char[] cs, int length, Appendable out) throws IOException { for (int i = 0; i < length && i < cs.length; i++) { htmlize(cs[i], out); } } /** * Append a character to a an <code>Appendable</code> object. If the * character has special meaning in HTML, append a sequence of characters * representing the special character. * * @param c the character to append * @param out the object to append the character to * @exception IOException if an I/O error occurs */ private static void htmlize(char c, Appendable out) throws IOException { switch (c) { case '&': out.append("&amp;"); break; case '>': out.append("&gt;"); break; case '<': out.append("&lt;"); break; case '\n': out.append("<br/>"); break; default: out.append(c); } } /** * Same as {@code breadcrumbPath(urlPrefix, l, '/')}. * @see #breadcrumbPath(String, String, char) */ public static String breadcrumbPath(String urlPrefix, String l) { return breadcrumbPath(urlPrefix, l, '/'); } private static final String anchorLinkStart = "<a href=\""; private static final String anchorClassStart = "<a class=\""; private static final String anchorEnd = "</a>"; private static final String closeQuotedTag = "\">"; /** * Same as {@code breadcrumbPath(urlPrefix, l, sep, "", false)}. * @see #breadcrumbPath(String, String, char, String, boolean) */ public static String breadcrumbPath(String urlPrefix, String l, char sep) { return breadcrumbPath(urlPrefix, l, sep, "", false); } /** * Create a breadcrumb path to allow navigation to each element of a path. * * @param urlPrefix what comes before the path in the URL * @param l the full path from which the breadcrumb path is built * @param sep the character that separates the path elements in {@code l} * @param urlPostfix what comes after the path in the URL * @param compact if {@code true}, remove {@code ..} and empty path * elements from the path in the links * @return HTML markup for the breadcrumb path */ public static String breadcrumbPath( String urlPrefix, String l, char sep, String urlPostfix, boolean compact) { if (l == null || l.length() <= 1) { return l; } StringBuilder hyperl = new StringBuilder(20); String[] path = l.split(escapeForRegex(sep), -1); for (int i = 0; i < path.length; i++) { leaveBreadcrumb( urlPrefix, sep, urlPostfix, compact, hyperl, path, i); } return hyperl.toString(); } /** * Leave a breadcrumb to allow navigation to one of the parent directories. * Write a hyperlink to the specified {@code StringBuilder}. * * @param urlPrefix what comes before the path in the URL * @param sep the character that separates path elements * @param urlPostfix what comes after the path in the URL * @param compact if {@code true}, remove {@code ..} and empty path * elements from the path in the link * @param hyperl a string builder to which the hyperlink is written * @param path all the elements of the full path * @param index which path element to create a link to */ private static void leaveBreadcrumb( String urlPrefix, char sep, String urlPostfix, boolean compact, StringBuilder hyperl, String[] path, int index) { // Only generate the link if the path element is non-empty. Empty // path elements could occur if the path contains two consecutive // separator characters, or if the path begins or ends with a path // separator. if (path[index].length() > 0) { hyperl.append(anchorLinkStart).append(urlPrefix); appendPath(path, index, hyperl, compact); hyperl.append(urlPostfix).append(closeQuotedTag). append(path[index]).append(anchorEnd); } // Add a separator between each path element, but not after the last // one. If the original path ended with a separator, the last element // of the path array is an empty string, which means that the final // separator will be printed. if (index < path.length - 1) { hyperl.append(sep); } } /** * Append parts of a file path to a {@code StringBuilder}. Separate each * element in the path with "/". The path elements from index 0 up to * index {@code lastIndex} (inclusive) are used. * * @param path array of path elements * @param lastIndex the index of the last path element to use * @param out the {@code StringBuilder} to which the path is appended * @param compact if {@code true}, remove {@code ..} and empty path * elements from the path in the link */ private static void appendPath( String[] path, int lastIndex, StringBuilder out, boolean compact) { final ArrayList<String> elements = new ArrayList<String>(lastIndex + 1); // Copy the relevant part of the path. If compact is false, just // copy the lastIndex first elements. If compact is true, remove empty // path elements, and follow .. up to the parent directory. Occurrences // of .. at the beginning of the path will be removed. for (int i = 0; i <= lastIndex; i++) { if (compact) { if ("..".equals(path[i])) { if (!elements.isEmpty()) { elements.remove(elements.size() - 1); } } else if (!"".equals(path[i])) { elements.add(path[i]); } } else { elements.add(path[i]); } } // Print the path with / between each element. No separator before // the first element or after the last element. for (int i = 0; i < elements.size(); i++) { out.append(elements.get(i)); if (i < elements.size() - 1) { out.append("/"); } } } /** * Generate a regex that matches the specified character. Escape it in * case it is a character that has a special meaning in a regex. * * @param c the character that the regex should match * @return a six-character string on the form <tt>&#92;u</tt><i>hhhh</i> */ private static String escapeForRegex(char c) { StringBuilder sb = new StringBuilder(6); sb.append("\\u"); String hex = Integer.toHexString((int) c); for (int i = 0; i < 4 - hex.length(); i++) { sb.append('0'); } sb.append(hex); return sb.toString(); } public static String redableSize(long num) { float l = (float) num; NumberFormat formatter = new DecimalFormat("#,###,###,###.#"); if (l < 1024) { return formatter.format(l); } else if (l < 1048576) { return (formatter.format(l / 1024) + "K"); } else { return ("<b>" + formatter.format(l / 1048576) + "M</b>"); } } public static void readableLine(int num, Writer out, Annotation annotation) throws IOException { String snum = String.valueOf(num); if (num > 1) { out.write("\n"); } out.write(anchorClassStart); out.write((num % 10 == 0 ? "hl" : "l")); out.write("\" name=\""); out.write(snum); + out.write("\" href=\"#"); + out.write(snum); out.write(closeQuotedTag); - out.write((num > 999 ? " " : (num > 99 ? " " : (num > 9 ? " " : " ")))); + out.write((num > 999 ? "&nbsp;&nbsp;&nbsp;" : (num > 99 ? "&nbsp;&nbsp;&nbsp;&nbsp;" : (num > 9 ? "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" : "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")))); out.write(snum); - out.write(" "); + out.write("&nbsp;"); out.write(anchorEnd); if (annotation != null) { String r = annotation.getRevision(num); boolean enabled = annotation.isEnabled(num); out.write("<span class=\"blame\"><span class=\"l\"> "); for (int i = r.length(); i < annotation.getWidestRevision(); i++) { out.write(" "); } if (enabled) { out.write(anchorLinkStart); out.write(URIEncode(annotation.getFilename())); out.write("?a=true&r="); out.write(URIEncode(r)); out.write(closeQuotedTag); } htmlize(r, out); if (enabled) { out.write(anchorEnd); } out.write(" </span>"); String a = annotation.getAuthor(num); out.write("<span class=\"l\"> "); for (int i = a.length(); i < annotation.getWidestAuthor(); i++) { out.write(" "); } String link = RuntimeEnvironment.getInstance().getUserPage(); if (link != null && link.length() > 0) { out.write(anchorLinkStart); out.write(link); out.write(URIEncode(a)); out.write(closeQuotedTag); htmlize(a, out); out.write(anchorEnd); } else { htmlize(a, out); } out.write(" </span></span>"); } } /** * Append path and date into a string in such a way that lexicographic * sorting gives the same results as a walk of the file hierarchy. Thus * null (\u0000) is used both to separate directory components and to * separate the path from the date. */ public static String uid(String path, String date) { return path.replace('/', '\u0000') + "\u0000" + date; } public static String uid2url(String uid) { String url = uid.replace('\u0000', '/'); // replace nulls with slashes return url.substring(0, url.lastIndexOf('/')); // remove date from end } public static String URIEncode(String q) { try { return URLEncoder.encode(q, "UTF-8"); } catch (UnsupportedEncodingException e) { // Should not happen. UTF-8 must be supported by JVMs. return null; } } public static String URIEncodePath(String path) { try { URI uri = new URI(null, null, path, null); return uri.getRawPath(); } catch (URISyntaxException ex) { OpenGrokLogger.getLogger().log(Level.WARNING, "Could not encode path " + path, ex); return ""; } } public static String formQuoteEscape(String q) { if (q == null) { return ""; } StringBuilder sb = new StringBuilder(); char c; for (int i = 0; i < q.length(); i++) { c = q.charAt(i); if (c == '"') { sb.append("&quot;"); } else { sb.append(c); } } return sb.toString(); } /** * Build a string that may be converted to a Query and passed to Lucene. * All parameters may be passed as null or an empty string to indicate that * they are unused. * * @param freetext The string from the "Full Search" text-field. This field * will be applied as it is specified. * @param defs The string from the "Definition" text-field. This field * will be searched for in the <b>defs</b> field in the lucene * index. All occurences of ":" will be replaced with "\:" * @param refs The string from the "Symbol" text-field. This field * will be searched for in the <b>refs</b> field in the lucene * index. All occurences of ":" will be replaced with "\:" * @param path The string from the "File Path" text-field. This field * will be searched for in the <b>path</b> field in the lucene * index. All occurences of ":" will be replaced with "\:" * @param hist The string from the "History" text-field. This field * will be searched for in the <b>hist</b> field in the lucene * index. All occurences of ":" will be replaced with "\:" * @return A string to be parsed by the Lucene parser. */ public static String buildQueryString(String freetext, String defs, String refs, String path, String hist) { StringBuilder sb = new StringBuilder(); if (freetext != null && freetext.length() > 0) { sb.append(freetext.replace("::", "\\:\\:")); } if (defs != null && defs.length() > 0) { sb.append(" defs:("); sb.append(escapeQueryString(defs)); sb.append(")"); } if (refs != null && refs.length() > 0) { sb.append(" refs:("); sb.append(escapeQueryString(refs)); sb.append(")"); } if (path != null && path.length() > 0) { sb.append(" path:("); sb.append(escapeQueryString(path)); sb.append(")"); } if (hist != null && hist.length() > 0) { sb.append(" hist:("); sb.append(escapeQueryString(hist)); sb.append(")"); } return sb.toString(); } private static String escapeQueryString(String input) { return input.replace(":", "\\:"); } }
false
true
public static void readableLine(int num, Writer out, Annotation annotation) throws IOException { String snum = String.valueOf(num); if (num > 1) { out.write("\n"); } out.write(anchorClassStart); out.write((num % 10 == 0 ? "hl" : "l")); out.write("\" name=\""); out.write(snum); out.write(closeQuotedTag); out.write((num > 999 ? " " : (num > 99 ? " " : (num > 9 ? " " : " ")))); out.write(snum); out.write(" "); out.write(anchorEnd); if (annotation != null) { String r = annotation.getRevision(num); boolean enabled = annotation.isEnabled(num); out.write("<span class=\"blame\"><span class=\"l\"> "); for (int i = r.length(); i < annotation.getWidestRevision(); i++) { out.write(" "); } if (enabled) { out.write(anchorLinkStart); out.write(URIEncode(annotation.getFilename())); out.write("?a=true&r="); out.write(URIEncode(r)); out.write(closeQuotedTag); } htmlize(r, out); if (enabled) { out.write(anchorEnd); } out.write(" </span>"); String a = annotation.getAuthor(num); out.write("<span class=\"l\"> "); for (int i = a.length(); i < annotation.getWidestAuthor(); i++) { out.write(" "); } String link = RuntimeEnvironment.getInstance().getUserPage(); if (link != null && link.length() > 0) { out.write(anchorLinkStart); out.write(link); out.write(URIEncode(a)); out.write(closeQuotedTag); htmlize(a, out); out.write(anchorEnd); } else { htmlize(a, out); } out.write(" </span></span>"); } }
public static void readableLine(int num, Writer out, Annotation annotation) throws IOException { String snum = String.valueOf(num); if (num > 1) { out.write("\n"); } out.write(anchorClassStart); out.write((num % 10 == 0 ? "hl" : "l")); out.write("\" name=\""); out.write(snum); out.write("\" href=\"#"); out.write(snum); out.write(closeQuotedTag); out.write((num > 999 ? "&nbsp;&nbsp;&nbsp;" : (num > 99 ? "&nbsp;&nbsp;&nbsp;&nbsp;" : (num > 9 ? "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" : "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")))); out.write(snum); out.write("&nbsp;"); out.write(anchorEnd); if (annotation != null) { String r = annotation.getRevision(num); boolean enabled = annotation.isEnabled(num); out.write("<span class=\"blame\"><span class=\"l\"> "); for (int i = r.length(); i < annotation.getWidestRevision(); i++) { out.write(" "); } if (enabled) { out.write(anchorLinkStart); out.write(URIEncode(annotation.getFilename())); out.write("?a=true&r="); out.write(URIEncode(r)); out.write(closeQuotedTag); } htmlize(r, out); if (enabled) { out.write(anchorEnd); } out.write(" </span>"); String a = annotation.getAuthor(num); out.write("<span class=\"l\"> "); for (int i = a.length(); i < annotation.getWidestAuthor(); i++) { out.write(" "); } String link = RuntimeEnvironment.getInstance().getUserPage(); if (link != null && link.length() > 0) { out.write(anchorLinkStart); out.write(link); out.write(URIEncode(a)); out.write(closeQuotedTag); htmlize(a, out); out.write(anchorEnd); } else { htmlize(a, out); } out.write(" </span></span>"); } }
diff --git a/src/core/org/luaj/lib/PackageLib.java b/src/core/org/luaj/lib/PackageLib.java index b8a0380..b491ae9 100644 --- a/src/core/org/luaj/lib/PackageLib.java +++ b/src/core/org/luaj/lib/PackageLib.java @@ -1,420 +1,419 @@ /******************************************************************************* * Copyright (c) 2007 LuaJ. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ package org.luaj.lib; import java.io.InputStream; import java.io.PrintStream; import java.util.Vector; import org.luaj.vm.CallInfo; import org.luaj.vm.LBoolean; import org.luaj.vm.LFunction; import org.luaj.vm.LNil; import org.luaj.vm.LString; import org.luaj.vm.LTable; import org.luaj.vm.LValue; import org.luaj.vm.Lua; import org.luaj.vm.LuaState; import org.luaj.vm.Platform; public class PackageLib extends LFunction { public static final String DEFAULT_LUA_PATH = "?.luac;?.lua"; public static InputStream STDIN = null; public static PrintStream STDOUT = System.out; public static LTable LOADED = null; private static final LString _M = new LString("_M"); private static final LString _NAME = new LString("_NAME"); private static final LString _PACKAGE = new LString("_PACKAGE"); private static final LString _DOT = new LString("."); private static final LString _EMPTY = new LString(""); private static final LString __INDEX = new LString("__index"); private static final LString _LOADERS = new LString("loaders"); private static final LString _PRELOAD = new LString("preload"); private static final LString _PATH = new LString("path"); private static final LValue _SENTINEL = _EMPTY; private static final LString _LUA_PATH = new LString(DEFAULT_LUA_PATH); private static final String[] NAMES = { "package", "module", "require", "loadlib", "seeall", "preload_loader", "lua_loader", "java_loader", }; private static final int INSTALL = 0; private static final int MODULE = 1; private static final int REQUIRE = 2; private static final int LOADLIB = 3; private static final int SEEALL = 4; private static final int PRELOAD_LOADER = 5; private static final int LUA_LOADER = 6; private static final int JAVA_LOADER = 7; // all functions in package share this environment private static LTable pckg; public static void install( LTable globals ) { for ( int i=1; i<=REQUIRE; i++ ) globals.put( NAMES[i], new PackageLib(i) ); pckg = new LTable(); for ( int i=LOADLIB; i<=SEEALL; i++ ) pckg.put( NAMES[i], new PackageLib(i) ); LOADED = new LTable(); pckg.put( "loaded", LOADED ); pckg.put( _PRELOAD, new LTable() ); LTable loaders = new LTable(3,0); for ( int i=PRELOAD_LOADER; i<=JAVA_LOADER; i++ ) loaders.luaInsertPos(0, new PackageLib(i) ); pckg.put( "loaders", loaders ); pckg.put( _PATH, _LUA_PATH ); globals.put( "package", pckg ); } public static void setLuaPath( String newLuaPath ) { pckg.put( _PATH, new LString(newLuaPath) ); } private final int id; private PackageLib( int id ) { this.id = id; } public String toString() { return NAMES[id]+"()"; } public boolean luaStackCall( LuaState vm ) { switch ( id ) { case INSTALL: install(vm._G); break; case MODULE: module(vm); break; case REQUIRE: require(vm); break; case LOADLIB: loadlib(vm); break; case SEEALL: { if ( ! vm.istable(2) ) vm.error( "table expected, got "+vm.typename(2) ); LTable t = vm.totable(2); LTable m = t.luaGetMetatable(); if ( m == null ) t.luaSetMetatable(m = new LTable()); m.put(__INDEX, vm._G); vm.resettop(); break; } case PRELOAD_LOADER: { loader_preload(vm); break; } case LUA_LOADER: { loader_Lua(vm); break; } case JAVA_LOADER: { loader_Java(vm); break; } default: LuaState.vmerror( "bad package id" ); } return false; } // ======================== Module, Package loading ============================= /** * module (name [, ...]) * * Creates a module. If there is a table in package.loaded[name], this table * is the module. Otherwise, if there is a global table t with the given * name, this table is the module. Otherwise creates a new table t and sets * it as the value of the global name and the value of package.loaded[name]. * This function also initializes t._NAME with the given name, t._M with the * module (t itself), and t._PACKAGE with the package name (the full module * name minus last component; see below). Finally, module sets t as the new * environment of the current function and the new value of * package.loaded[name], so that require returns t. * * If name is a compound name (that is, one with components separated by * dots), module creates (or reuses, if they already exist) tables for each * component. For instance, if name is a.b.c, then module stores the module * table in field c of field b of global a. * * This function may receive optional options after the module name, where * each option is a function to be applied over the module. */ public static void module(LuaState vm) { LString modname = vm.tolstring(2); int n = vm.gettop(); LValue value = LOADED.get(modname); LTable module; if ( value.luaGetType() != Lua.LUA_TTABLE ) { /* not found? */ /* try global variable (and create one if it does not exist) */ module = findtable( vm._G, modname ); if ( module == null ) vm.error( "name conflict for module '"+modname+"'" ); LOADED.luaSetTable(vm, LOADED, modname, module); } else { module = (LTable) value; } /* check whether table already has a _NAME field */ LValue name = module.luaGetTable(vm, module, _NAME); if ( name.isNil() ) { modinit( vm, module, modname ); } // set the environment of the current function CallInfo ci = vm.getStackFrame(0); ci.closure.env = module; // apply the functions for ( int i=3; i<=n; i++ ) { vm.pushvalue( i ); /* get option (a function) */ vm.pushlvalue( module ); /* module */ vm.call( 1, 0 ); } // returns no results vm.resettop(); } /** * * @param table the table at which to start the search * @param fname the name to look up or create, such as "abc.def.ghi" * @return the table for that name, possible a new one, or null if a non-table has that name already. */ private static LTable findtable(LTable table, LString fname) { int b, e=(-1); do { e = fname.indexOf(_DOT, b=e+1 ); if ( e < 0 ) e = fname.m_length; LString key = fname.substring(b, e); LValue val = table.get(key); if ( val.isNil() ) { /* no such field? */ LTable field = new LTable(); /* new table for field */ table.put(key, field); table = field; } else if ( val.luaGetType() != Lua.LUA_TTABLE ) { /* field has a non-table value? */ return null; } else { table = (LTable) val; } } while ( e < fname.m_length ); return table; } private static void modinit(LuaState vm, LTable module, LString modname) { /* module._M = module */ module.luaSetTable(vm, module, _M, module); int e = modname.lastIndexOf(_DOT); module.luaSetTable(vm, module, _NAME, modname ); module.luaSetTable(vm, module, _PACKAGE, (e<0? _EMPTY: modname.substring(0,e+1)) ); } /** * require (modname) * * Loads the given module. The function starts by looking into the package.loaded table to * determine whether modname is already loaded. If it is, then require returns the value * stored at package.loaded[modname]. Otherwise, it tries to find a loader for the module. * * To find a loader, require is guided by the package.loaders array. By changing this array, * we can change how require looks for a module. The following explanation is based on the * default configuration for package.loaders. * * First require queries package.preload[modname]. If it has a value, this value * (which should be a function) is the loader. Otherwise require searches for a Lua loader * using the path stored in package.path. If that also fails, it searches for a C loader * using the path stored in package.cpath. If that also fails, it tries an all-in-one loader * (see package.loaders). * * Once a loader is found, require calls the loader with a single argument, modname. * If the loader returns any value, require assigns the returned value to package.loaded[modname]. * If the loader returns no value and has not assigned any value to package.loaded[modname], * then require assigns true to this entry. In any case, require returns the final value of * package.loaded[modname]. * * If there is any error loading or running the module, or if it cannot find any loader for * the module, then require signals an error. */ public void require( LuaState vm ) { LString name = vm.tolstring(2); LValue loaded = LOADED.get(name); if ( loaded.toJavaBoolean() ) { if ( loaded == _SENTINEL ) vm.error("loop or previous error loading module '"+name+"'"); vm.resettop(); vm.pushlvalue( loaded ); return; } - vm.settop(0); + vm.resettop(); /* else must load it; iterate over available loaders */ LValue val = pckg.luaGetTable(vm, pckg, _LOADERS); if ( ! val.isTable() ) vm.error( "'package.loaders' must be a table" ); vm.pushlvalue(val); Vector v = new Vector(); for ( int i=1; true; i++ ) { vm.rawgeti(1, i); if ( vm.isnil(-1) ) { vm.error( "module '"+name+"' not found: "+v ); } /* call loader with module name as argument */ vm.pushlstring(name); vm.call(1, 1); if ( vm.isfunction(-1) ) break; /* module loaded successfully */ if ( vm.isstring(-1) ) /* loader returned error message? */ v.addElement(vm.tolstring(-1)); /* accumulate it */ vm.pop(1); } // load the module using the loader LOADED.luaSetTable(vm, LOADED, name, _SENTINEL); vm.pushlstring( name ); /* pass name as argument to module */ vm.call( 1, 1 ); /* run loaded module */ if ( ! vm.isnil(-1) ) /* non-nil return? */ LOADED.luaSetTable(vm, LOADED, name, vm.topointer(-1) ); /* _LOADED[name] = returned value */ - LOADED.luaGetTable(vm, LOADED, name); - if ( vm.topointer(-1) == _SENTINEL ) { /* module did not set a value? */ + if ( LOADED.luaGetTable(vm, LOADED, name) == _SENTINEL ) { /* module did not set a value? */ LOADED.luaSetTable(vm, LOADED, name, LBoolean.TRUE ); /* _LOADED[name] = true */ vm.pushboolean(true); } - vm.insert(1); + vm.replace(1); vm.settop(1); } public static void loadlib( LuaState vm ) { vm.error( "loadlib not implemented" ); } private void loader_preload( LuaState vm ) { LString name = vm.tolstring(2); LValue preload = pckg.luaGetTable(vm, pckg, _PRELOAD); if ( ! preload.isTable() ) vm.error("package.preload '"+name+"' must be a table"); LValue val = preload.luaGetTable(vm, preload, name); if ( val.isNil() ) vm.pushstring("\n\tno field package.preload['"+name+"']"); vm.resettop(); vm.pushlvalue(val); } private void loader_Lua( LuaState vm ) { String name = vm.tostring(2); InputStream is = findfile( vm, name, _PATH ); if ( is != null ) { String filename = vm.tostring(-1); if ( ! BaseLib.loadis(vm, is, filename) ) loaderror( vm, filename ); } vm.insert(1); vm.settop(1); } private void loader_Java( LuaState vm ) { String name = vm.tostring(2); Class c = null; LValue v = null; try { c = Class.forName(name); v = (LValue) c.newInstance(); vm.pushlvalue( v ); } catch ( ClassNotFoundException cnfe ) { vm.pushstring("\n\tno class '"+name+"'" ); } catch ( Exception e ) { vm.pushstring("\n\tjava load failed on '"+name+"', "+e ); } vm.insert(1); vm.settop(1); } private InputStream findfile(LuaState vm, String name, LString pname) { Platform p = Platform.getInstance(); LValue pkg = pckg.luaGetTable(vm, pckg, pname); if ( ! pkg.isString() ) vm.error("package."+pname+" must be a string"); String path = pkg.toJavaString(); int e = -1; int n = path.length(); StringBuffer sb = null; name = name.replace('.','/'); while ( e < n ) { // find next template int b = e+1; e = path.indexOf(';',b); if ( e < 0 ) e = path.length(); String template = path.substring(b,e); // create filename int q = template.indexOf('?'); String filename = template; if ( q >= 0 ) { filename = template.substring(0,q) + name + template.substring(q+1); } // try opening the file InputStream is = p.openFile(filename); if ( is != null ) { vm.pushstring(filename); return is; } // report error if ( sb == null ) sb = new StringBuffer(); sb.append( "\n\tno file '"+filename+"'"); } // not found, push error on stack and return vm.pushstring(sb.toString()); return null; } private static void loaderror(LuaState vm, String filename) { vm.error( "error loading module '"+vm.tostring(1)+"' from file '"+filename+"':\n\t"+vm.tostring(-1) ); } }
false
true
public void require( LuaState vm ) { LString name = vm.tolstring(2); LValue loaded = LOADED.get(name); if ( loaded.toJavaBoolean() ) { if ( loaded == _SENTINEL ) vm.error("loop or previous error loading module '"+name+"'"); vm.resettop(); vm.pushlvalue( loaded ); return; } vm.settop(0); /* else must load it; iterate over available loaders */ LValue val = pckg.luaGetTable(vm, pckg, _LOADERS); if ( ! val.isTable() ) vm.error( "'package.loaders' must be a table" ); vm.pushlvalue(val); Vector v = new Vector(); for ( int i=1; true; i++ ) { vm.rawgeti(1, i); if ( vm.isnil(-1) ) { vm.error( "module '"+name+"' not found: "+v ); } /* call loader with module name as argument */ vm.pushlstring(name); vm.call(1, 1); if ( vm.isfunction(-1) ) break; /* module loaded successfully */ if ( vm.isstring(-1) ) /* loader returned error message? */ v.addElement(vm.tolstring(-1)); /* accumulate it */ vm.pop(1); } // load the module using the loader LOADED.luaSetTable(vm, LOADED, name, _SENTINEL); vm.pushlstring( name ); /* pass name as argument to module */ vm.call( 1, 1 ); /* run loaded module */ if ( ! vm.isnil(-1) ) /* non-nil return? */ LOADED.luaSetTable(vm, LOADED, name, vm.topointer(-1) ); /* _LOADED[name] = returned value */ LOADED.luaGetTable(vm, LOADED, name); if ( vm.topointer(-1) == _SENTINEL ) { /* module did not set a value? */ LOADED.luaSetTable(vm, LOADED, name, LBoolean.TRUE ); /* _LOADED[name] = true */ vm.pushboolean(true); } vm.insert(1); vm.settop(1); }
public void require( LuaState vm ) { LString name = vm.tolstring(2); LValue loaded = LOADED.get(name); if ( loaded.toJavaBoolean() ) { if ( loaded == _SENTINEL ) vm.error("loop or previous error loading module '"+name+"'"); vm.resettop(); vm.pushlvalue( loaded ); return; } vm.resettop(); /* else must load it; iterate over available loaders */ LValue val = pckg.luaGetTable(vm, pckg, _LOADERS); if ( ! val.isTable() ) vm.error( "'package.loaders' must be a table" ); vm.pushlvalue(val); Vector v = new Vector(); for ( int i=1; true; i++ ) { vm.rawgeti(1, i); if ( vm.isnil(-1) ) { vm.error( "module '"+name+"' not found: "+v ); } /* call loader with module name as argument */ vm.pushlstring(name); vm.call(1, 1); if ( vm.isfunction(-1) ) break; /* module loaded successfully */ if ( vm.isstring(-1) ) /* loader returned error message? */ v.addElement(vm.tolstring(-1)); /* accumulate it */ vm.pop(1); } // load the module using the loader LOADED.luaSetTable(vm, LOADED, name, _SENTINEL); vm.pushlstring( name ); /* pass name as argument to module */ vm.call( 1, 1 ); /* run loaded module */ if ( ! vm.isnil(-1) ) /* non-nil return? */ LOADED.luaSetTable(vm, LOADED, name, vm.topointer(-1) ); /* _LOADED[name] = returned value */ if ( LOADED.luaGetTable(vm, LOADED, name) == _SENTINEL ) { /* module did not set a value? */ LOADED.luaSetTable(vm, LOADED, name, LBoolean.TRUE ); /* _LOADED[name] = true */ vm.pushboolean(true); } vm.replace(1); vm.settop(1); }
diff --git a/SQLENGINE_A1/SqlConsole.java b/SQLENGINE_A1/SqlConsole.java index 59793a2..80bb9eb 100755 --- a/SQLENGINE_A1/SqlConsole.java +++ b/SQLENGINE_A1/SqlConsole.java @@ -1,25 +1,25 @@ package sqlengine_a1; import java.util.*; import sqlengine_a1.parser.*; public class SqlConsole { - public static void main(String[] args) { - Scanner stdin = new Scanner(System.in); + public static void main(String[] args) { + Scanner stdin = new Scanner(System.in); while (true) { System.out.print("|> "); String line = stdin.nextLine(); try { SqlParser sp = new SqlParser(line); ASTNode astRoot = sp.parseStatement(); System.out.println(astRoot.toString()); if (astRoot.type == ASTNode.Type.QUIT_STATEMENT) return; } catch (ParseError e) { System.err.println("Parse error: " + e); } - } - } + } + } }
false
true
public static void main(String[] args) { Scanner stdin = new Scanner(System.in); while (true) { System.out.print("|> "); String line = stdin.nextLine(); try { SqlParser sp = new SqlParser(line); ASTNode astRoot = sp.parseStatement(); System.out.println(astRoot.toString()); if (astRoot.type == ASTNode.Type.QUIT_STATEMENT) return; } catch (ParseError e) { System.err.println("Parse error: " + e); } } }
public static void main(String[] args) { Scanner stdin = new Scanner(System.in); while (true) { System.out.print("|> "); String line = stdin.nextLine(); try { SqlParser sp = new SqlParser(line); ASTNode astRoot = sp.parseStatement(); System.out.println(astRoot.toString()); if (astRoot.type == ASTNode.Type.QUIT_STATEMENT) return; } catch (ParseError e) { System.err.println("Parse error: " + e); } } }
diff --git a/src/java/fi/hoski/web/auth/LoginServlet.java b/src/java/fi/hoski/web/auth/LoginServlet.java index f6fb476..92e9f88 100644 --- a/src/java/fi/hoski/web/auth/LoginServlet.java +++ b/src/java/fi/hoski/web/auth/LoginServlet.java @@ -1,219 +1,220 @@ /* * Copyright (C) 2012 Helsingfors Segelklubb ry * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fi.hoski.web.auth; import fi.hoski.datastore.EmailNotUniqueException; import fi.hoski.web.google.DatastoreUserDirectory; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.UnavailableException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.Cookie; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import static fi.hoski.web.auth.UserDirectory.EMAIL; /** * LoginServlet authenticates the user using e-mail and password as the login * credentials. The login servlet creates a servlet session where it stores the * user object. * * The Login Servlet is designed to be used through AJAX. */ public class LoginServlet extends HttpServlet { public static final long serialVersionUID = -1; public static final String USER = "fi.hoski.web.user"; private UserDirectory userDirectory; @Override public void init() { userDirectory = new DatastoreUserDirectory(); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); + response.setHeader("Cache-Control", "private, max-age=0, no-cache"); String action = request.getParameter("action"); try { if (action == null || action.equals("login")) { // login String email = request.getParameter("email"); String password = request.getParameter("password"); email = (email != null) ? email.trim() : null; // 1. check params if (email == null || email.isEmpty() || password == null || password.isEmpty()) { log("email or password not ok"); response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { // 2. check user exists Map<String, Object> user = userDirectory.authenticateUser(email, password); if (user == null) { log("user not found"); response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { // 3. create session HttpSession session = request.getSession(true); session.setAttribute(USER, user); response.getWriter().println("Logged in"); } } } else { // logout HttpSession session = request.getSession(false); if (session != null) { session.setAttribute(USER, null); session.invalidate(); } // change Cookie so that Vary: Cookie works Cookie c = new Cookie("JSESSIONID", null); c.setMaxAge(0); response.addCookie(c); response.getWriter().println("Logged out"); } } catch (UnavailableException ex) { log(ex.getMessage(), ex); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); } catch (EmailNotUniqueException ex) { log(ex.getMessage(), ex); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); String email = request.getParameter("email"); String activationKey = request.getParameter("activationKey"); try { if (email != null && activationKey != null) { Map<String, Object> user = userDirectory.useActivationKey(email, activationKey); if (user != null) { HttpSession session = request.getSession(true); session.setAttribute(USER, user); } // redirect always, if user is not logged in, // there will be a login screen response.sendRedirect("/member"); //TODO target make configurable } else { HttpSession session = request.getSession(false); String etag = request.getHeader("If-None-Match"); @SuppressWarnings("unchecked") Map<String, Object> user = (session != null) ? (Map<String, Object>) session.getAttribute(USER) : null; String userEtag = getEtag(user); if (etag != null && etag.equals(userEtag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { response.setHeader("ETag", userEtag); response.setHeader("Cache-Control", "private"); response.setHeader("Vary", "Cookie"); writeUserJSON(user, response); } } } catch (UnavailableException ex) { log(ex.getMessage(), ex); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); } catch (EmailNotUniqueException ex) { log(ex.getMessage(), ex); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); } } private void writeUserJSON(Map<String, Object> user, HttpServletResponse response) throws ServletException, IOException { try { response.setContentType("application/json"); JSONObject json = new JSONObject(); json.put("user", getUserJSON(user)); response.getWriter().println(json.toString(4)); //json.write(response.getWriter()); } catch (JSONException e) { throw new ServletException("Could not serialize user object"); } } private Object getUserJSON(Map<String, Object> user) throws JSONException { if (user != null) { JSONObject userjson = new JSONObject(); for (Map.Entry<String, Object> entry : user.entrySet()) { Object ob = entry.getValue(); if (ob instanceof List) { List opt = (List) ob; JSONArray optarray = new JSONArray(); for (Object etr : opt) { if (etr instanceof Map) { etr = getUserJSON((Map<String, Object>) etr); } // else expect it to be primitive type optarray.put(etr); } userjson.put(entry.getKey(), optarray); } else { userjson.put(entry.getKey(), ob); } } return userjson; } else { return JSONObject.NULL; } } private String getEtag(Map<String, Object> user) { if (user == null) { return "\"null\""; } else { String tag = (String) user.get(EMAIL); tag = (tag != null) ? tag.replace('"', '_') : null; return '"' + tag + '"'; } } }
true
true
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); String action = request.getParameter("action"); try { if (action == null || action.equals("login")) { // login String email = request.getParameter("email"); String password = request.getParameter("password"); email = (email != null) ? email.trim() : null; // 1. check params if (email == null || email.isEmpty() || password == null || password.isEmpty()) { log("email or password not ok"); response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { // 2. check user exists Map<String, Object> user = userDirectory.authenticateUser(email, password); if (user == null) { log("user not found"); response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { // 3. create session HttpSession session = request.getSession(true); session.setAttribute(USER, user); response.getWriter().println("Logged in"); } } } else { // logout HttpSession session = request.getSession(false); if (session != null) { session.setAttribute(USER, null); session.invalidate(); } // change Cookie so that Vary: Cookie works Cookie c = new Cookie("JSESSIONID", null); c.setMaxAge(0); response.addCookie(c); response.getWriter().println("Logged out"); } } catch (UnavailableException ex) { log(ex.getMessage(), ex); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); } catch (EmailNotUniqueException ex) { log(ex.getMessage(), ex); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); } }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setHeader("Cache-Control", "private, max-age=0, no-cache"); String action = request.getParameter("action"); try { if (action == null || action.equals("login")) { // login String email = request.getParameter("email"); String password = request.getParameter("password"); email = (email != null) ? email.trim() : null; // 1. check params if (email == null || email.isEmpty() || password == null || password.isEmpty()) { log("email or password not ok"); response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { // 2. check user exists Map<String, Object> user = userDirectory.authenticateUser(email, password); if (user == null) { log("user not found"); response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { // 3. create session HttpSession session = request.getSession(true); session.setAttribute(USER, user); response.getWriter().println("Logged in"); } } } else { // logout HttpSession session = request.getSession(false); if (session != null) { session.setAttribute(USER, null); session.invalidate(); } // change Cookie so that Vary: Cookie works Cookie c = new Cookie("JSESSIONID", null); c.setMaxAge(0); response.addCookie(c); response.getWriter().println("Logged out"); } } catch (UnavailableException ex) { log(ex.getMessage(), ex); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); } catch (EmailNotUniqueException ex) { log(ex.getMessage(), ex); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); } }
diff --git a/modules/testkit/src/main/java/org/apache/axis2/transport/testkit/axis2/client/AxisTestClient.java b/modules/testkit/src/main/java/org/apache/axis2/transport/testkit/axis2/client/AxisTestClient.java index c0c607c..d865e0a 100644 --- a/modules/testkit/src/main/java/org/apache/axis2/transport/testkit/axis2/client/AxisTestClient.java +++ b/modules/testkit/src/main/java/org/apache/axis2/transport/testkit/axis2/client/AxisTestClient.java @@ -1,158 +1,158 @@ /* * 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.axis2.transport.testkit.axis2.client; import javax.mail.internet.ContentType; import javax.xml.namespace.QName; import junit.framework.Assert; import junit.framework.AssertionFailedError; import org.apache.axiom.attachments.Attachments; import org.apache.axis2.Constants; import org.apache.axis2.client.OperationClient; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; import org.apache.axis2.context.MessageContext; import org.apache.axis2.transport.TransportSender; import org.apache.axis2.transport.base.BaseConstants; import org.apache.axis2.transport.base.ManagementSupport; import org.apache.axis2.transport.testkit.MessageExchangeValidator; import org.apache.axis2.transport.testkit.axis2.util.MessageLevelMetricsCollectorImpl; import org.apache.axis2.transport.testkit.channel.Channel; import org.apache.axis2.transport.testkit.client.ClientOptions; import org.apache.axis2.transport.testkit.client.TestClient; import org.apache.axis2.transport.testkit.message.AxisMessage; import org.apache.axis2.transport.testkit.name.Name; import org.apache.axis2.transport.testkit.tests.Setup; import org.apache.axis2.transport.testkit.tests.TearDown; import org.apache.axis2.transport.testkit.tests.Transient; import org.apache.axis2.transport.testkit.util.ContentTypeUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @Name("axis") public class AxisTestClient implements TestClient, MessageExchangeValidator { private static final Log log = LogFactory.getLog(AxisTestClient.class); private @Transient AxisTestClientConfigurator[] configurators; private @Transient TransportSender sender; protected @Transient ServiceClient serviceClient; protected @Transient Options axisOptions; private long messagesSent; private long bytesSent; private MessageLevelMetricsCollectorImpl metrics; @Setup @SuppressWarnings("unused") private void setUp(AxisTestClientContext context, Channel channel, AxisTestClientConfigurator[] configurators) throws Exception { this.configurators = configurators; sender = context.getSender(); serviceClient = new ServiceClient(context.getConfigurationContext(), null); axisOptions = new Options(); axisOptions.setTo(channel.getEndpointReference()); serviceClient.setOptions(axisOptions); } @TearDown @SuppressWarnings("unused") private void tearDown() throws Exception { serviceClient.cleanup(); } public ContentType getContentType(ClientOptions options, ContentType contentType) { // TODO: this may be incorrect in some cases String charset = options.getCharset(); if (charset == null) { return contentType; } else { return ContentTypeUtil.addCharset(contentType, options.getCharset()); } } public void beforeSend() throws Exception { if (sender instanceof ManagementSupport) { ManagementSupport sender = (ManagementSupport)this.sender; messagesSent = sender.getMessagesSent(); bytesSent = sender.getBytesSent(); metrics = new MessageLevelMetricsCollectorImpl(); } else { metrics = null; } } protected MessageContext send(ClientOptions options, AxisMessage message, QName operationQName, boolean block, String resultMessageLabel) throws Exception { OperationClient mepClient = serviceClient.createClient(operationQName); MessageContext mc = new MessageContext(); mc.setProperty(Constants.Configuration.MESSAGE_TYPE, message.getMessageType()); mc.setEnvelope(message.getEnvelope()); Attachments attachments = message.getAttachments(); if (attachments != null) { mc.setAttachmentMap(attachments); mc.setDoingSwA(true); mc.setProperty(Constants.Configuration.ENABLE_SWA, true); } for (AxisTestClientConfigurator configurator : configurators) { configurator.setupRequestMessageContext(mc); } mc.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, options.getCharset()); mc.setServiceContext(serviceClient.getServiceContext()); if (metrics != null) { mc.setProperty(BaseConstants.METRICS_COLLECTOR, metrics); } mepClient.addMessageContext(mc); mepClient.execute(block); mepClient.complete(mc); return resultMessageLabel == null ? null : mepClient.getMessageContext(resultMessageLabel); } public void afterReceive() throws Exception { if (sender instanceof ManagementSupport) { ManagementSupport sender = (ManagementSupport)this.sender; synchronized (metrics) { long start = System.currentTimeMillis(); while (true) { try { Assert.assertEquals(1, metrics.getMessagesSent()); Assert.assertEquals(messagesSent+1, sender.getMessagesSent()); long thisBytesSent = metrics.getBytesSent(); Assert.assertTrue("No increase in bytes sent in message level metrics", thisBytesSent != 0); long newBytesSent = sender.getBytesSent(); Assert.assertTrue("No increase in bytes sent in transport level metrics", newBytesSent > bytesSent); Assert.assertEquals("Mismatch between message and transport level metrics", thisBytesSent, newBytesSent - bytesSent); break; } catch (AssertionFailedError ex) { // SYNAPSE-491: Maybe the transport sender didn't finish updating the // metrics yet. We give it a couple of seconds to do so. long remaining = start + 5000 - System.currentTimeMillis(); - if (remaining < 0) { + if (remaining <= 0) { throw ex; } else { log.debug("The transport sender didn't update the metrics yet (" + ex.getMessage() + "). Waiting for " + remaining + " ms."); metrics.wait(remaining); } } } } log.debug("Message level metrics check OK"); } } }
true
true
public void afterReceive() throws Exception { if (sender instanceof ManagementSupport) { ManagementSupport sender = (ManagementSupport)this.sender; synchronized (metrics) { long start = System.currentTimeMillis(); while (true) { try { Assert.assertEquals(1, metrics.getMessagesSent()); Assert.assertEquals(messagesSent+1, sender.getMessagesSent()); long thisBytesSent = metrics.getBytesSent(); Assert.assertTrue("No increase in bytes sent in message level metrics", thisBytesSent != 0); long newBytesSent = sender.getBytesSent(); Assert.assertTrue("No increase in bytes sent in transport level metrics", newBytesSent > bytesSent); Assert.assertEquals("Mismatch between message and transport level metrics", thisBytesSent, newBytesSent - bytesSent); break; } catch (AssertionFailedError ex) { // SYNAPSE-491: Maybe the transport sender didn't finish updating the // metrics yet. We give it a couple of seconds to do so. long remaining = start + 5000 - System.currentTimeMillis(); if (remaining < 0) { throw ex; } else { log.debug("The transport sender didn't update the metrics yet (" + ex.getMessage() + "). Waiting for " + remaining + " ms."); metrics.wait(remaining); } } } } log.debug("Message level metrics check OK"); } }
public void afterReceive() throws Exception { if (sender instanceof ManagementSupport) { ManagementSupport sender = (ManagementSupport)this.sender; synchronized (metrics) { long start = System.currentTimeMillis(); while (true) { try { Assert.assertEquals(1, metrics.getMessagesSent()); Assert.assertEquals(messagesSent+1, sender.getMessagesSent()); long thisBytesSent = metrics.getBytesSent(); Assert.assertTrue("No increase in bytes sent in message level metrics", thisBytesSent != 0); long newBytesSent = sender.getBytesSent(); Assert.assertTrue("No increase in bytes sent in transport level metrics", newBytesSent > bytesSent); Assert.assertEquals("Mismatch between message and transport level metrics", thisBytesSent, newBytesSent - bytesSent); break; } catch (AssertionFailedError ex) { // SYNAPSE-491: Maybe the transport sender didn't finish updating the // metrics yet. We give it a couple of seconds to do so. long remaining = start + 5000 - System.currentTimeMillis(); if (remaining <= 0) { throw ex; } else { log.debug("The transport sender didn't update the metrics yet (" + ex.getMessage() + "). Waiting for " + remaining + " ms."); metrics.wait(remaining); } } } } log.debug("Message level metrics check OK"); } }
diff --git a/src/main/java/com/google/mockwebserver/MockWebServer.java b/src/main/java/com/google/mockwebserver/MockWebServer.java index 5116991d..75f42cd0 100644 --- a/src/main/java/com/google/mockwebserver/MockWebServer.java +++ b/src/main/java/com/google/mockwebserver/MockWebServer.java @@ -1,567 +1,565 @@ /* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mockwebserver; import static com.google.mockwebserver.SocketPolicy.DISCONNECT_AT_START; import static com.google.mockwebserver.SocketPolicy.FAIL_HANDSHAKE; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Proxy; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * A scriptable web server. Callers supply canned responses and the server * replays them upon request in sequence. */ public final class MockWebServer { static final String ASCII = "US-ASCII"; private static final Logger logger = Logger.getLogger(MockWebServer.class.getName()); private final BlockingQueue<RecordedRequest> requestQueue = new LinkedBlockingQueue<RecordedRequest>(); private final BlockingQueue<MockResponse> responseQueue = new LinkedBlockingDeque<MockResponse>(); private final Set<Socket> openClientSockets = Collections.newSetFromMap(new ConcurrentHashMap<Socket, Boolean>()); private boolean singleResponse; private final AtomicInteger requestCount = new AtomicInteger(); private int bodyLimit = Integer.MAX_VALUE; private ServerSocket serverSocket; private SSLSocketFactory sslSocketFactory; private ExecutorService executor; private boolean tunnelProxy; private int port = -1; public int getPort() { if (port == -1) { throw new IllegalStateException("Cannot retrieve port before calling play()"); } return port; } public String getHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { throw new AssertionError(); } } public Proxy toProxyAddress() { return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(getHostName(), getPort())); } /** * Returns a URL for connecting to this server. * * @param path the request path, such as "/". */ public URL getUrl(String path) throws MalformedURLException, UnknownHostException { return sslSocketFactory != null ? new URL("https://" + getHostName() + ":" + getPort() + path) : new URL("http://" + getHostName() + ":" + getPort() + path); } /** * Returns a cookie domain for this server. This returns the server's * non-loopback host name if it is known. Otherwise this returns ".local" * for this server's loopback name. */ public String getCookieDomain() { String hostName = getHostName(); return hostName.contains(".") ? hostName : ".local"; } /** * Sets the number of bytes of the POST body to keep in memory to the given * limit. */ public void setBodyLimit(int maxBodyLength) { this.bodyLimit = maxBodyLength; } /** * Serve requests with HTTPS rather than otherwise. * * @param tunnelProxy whether to expect the HTTP CONNECT method before * negotiating TLS. */ public void useHttps(SSLSocketFactory sslSocketFactory, boolean tunnelProxy) { this.sslSocketFactory = sslSocketFactory; this.tunnelProxy = tunnelProxy; } /** * Awaits the next HTTP request, removes it, and returns it. Callers should * use this to verify the request sent was as intended. */ public RecordedRequest takeRequest() throws InterruptedException { return requestQueue.take(); } /** * Returns the number of HTTP requests received thus far by this server. * This may exceed the number of HTTP connections when connection reuse is * in practice. */ public int getRequestCount() { return requestCount.get(); } public void enqueue(MockResponse response) { responseQueue.add(response.clone()); } /** * By default, this class processes requests coming in by adding them to a * queue and serves responses by removing them from another queue. This mode * is appropriate for correctness testing. * * <p>Serving a single response causes the server to be stateless: requests * are not enqueued, and responses are not dequeued. This mode is appropriate * for benchmarking. */ public void setSingleResponse(boolean singleResponse) { this.singleResponse = singleResponse; } /** * Equivalent to {@code play(0)}. */ public void play() throws IOException { play(0); } /** * Starts the server, serves all enqueued requests, and shuts the server * down. * * @param port the port to listen to, or 0 for any available port. * Automated tests should always use port 0 to avoid flakiness when a * specific port is unavailable. */ public void play(int port) throws IOException { executor = Executors.newCachedThreadPool(); serverSocket = new ServerSocket(port); serverSocket.setReuseAddress(true); this.port = serverSocket.getLocalPort(); executor.execute(namedRunnable("MockWebServer-accept-" + port, new Runnable() { public void run() { try { acceptConnections(); } catch (Throwable e) { logger.log(Level.WARNING, "MockWebServer connection failed", e); } /* * This gnarly block of code will release all sockets and * all thread, even if any close fails. */ try { serverSocket.close(); } catch (Throwable e) { logger.log(Level.WARNING, "MockWebServer server socket close failed", e); } for (Iterator<Socket> s = openClientSockets.iterator(); s.hasNext();) { try { s.next().close(); s.remove(); } catch (Throwable e) { logger.log(Level.WARNING, "MockWebServer socket close failed", e); } } try { executor.shutdown(); } catch (Throwable e) { logger.log(Level.WARNING, "MockWebServer executor shutdown failed", e); } } private void acceptConnections() throws Exception { while (true) { Socket socket; try { socket = serverSocket.accept(); } catch (SocketException e) { return; } MockResponse peek = responseQueue.peek(); if (peek != null && peek.getSocketPolicy() == DISCONNECT_AT_START) { responseQueue.take(); socket.close(); } else { openClientSockets.add(socket); serveConnection(socket); } } } })); } public void shutdown() throws IOException { if (serverSocket != null) { serverSocket.close(); // should cause acceptConnections() to break out } } private void serveConnection(final Socket raw) { String name = "MockWebServer-" + raw.getRemoteSocketAddress(); executor.execute(namedRunnable(name, new Runnable() { int sequenceNumber = 0; public void run() { try { processConnection(); } catch (Exception e) { logger.log(Level.WARNING, "MockWebServer connection failed", e); } } public void processConnection() throws Exception { Socket socket; if (sslSocketFactory != null) { if (tunnelProxy) { createTunnel(); } MockResponse response = responseQueue.peek(); if (response != null && response.getSocketPolicy() == FAIL_HANDSHAKE) { processHandshakeFailure(raw, sequenceNumber++); return; } socket = sslSocketFactory.createSocket( raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true); ((SSLSocket) socket).setUseClientMode(false); openClientSockets.add(socket); openClientSockets.remove(raw); } else { socket = raw; } InputStream in = new BufferedInputStream(socket.getInputStream()); OutputStream out = new BufferedOutputStream(socket.getOutputStream()); - while (processOneRequest(socket, in, out)) {} + while (processOneRequest(socket, in, out)) { + } if (sequenceNumber == 0) { logger.warning("MockWebServer connection didn't make a request"); } in.close(); out.close(); socket.close(); - if (responseQueue.isEmpty()) { - shutdown(); - } openClientSockets.remove(socket); } /** * Respond to CONNECT requests until a SWITCH_TO_SSL_AT_END response * is dispatched. */ private void createTunnel() throws IOException, InterruptedException { while (true) { MockResponse connect = responseQueue.peek(); if (!processOneRequest(raw, raw.getInputStream(), raw.getOutputStream())) { throw new IllegalStateException("Tunnel without any CONNECT!"); } if (connect.getSocketPolicy() == SocketPolicy.UPGRADE_TO_SSL_AT_END) { return; } } } /** * Reads a request and writes its response. Returns true if a request * was processed. */ private boolean processOneRequest(Socket socket, InputStream in, OutputStream out) throws IOException, InterruptedException { RecordedRequest request = readRequest(socket, in, sequenceNumber); if (request == null) { return false; } MockResponse response = dispatch(request); writeResponse(out, response); if (response.getSocketPolicy() == SocketPolicy.DISCONNECT_AT_END) { in.close(); out.close(); } else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_INPUT_AT_END) { socket.shutdownInput(); } else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_OUTPUT_AT_END) { socket.shutdownOutput(); } logger.info("Received request: " + request + " and responded: " + response); sequenceNumber++; return true; } })); } private void processHandshakeFailure(Socket raw, int sequenceNumber) throws Exception { responseQueue.take(); X509TrustManager untrusted = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { throw new CertificateException(); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { throw new AssertionError(); } @Override public X509Certificate[] getAcceptedIssuers() { throw new AssertionError(); } }; SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { untrusted }, new java.security.SecureRandom()); SSLSocketFactory sslSocketFactory = context.getSocketFactory(); SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket( raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true); try { socket.startHandshake(); // we're testing a handshake failure throw new AssertionError(); } catch (IOException expected) { } socket.close(); requestCount.incrementAndGet(); requestQueue.add(new RecordedRequest(null, null, null, -1, null, sequenceNumber, socket)); } /** * @param sequenceNumber the index of this request on this connection. */ private RecordedRequest readRequest(Socket socket, InputStream in, int sequenceNumber) throws IOException { String request; try { request = readAsciiUntilCrlf(in); } catch (IOException streamIsClosed) { return null; // no request because we closed the stream } if (request.isEmpty()) { return null; // no request because the stream is exhausted } List<String> headers = new ArrayList<String>(); int contentLength = -1; boolean chunked = false; String header; while (!(header = readAsciiUntilCrlf(in)).isEmpty()) { headers.add(header); String lowercaseHeader = header.toLowerCase(); if (contentLength == -1 && lowercaseHeader.startsWith("content-length:")) { contentLength = Integer.parseInt(header.substring(15).trim()); } if (lowercaseHeader.startsWith("transfer-encoding:") && lowercaseHeader.substring(18).trim().equals("chunked")) { chunked = true; } } boolean hasBody = false; TruncatingOutputStream requestBody = new TruncatingOutputStream(); List<Integer> chunkSizes = new ArrayList<Integer>(); if (contentLength != -1) { hasBody = true; transfer(contentLength, in, requestBody); } else if (chunked) { hasBody = true; while (true) { int chunkSize = Integer.parseInt(readAsciiUntilCrlf(in).trim(), 16); if (chunkSize == 0) { readEmptyLine(in); break; } chunkSizes.add(chunkSize); transfer(chunkSize, in, requestBody); readEmptyLine(in); } } if (request.startsWith("OPTIONS ") || request.startsWith("GET ") || request.startsWith("HEAD ") || request.startsWith("DELETE ") || request .startsWith("TRACE ") || request.startsWith("CONNECT ")) { if (hasBody) { throw new IllegalArgumentException("Request must not have a body: " + request); } } else if (request.startsWith("POST ") || request.startsWith("PUT ")) { if (!hasBody) { throw new IllegalArgumentException("Request must have a body: " + request); } } else { throw new UnsupportedOperationException("Unexpected method: " + request); } return new RecordedRequest(request, headers, chunkSizes, requestBody.numBytesReceived, requestBody.toByteArray(), sequenceNumber, socket); } /** * Returns a response to satisfy {@code request}. */ private MockResponse dispatch(RecordedRequest request) throws InterruptedException { // to permit interactive/browser testing, ignore requests for favicons if (request.getRequestLine().equals("GET /favicon.ico HTTP/1.1")) { System.out.println("served " + request.getRequestLine()); return new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NOT_FOUND); } if (singleResponse) { return responseQueue.peek(); } else { requestCount.incrementAndGet(); requestQueue.add(request); return responseQueue.take(); } } private void writeResponse(OutputStream out, MockResponse response) throws IOException { out.write((response.getStatus() + "\r\n").getBytes(ASCII)); for (String header : response.getHeaders()) { out.write((header + "\r\n").getBytes(ASCII)); } out.write(("\r\n").getBytes(ASCII)); out.flush(); byte[] body = response.getBody(); int bytesPerSecond = response.getBytesPerSecond(); for (int offset = 0; offset < body.length; offset += bytesPerSecond) { int count = Math.min(body.length - offset, bytesPerSecond); out.write(body, offset, count); out.flush(); if (offset + count < body.length) { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new AssertionError(); } } } } /** * Transfer bytes from {@code in} to {@code out} until either {@code length} * bytes have been transferred or {@code in} is exhausted. */ private void transfer(int length, InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; while (length > 0) { int count = in.read(buffer, 0, Math.min(buffer.length, length)); if (count == -1) { return; } out.write(buffer, 0, count); length -= count; } } /** * Returns the text from {@code in} until the next "\r\n", or null if * {@code in} is exhausted. */ private String readAsciiUntilCrlf(InputStream in) throws IOException { StringBuilder builder = new StringBuilder(); while (true) { int c = in.read(); if (c == '\n' && builder.length() > 0 && builder.charAt(builder.length() - 1) == '\r') { builder.deleteCharAt(builder.length() - 1); return builder.toString(); } else if (c == -1) { return builder.toString(); } else { builder.append((char) c); } } } private void readEmptyLine(InputStream in) throws IOException { String line = readAsciiUntilCrlf(in); if (!line.isEmpty()) { throw new IllegalStateException("Expected empty but was: " + line); } } /** * An output stream that drops data after bodyLimit bytes. */ private class TruncatingOutputStream extends ByteArrayOutputStream { private int numBytesReceived = 0; @Override public void write(byte[] buffer, int offset, int len) { numBytesReceived += len; super.write(buffer, offset, Math.min(len, bodyLimit - count)); } @Override public void write(int oneByte) { numBytesReceived++; if (count < bodyLimit) { super.write(oneByte); } } } private static Runnable namedRunnable(final String name, final Runnable runnable) { return new Runnable() { public void run() { String originalName = Thread.currentThread().getName(); Thread.currentThread().setName(name); try { runnable.run(); } finally { Thread.currentThread().setName(originalName); } } }; } }
false
true
private void serveConnection(final Socket raw) { String name = "MockWebServer-" + raw.getRemoteSocketAddress(); executor.execute(namedRunnable(name, new Runnable() { int sequenceNumber = 0; public void run() { try { processConnection(); } catch (Exception e) { logger.log(Level.WARNING, "MockWebServer connection failed", e); } } public void processConnection() throws Exception { Socket socket; if (sslSocketFactory != null) { if (tunnelProxy) { createTunnel(); } MockResponse response = responseQueue.peek(); if (response != null && response.getSocketPolicy() == FAIL_HANDSHAKE) { processHandshakeFailure(raw, sequenceNumber++); return; } socket = sslSocketFactory.createSocket( raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true); ((SSLSocket) socket).setUseClientMode(false); openClientSockets.add(socket); openClientSockets.remove(raw); } else { socket = raw; } InputStream in = new BufferedInputStream(socket.getInputStream()); OutputStream out = new BufferedOutputStream(socket.getOutputStream()); while (processOneRequest(socket, in, out)) {} if (sequenceNumber == 0) { logger.warning("MockWebServer connection didn't make a request"); } in.close(); out.close(); socket.close(); if (responseQueue.isEmpty()) { shutdown(); } openClientSockets.remove(socket); } /** * Respond to CONNECT requests until a SWITCH_TO_SSL_AT_END response * is dispatched. */ private void createTunnel() throws IOException, InterruptedException { while (true) { MockResponse connect = responseQueue.peek(); if (!processOneRequest(raw, raw.getInputStream(), raw.getOutputStream())) { throw new IllegalStateException("Tunnel without any CONNECT!"); } if (connect.getSocketPolicy() == SocketPolicy.UPGRADE_TO_SSL_AT_END) { return; } } } /** * Reads a request and writes its response. Returns true if a request * was processed. */ private boolean processOneRequest(Socket socket, InputStream in, OutputStream out) throws IOException, InterruptedException { RecordedRequest request = readRequest(socket, in, sequenceNumber); if (request == null) { return false; } MockResponse response = dispatch(request); writeResponse(out, response); if (response.getSocketPolicy() == SocketPolicy.DISCONNECT_AT_END) { in.close(); out.close(); } else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_INPUT_AT_END) { socket.shutdownInput(); } else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_OUTPUT_AT_END) { socket.shutdownOutput(); } logger.info("Received request: " + request + " and responded: " + response); sequenceNumber++; return true; } })); }
private void serveConnection(final Socket raw) { String name = "MockWebServer-" + raw.getRemoteSocketAddress(); executor.execute(namedRunnable(name, new Runnable() { int sequenceNumber = 0; public void run() { try { processConnection(); } catch (Exception e) { logger.log(Level.WARNING, "MockWebServer connection failed", e); } } public void processConnection() throws Exception { Socket socket; if (sslSocketFactory != null) { if (tunnelProxy) { createTunnel(); } MockResponse response = responseQueue.peek(); if (response != null && response.getSocketPolicy() == FAIL_HANDSHAKE) { processHandshakeFailure(raw, sequenceNumber++); return; } socket = sslSocketFactory.createSocket( raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true); ((SSLSocket) socket).setUseClientMode(false); openClientSockets.add(socket); openClientSockets.remove(raw); } else { socket = raw; } InputStream in = new BufferedInputStream(socket.getInputStream()); OutputStream out = new BufferedOutputStream(socket.getOutputStream()); while (processOneRequest(socket, in, out)) { } if (sequenceNumber == 0) { logger.warning("MockWebServer connection didn't make a request"); } in.close(); out.close(); socket.close(); openClientSockets.remove(socket); } /** * Respond to CONNECT requests until a SWITCH_TO_SSL_AT_END response * is dispatched. */ private void createTunnel() throws IOException, InterruptedException { while (true) { MockResponse connect = responseQueue.peek(); if (!processOneRequest(raw, raw.getInputStream(), raw.getOutputStream())) { throw new IllegalStateException("Tunnel without any CONNECT!"); } if (connect.getSocketPolicy() == SocketPolicy.UPGRADE_TO_SSL_AT_END) { return; } } } /** * Reads a request and writes its response. Returns true if a request * was processed. */ private boolean processOneRequest(Socket socket, InputStream in, OutputStream out) throws IOException, InterruptedException { RecordedRequest request = readRequest(socket, in, sequenceNumber); if (request == null) { return false; } MockResponse response = dispatch(request); writeResponse(out, response); if (response.getSocketPolicy() == SocketPolicy.DISCONNECT_AT_END) { in.close(); out.close(); } else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_INPUT_AT_END) { socket.shutdownInput(); } else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_OUTPUT_AT_END) { socket.shutdownOutput(); } logger.info("Received request: " + request + " and responded: " + response); sequenceNumber++; return true; } })); }
diff --git a/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java b/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java index 389effc6..f3faa2de 100644 --- a/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java +++ b/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java @@ -1,519 +1,520 @@ package com.earth2me.essentials.signs; import static com.earth2me.essentials.I18n._; import com.earth2me.essentials.*; import java.util.HashSet; import java.util.Locale; import java.util.Set; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.inventory.ItemStack; public class EssentialsSign { private static final Set<Material> EMPTY_SET = new HashSet<Material>(); protected transient final String signName; public EssentialsSign(final String signName) { this.signName = signName; } public final boolean onSignCreate(final SignChangeEvent event, final IEssentials ess) { final ISign sign = new EventSign(event); final User user = ess.getUser(event.getPlayer()); if (!(user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".create") || user.isAuthorized("essentials.signs.create." + signName.toLowerCase(Locale.ENGLISH)))) { // Return true, so other plugins can use the same sign title, just hope // they won't change it to §1[Signname] return true; } sign.setLine(0, _("signFormatFail", this.signName)); try { final boolean ret = onSignCreate(sign, user, getUsername(user), ess); if (ret) { sign.setLine(0, getSuccessName()); } return ret; } catch (ChargeException ex) { ess.showError(user, ex, signName); } catch (SignException ex) { ess.showError(user, ex, signName); } // Return true, so the player sees the wrong sign. return true; } public String getSuccessName() { return _("signFormatSuccess", this.signName); } public String getTemplateName() { return _("signFormatTemplate", this.signName); } private String getUsername(final User user) { return user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length()); } public final boolean onSignInteract(final Block block, final Player player, final IEssentials ess) { final ISign sign = new BlockSign(block); final User user = ess.getUser(player); if (user.checkSignThrottle()) { return false; } try { return (user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".use") || user.isAuthorized("essentials.signs.use." + signName.toLowerCase(Locale.ENGLISH))) && onSignInteract(sign, user, getUsername(user), ess); } catch (ChargeException ex) { ess.showError(user, ex, signName); return false; } catch (SignException ex) { ess.showError(user, ex, signName); return false; } } public final boolean onSignBreak(final Block block, final Player player, final IEssentials ess) { final ISign sign = new BlockSign(block); final User user = ess.getUser(player); try { return (user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".break") || user.isAuthorized("essentials.signs.break." + signName.toLowerCase(Locale.ENGLISH))) && onSignBreak(sign, user, getUsername(user), ess); } catch (SignException ex) { ess.showError(user, ex, signName); return false; } } protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException { return true; } protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException { return true; } protected boolean onSignBreak(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException { return true; } public final boolean onBlockPlace(final Block block, final Player player, final IEssentials ess) { User user = ess.getUser(player); try { return onBlockPlace(block, user, getUsername(user), ess); } catch (ChargeException ex) { ess.showError(user, ex, signName); } catch (SignException ex) { ess.showError(user, ex, signName); } return false; } public final boolean onBlockInteract(final Block block, final Player player, final IEssentials ess) { User user = ess.getUser(player); try { return onBlockInteract(block, user, getUsername(user), ess); } catch (ChargeException ex) { ess.showError(user, ex, signName); } catch (SignException ex) { ess.showError(user, ex, signName); } return false; } public final boolean onBlockBreak(final Block block, final Player player, final IEssentials ess) { User user = ess.getUser(player); try { return onBlockBreak(block, user, getUsername(user), ess); } catch (SignException ex) { ess.showError(user, ex, signName); } return false; } public boolean onBlockBreak(final Block block, final IEssentials ess) { return true; } public boolean onBlockExplode(final Block block, final IEssentials ess) { return true; } public boolean onBlockBurn(final Block block, final IEssentials ess) { return true; } public boolean onBlockIgnite(final Block block, final IEssentials ess) { return true; } public boolean onBlockPush(final Block block, final IEssentials ess) { return true; } public static boolean checkIfBlockBreaksSigns(final Block block) { final Block sign = block.getRelative(BlockFace.UP); if (sign.getType() == Material.SIGN_POST && isValidSign(new BlockSign(sign))) { return true; } final BlockFace[] directions = new BlockFace[] { BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST }; for (BlockFace blockFace : directions) { final Block signblock = block.getRelative(blockFace); if (signblock.getType() == Material.WALL_SIGN) { final org.bukkit.material.Sign signMat = (org.bukkit.material.Sign)signblock.getState().getData(); if (signMat != null && signMat.getFacing() == blockFace && isValidSign(new BlockSign(signblock))) { return true; } } } return false; } public static boolean isValidSign(final ISign sign) { return sign.getLine(0).matches("§1\\[.*\\]"); } protected boolean onBlockPlace(final Block block, final User player, final String username, final IEssentials ess) throws SignException, ChargeException { return true; } protected boolean onBlockInteract(final Block block, final User player, final String username, final IEssentials ess) throws SignException, ChargeException { return true; } protected boolean onBlockBreak(final Block block, final User player, final String username, final IEssentials ess) throws SignException { return true; } public Set<Material> getBlocks() { return EMPTY_SET; } protected final void validateTrade(final ISign sign, final int index, final IEssentials ess) throws SignException { final String line = sign.getLine(index).trim(); if (line.isEmpty()) { return; } final Trade trade = getTrade(sign, index, 0, ess); final Double money = trade.getMoney(); if (money != null) { sign.setLine(index, Util.shortCurrency(money, ess)); } } protected final void validateTrade(final ISign sign, final int amountIndex, final int itemIndex, final User player, final IEssentials ess) throws SignException { if (sign.getLine(itemIndex).equalsIgnoreCase("exp") || sign.getLine(itemIndex).equalsIgnoreCase("xp")) { int amount = getIntegerPositive(sign.getLine(amountIndex)); sign.setLine(amountIndex, Integer.toString(amount)); sign.setLine(itemIndex, "exp"); return; } final Trade trade = getTrade(sign, amountIndex, itemIndex, player, ess); final ItemStack item = trade.getItemStack(); sign.setLine(amountIndex, Integer.toString(item.getAmount())); sign.setLine(itemIndex, sign.getLine(itemIndex).trim()); } protected final Trade getTrade(final ISign sign, final int amountIndex, final int itemIndex, final User player, final IEssentials ess) throws SignException { if (sign.getLine(itemIndex).equalsIgnoreCase("exp") || sign.getLine(itemIndex).equalsIgnoreCase("xp")) { final int amount = getIntegerPositive(sign.getLine(amountIndex)); return new Trade(amount, ess); } final ItemStack item = getItemStack(sign.getLine(itemIndex), 1, ess); final int amount = Math.min(getIntegerPositive(sign.getLine(amountIndex)), item.getType().getMaxStackSize() * player.getInventory().getSize()); if (item.getTypeId() == 0 || amount < 1) { throw new SignException(_("moreThanZero")); } item.setAmount(amount); return new Trade(item, ess); } protected final void validateInteger(final ISign sign, final int index) throws SignException { final String line = sign.getLine(index).trim(); if (line.isEmpty()) { throw new SignException("Empty line " + index); } final int quantity = getIntegerPositive(line); sign.setLine(index, Integer.toString(quantity)); } protected final int getIntegerPositive(final String line) throws SignException { final int quantity = getInteger(line); if (quantity < 1) { throw new SignException(_("moreThanZero")); } return quantity; } protected final int getInteger(final String line) throws SignException { try { final int quantity = Integer.parseInt(line); return quantity; } catch (NumberFormatException ex) { throw new SignException("Invalid sign", ex); } } protected final ItemStack getItemStack(final String itemName, final int quantity, final IEssentials ess) throws SignException { try { final ItemStack item = ess.getItemDb().get(itemName); item.setAmount(quantity); return item; } catch (Exception ex) { throw new SignException(ex.getMessage(), ex); } } protected final Double getMoney(final String line) throws SignException { final boolean isMoney = line.matches("^[^0-9-\\.][\\.0-9]+$"); return isMoney ? getDoublePositive(line.substring(1)) : null; } protected final Double getDoublePositive(final String line) throws SignException { final double quantity = getDouble(line); if (Math.round(quantity * 100.0) < 1.0) { throw new SignException(_("moreThanZero")); } return quantity; } protected final Double getDouble(final String line) throws SignException { try { return Double.parseDouble(line); } catch (NumberFormatException ex) { throw new SignException(ex.getMessage(), ex); } } protected final Trade getTrade(final ISign sign, final int index, final IEssentials ess) throws SignException { return getTrade(sign, index, 1, ess); } protected final Trade getTrade(final ISign sign, final int index, final int decrement, final IEssentials ess) throws SignException { final String line = sign.getLine(index).trim(); if (line.isEmpty()) { return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess); } final Double money = getMoney(line); if (money == null) { final String[] split = line.split("[ :]+", 2); if (split.length != 2) { throw new SignException(_("invalidCharge")); } final int quantity = getIntegerPositive(split[0]); final String item = split[1].toLowerCase(Locale.ENGLISH); if (item.equalsIgnoreCase("times")) { sign.setLine(index, (quantity - decrement) + " times"); + sign.updateSign(); return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess); } else if (item.equalsIgnoreCase("exp") || item.equalsIgnoreCase("xp")) { sign.setLine(index, quantity + " exp"); return new Trade(quantity, ess); } else { final ItemStack stack = getItemStack(item, quantity, ess); sign.setLine(index, quantity + " " + item); return new Trade(stack, ess); } } else { return new Trade(money, ess); } } static class EventSign implements ISign { private final transient SignChangeEvent event; private final transient Block block; public EventSign(final SignChangeEvent event) { this.event = event; this.block = event.getBlock(); } @Override public final String getLine(final int index) { return event.getLine(index); } @Override public final void setLine(final int index, final String text) { event.setLine(index, text); } @Override public Block getBlock() { return block; } @Override public void updateSign() { } } static class BlockSign implements ISign { private final transient Sign sign; private final transient Block block; public BlockSign(final Block block) { this.block = block; this.sign = (Sign)block.getState(); } @Override public final String getLine(final int index) { return sign.getLine(index); } @Override public final void setLine(final int index, final String text) { sign.setLine(index, text); } @Override public final Block getBlock() { return block; } @Override public final void updateSign() { sign.update(); } } public interface ISign { String getLine(final int index); void setLine(final int index, final String text); public Block getBlock(); void updateSign(); } }
true
true
protected final Trade getTrade(final ISign sign, final int index, final int decrement, final IEssentials ess) throws SignException { final String line = sign.getLine(index).trim(); if (line.isEmpty()) { return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess); } final Double money = getMoney(line); if (money == null) { final String[] split = line.split("[ :]+", 2); if (split.length != 2) { throw new SignException(_("invalidCharge")); } final int quantity = getIntegerPositive(split[0]); final String item = split[1].toLowerCase(Locale.ENGLISH); if (item.equalsIgnoreCase("times")) { sign.setLine(index, (quantity - decrement) + " times"); return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess); } else if (item.equalsIgnoreCase("exp") || item.equalsIgnoreCase("xp")) { sign.setLine(index, quantity + " exp"); return new Trade(quantity, ess); } else { final ItemStack stack = getItemStack(item, quantity, ess); sign.setLine(index, quantity + " " + item); return new Trade(stack, ess); } } else { return new Trade(money, ess); } }
protected final Trade getTrade(final ISign sign, final int index, final int decrement, final IEssentials ess) throws SignException { final String line = sign.getLine(index).trim(); if (line.isEmpty()) { return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess); } final Double money = getMoney(line); if (money == null) { final String[] split = line.split("[ :]+", 2); if (split.length != 2) { throw new SignException(_("invalidCharge")); } final int quantity = getIntegerPositive(split[0]); final String item = split[1].toLowerCase(Locale.ENGLISH); if (item.equalsIgnoreCase("times")) { sign.setLine(index, (quantity - decrement) + " times"); sign.updateSign(); return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess); } else if (item.equalsIgnoreCase("exp") || item.equalsIgnoreCase("xp")) { sign.setLine(index, quantity + " exp"); return new Trade(quantity, ess); } else { final ItemStack stack = getItemStack(item, quantity, ess); sign.setLine(index, quantity + " " + item); return new Trade(stack, ess); } } else { return new Trade(money, ess); } }
diff --git a/src/net/java/sip/communicator/plugin/branding/AboutWindow.java b/src/net/java/sip/communicator/plugin/branding/AboutWindow.java index 669d924bf..281c4da56 100644 --- a/src/net/java/sip/communicator/plugin/branding/AboutWindow.java +++ b/src/net/java/sip/communicator/plugin/branding/AboutWindow.java @@ -1,265 +1,266 @@ /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.plugin.branding; import java.awt.*; import java.awt.event.*; import java.io.*; import javax.imageio.*; import javax.swing.*; import javax.swing.event.*; import net.java.sip.communicator.service.browserlauncher.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.resources.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.util.swing.*; import org.osgi.framework.*; public class AboutWindow extends JDialog implements HyperlinkListener, ActionListener, ExportedWindow { private static final int DEFAULT_TEXT_INDENT = BrandingActivator.getResources() .getSettingsInt("plugin.branding.ABOUT_TEXT_INDENT"); public AboutWindow(Frame owner) { super(owner); ResourceManagementService resources = BrandingActivator.getResources(); String applicationName = resources.getSettingsString("service.gui.APPLICATION_NAME"); this.setTitle( resources.getI18NString("plugin.branding.ABOUT_WINDOW_TITLE", new String[]{applicationName})); setModal(false); setDefaultCloseOperation(DISPOSE_ON_CLOSE); JPanel mainPanel = new WindowBackground(); mainPanel.setLayout(new BorderLayout()); JPanel textPanel = new JPanel(); textPanel.setPreferredSize(new Dimension(470, 280)); textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.Y_AXIS)); textPanel.setBorder(BorderFactory .createEmptyBorder(15, 15, 15, 15)); textPanel.setOpaque(false); JLabel titleLabel = new JLabel(applicationName); titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 28)); titleLabel.setForeground(Constants.TITLE_COLOR); titleLabel.setAlignmentX(Component.RIGHT_ALIGNMENT); JLabel versionLabel = new JLabel(" " + System.getProperty("sip-communicator.version")); versionLabel.setFont(versionLabel.getFont().deriveFont(Font.BOLD, 18)); versionLabel.setForeground(Constants.TITLE_COLOR); versionLabel.setAlignmentX(Component.RIGHT_ALIGNMENT); int logoAreaFontSize = resources.getSettingsInt("plugin.branding.ABOUT_LOGO_FONT_SIZE"); + // FIXME: the message exceeds the window length JTextArea logoArea = new JTextArea(resources.getI18NString("plugin.branding.LOGO_MESSAGE")); logoArea.setFont( logoArea.getFont().deriveFont(Font.BOLD, logoAreaFontSize)); logoArea.setForeground(Constants.TITLE_COLOR); logoArea.setOpaque(false); - logoArea.setLineWrap(true); + logoArea.setLineWrap(false); logoArea.setWrapStyleWord(true); logoArea.setEditable(false); logoArea.setPreferredSize(new Dimension(100, 20)); logoArea.setAlignmentX(Component.RIGHT_ALIGNMENT); logoArea.setBorder(BorderFactory .createEmptyBorder(30, DEFAULT_TEXT_INDENT, 0, 0)); StyledHTMLEditorPane rightsArea = new StyledHTMLEditorPane(); rightsArea.setContentType("text/html"); rightsArea.appendToEnd(resources.getI18NString("plugin.branding.COPYRIGHT", new String[] { Constants.TEXT_COLOR })); rightsArea.setPreferredSize(new Dimension(50, 20)); rightsArea .setBorder(BorderFactory .createEmptyBorder(0, DEFAULT_TEXT_INDENT, 0, 0)); rightsArea.setOpaque(false); rightsArea.setEditable(false); rightsArea.setAlignmentX(Component.RIGHT_ALIGNMENT); rightsArea.addHyperlinkListener(this); StyledHTMLEditorPane licenseArea = new StyledHTMLEditorPane(); licenseArea.setContentType("text/html"); licenseArea.appendToEnd(resources. getI18NString("plugin.branding.LICENSE", new String[]{Constants.TEXT_COLOR})); licenseArea.setPreferredSize(new Dimension(50, 20)); licenseArea.setBorder( BorderFactory.createEmptyBorder( resources.getSettingsInt("plugin.branding.ABOUT_PARAGRAPH_GAP"), DEFAULT_TEXT_INDENT, 0, 0)); licenseArea.setOpaque(false); licenseArea.setEditable(false); licenseArea.setAlignmentX(Component.RIGHT_ALIGNMENT); licenseArea.addHyperlinkListener(this); textPanel.add(titleLabel); textPanel.add(versionLabel); textPanel.add(logoArea); textPanel.add(rightsArea); textPanel.add(licenseArea); JButton okButton = new JButton(resources.getI18NString("service.gui.OK")); this.getRootPane().setDefaultButton(okButton); okButton.setMnemonic(resources.getI18nMnemonic("service.gui.OK")); okButton.addActionListener(this); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(okButton); buttonPanel.setOpaque(false); mainPanel.add(textPanel, BorderLayout.CENTER); mainPanel.add(buttonPanel, BorderLayout.SOUTH); this.getContentPane().add(mainPanel); this.setSize(mainPanel.getPreferredSize()); this.setResizable(false); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(screenSize.width / 2 - getWidth() / 2, screenSize.height / 2 - getHeight() / 2); } /** * Constructs the window background in order to have a background image. */ private static class WindowBackground extends JPanel { private final Logger logger = Logger.getLogger(WindowBackground.class.getName()); private Image bgImage = null; public WindowBackground() { try { bgImage = ImageIO.read(BrandingActivator.getResources(). getImageURL("plugin.branding.ABOUT_WINDOW_BACKGROUND")); } catch (IOException e) { logger.error("Error cannot obtain background image", e); bgImage = null; } this.setPreferredSize(new Dimension(bgImage.getWidth(this), bgImage.getHeight(this))); } protected void paintComponent(Graphics g) { super.paintComponent(g); g = g.create(); try { AntialiasingManager.activateAntialiasing(g); g.drawImage(bgImage, 0, 0, null); } finally { g.dispose(); } } } public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { String href = e.getDescription(); ServiceReference serviceReference = BrandingActivator .getBundleContext().getServiceReference( BrowserLauncherService.class.getName()); if (serviceReference != null) { BrowserLauncherService browserLauncherService = (BrowserLauncherService) BrandingActivator .getBundleContext().getService(serviceReference); browserLauncherService.openURL(href); } } } public void actionPerformed(ActionEvent e) { setVisible(false); dispose(); } /** * Implements the <tt>ExportedWindow.getIdentifier()</tt> method. */ public WindowID getIdentifier() { return ExportedWindow.ABOUT_WINDOW; } /** * This dialog could not be minimized. */ public void minimize() { } /** * This dialog could not be maximized. */ public void maximize() { } /** * Implements the <tt>ExportedWindow.bringToFront()</tt> method. Brings * this window to front. */ public void bringToFront() { this.toFront(); } /** * The source of the window * @return the source of the window */ public Object getSource() { return this; } /** * Implementation of {@link ExportedWindow#setParams(Object[])}. */ public void setParams(Object[] windowParams) {} }
false
true
public AboutWindow(Frame owner) { super(owner); ResourceManagementService resources = BrandingActivator.getResources(); String applicationName = resources.getSettingsString("service.gui.APPLICATION_NAME"); this.setTitle( resources.getI18NString("plugin.branding.ABOUT_WINDOW_TITLE", new String[]{applicationName})); setModal(false); setDefaultCloseOperation(DISPOSE_ON_CLOSE); JPanel mainPanel = new WindowBackground(); mainPanel.setLayout(new BorderLayout()); JPanel textPanel = new JPanel(); textPanel.setPreferredSize(new Dimension(470, 280)); textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.Y_AXIS)); textPanel.setBorder(BorderFactory .createEmptyBorder(15, 15, 15, 15)); textPanel.setOpaque(false); JLabel titleLabel = new JLabel(applicationName); titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 28)); titleLabel.setForeground(Constants.TITLE_COLOR); titleLabel.setAlignmentX(Component.RIGHT_ALIGNMENT); JLabel versionLabel = new JLabel(" " + System.getProperty("sip-communicator.version")); versionLabel.setFont(versionLabel.getFont().deriveFont(Font.BOLD, 18)); versionLabel.setForeground(Constants.TITLE_COLOR); versionLabel.setAlignmentX(Component.RIGHT_ALIGNMENT); int logoAreaFontSize = resources.getSettingsInt("plugin.branding.ABOUT_LOGO_FONT_SIZE"); JTextArea logoArea = new JTextArea(resources.getI18NString("plugin.branding.LOGO_MESSAGE")); logoArea.setFont( logoArea.getFont().deriveFont(Font.BOLD, logoAreaFontSize)); logoArea.setForeground(Constants.TITLE_COLOR); logoArea.setOpaque(false); logoArea.setLineWrap(true); logoArea.setWrapStyleWord(true); logoArea.setEditable(false); logoArea.setPreferredSize(new Dimension(100, 20)); logoArea.setAlignmentX(Component.RIGHT_ALIGNMENT); logoArea.setBorder(BorderFactory .createEmptyBorder(30, DEFAULT_TEXT_INDENT, 0, 0)); StyledHTMLEditorPane rightsArea = new StyledHTMLEditorPane(); rightsArea.setContentType("text/html"); rightsArea.appendToEnd(resources.getI18NString("plugin.branding.COPYRIGHT", new String[] { Constants.TEXT_COLOR })); rightsArea.setPreferredSize(new Dimension(50, 20)); rightsArea .setBorder(BorderFactory .createEmptyBorder(0, DEFAULT_TEXT_INDENT, 0, 0)); rightsArea.setOpaque(false); rightsArea.setEditable(false); rightsArea.setAlignmentX(Component.RIGHT_ALIGNMENT); rightsArea.addHyperlinkListener(this); StyledHTMLEditorPane licenseArea = new StyledHTMLEditorPane(); licenseArea.setContentType("text/html"); licenseArea.appendToEnd(resources. getI18NString("plugin.branding.LICENSE", new String[]{Constants.TEXT_COLOR})); licenseArea.setPreferredSize(new Dimension(50, 20)); licenseArea.setBorder( BorderFactory.createEmptyBorder( resources.getSettingsInt("plugin.branding.ABOUT_PARAGRAPH_GAP"), DEFAULT_TEXT_INDENT, 0, 0)); licenseArea.setOpaque(false); licenseArea.setEditable(false); licenseArea.setAlignmentX(Component.RIGHT_ALIGNMENT); licenseArea.addHyperlinkListener(this); textPanel.add(titleLabel); textPanel.add(versionLabel); textPanel.add(logoArea); textPanel.add(rightsArea); textPanel.add(licenseArea); JButton okButton = new JButton(resources.getI18NString("service.gui.OK")); this.getRootPane().setDefaultButton(okButton); okButton.setMnemonic(resources.getI18nMnemonic("service.gui.OK")); okButton.addActionListener(this); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(okButton); buttonPanel.setOpaque(false); mainPanel.add(textPanel, BorderLayout.CENTER); mainPanel.add(buttonPanel, BorderLayout.SOUTH); this.getContentPane().add(mainPanel); this.setSize(mainPanel.getPreferredSize()); this.setResizable(false); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(screenSize.width / 2 - getWidth() / 2, screenSize.height / 2 - getHeight() / 2); }
public AboutWindow(Frame owner) { super(owner); ResourceManagementService resources = BrandingActivator.getResources(); String applicationName = resources.getSettingsString("service.gui.APPLICATION_NAME"); this.setTitle( resources.getI18NString("plugin.branding.ABOUT_WINDOW_TITLE", new String[]{applicationName})); setModal(false); setDefaultCloseOperation(DISPOSE_ON_CLOSE); JPanel mainPanel = new WindowBackground(); mainPanel.setLayout(new BorderLayout()); JPanel textPanel = new JPanel(); textPanel.setPreferredSize(new Dimension(470, 280)); textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.Y_AXIS)); textPanel.setBorder(BorderFactory .createEmptyBorder(15, 15, 15, 15)); textPanel.setOpaque(false); JLabel titleLabel = new JLabel(applicationName); titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 28)); titleLabel.setForeground(Constants.TITLE_COLOR); titleLabel.setAlignmentX(Component.RIGHT_ALIGNMENT); JLabel versionLabel = new JLabel(" " + System.getProperty("sip-communicator.version")); versionLabel.setFont(versionLabel.getFont().deriveFont(Font.BOLD, 18)); versionLabel.setForeground(Constants.TITLE_COLOR); versionLabel.setAlignmentX(Component.RIGHT_ALIGNMENT); int logoAreaFontSize = resources.getSettingsInt("plugin.branding.ABOUT_LOGO_FONT_SIZE"); // FIXME: the message exceeds the window length JTextArea logoArea = new JTextArea(resources.getI18NString("plugin.branding.LOGO_MESSAGE")); logoArea.setFont( logoArea.getFont().deriveFont(Font.BOLD, logoAreaFontSize)); logoArea.setForeground(Constants.TITLE_COLOR); logoArea.setOpaque(false); logoArea.setLineWrap(false); logoArea.setWrapStyleWord(true); logoArea.setEditable(false); logoArea.setPreferredSize(new Dimension(100, 20)); logoArea.setAlignmentX(Component.RIGHT_ALIGNMENT); logoArea.setBorder(BorderFactory .createEmptyBorder(30, DEFAULT_TEXT_INDENT, 0, 0)); StyledHTMLEditorPane rightsArea = new StyledHTMLEditorPane(); rightsArea.setContentType("text/html"); rightsArea.appendToEnd(resources.getI18NString("plugin.branding.COPYRIGHT", new String[] { Constants.TEXT_COLOR })); rightsArea.setPreferredSize(new Dimension(50, 20)); rightsArea .setBorder(BorderFactory .createEmptyBorder(0, DEFAULT_TEXT_INDENT, 0, 0)); rightsArea.setOpaque(false); rightsArea.setEditable(false); rightsArea.setAlignmentX(Component.RIGHT_ALIGNMENT); rightsArea.addHyperlinkListener(this); StyledHTMLEditorPane licenseArea = new StyledHTMLEditorPane(); licenseArea.setContentType("text/html"); licenseArea.appendToEnd(resources. getI18NString("plugin.branding.LICENSE", new String[]{Constants.TEXT_COLOR})); licenseArea.setPreferredSize(new Dimension(50, 20)); licenseArea.setBorder( BorderFactory.createEmptyBorder( resources.getSettingsInt("plugin.branding.ABOUT_PARAGRAPH_GAP"), DEFAULT_TEXT_INDENT, 0, 0)); licenseArea.setOpaque(false); licenseArea.setEditable(false); licenseArea.setAlignmentX(Component.RIGHT_ALIGNMENT); licenseArea.addHyperlinkListener(this); textPanel.add(titleLabel); textPanel.add(versionLabel); textPanel.add(logoArea); textPanel.add(rightsArea); textPanel.add(licenseArea); JButton okButton = new JButton(resources.getI18NString("service.gui.OK")); this.getRootPane().setDefaultButton(okButton); okButton.setMnemonic(resources.getI18nMnemonic("service.gui.OK")); okButton.addActionListener(this); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonPanel.add(okButton); buttonPanel.setOpaque(false); mainPanel.add(textPanel, BorderLayout.CENTER); mainPanel.add(buttonPanel, BorderLayout.SOUTH); this.getContentPane().add(mainPanel); this.setSize(mainPanel.getPreferredSize()); this.setResizable(false); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(screenSize.width / 2 - getWidth() / 2, screenSize.height / 2 - getHeight() / 2); }
diff --git a/src/main/ed/db/ImportBinary.java b/src/main/ed/db/ImportBinary.java index 08df079a2..8989045a1 100644 --- a/src/main/ed/db/ImportBinary.java +++ b/src/main/ed/db/ImportBinary.java @@ -1,79 +1,80 @@ // ImportBinary.java package ed.db; import java.io.*; import java.nio.*; import java.nio.channels.*; import java.util.*; import ed.js.*; public class ImportBinary { static void load( File root ) throws IOException { for ( File f : root.listFiles() ){ if ( ! f.isDirectory() ) continue; loadNamespace( f ); } } static void loadNamespace( File dir ) throws IOException { for ( File f : dir.listFiles() ){ if ( f.isDirectory() ) continue; loadOne( f ); } } static void loadOne( File f ) throws IOException { final String ns = f.getName().replaceAll( "\\.bin$" , "" ); final String root = f.getParentFile().getName(); DBApiLayer db = DBProvider.get( root ); DBCollection coll = db.getCollection( ns ); System.out.println( "full ns : " + root + "." + ns ); FileInputStream fin = new FileInputStream( f ); ByteBuffer bb = ByteBuffer.allocateDirect( (int)(f.length()) ); bb.order( ByteOrder.LITTLE_ENDIAN ); FileChannel fc = fin.getChannel(); fc.read( bb ); bb.flip(); ByteDecoder decoder = new ByteDecoder( bb ); boolean hasAny = false; { - Iterator<JSObject> checkForAny = coll.find( new JSObjectBase() , new JSObjectBase() , 0 , 1 ); + Iterator<JSObject> checkForAny = coll.find( new JSObjectBase() , null , 0 , 2 ); if ( checkForAny != null && checkForAny.hasNext() ) hasAny = true; } + System.out.println( "\t hasAny : " + hasAny ); JSObject o; while ( ( o = decoder.readObject() ) != null ){ if ( hasAny ) coll.save( o ); else coll.doSave( o ); } coll.find( new JSObjectBase() , null , 0 , 1 ); } public static void main( String args[] ) throws Exception { load( new File( args[0] ) ); } }
false
true
static void loadOne( File f ) throws IOException { final String ns = f.getName().replaceAll( "\\.bin$" , "" ); final String root = f.getParentFile().getName(); DBApiLayer db = DBProvider.get( root ); DBCollection coll = db.getCollection( ns ); System.out.println( "full ns : " + root + "." + ns ); FileInputStream fin = new FileInputStream( f ); ByteBuffer bb = ByteBuffer.allocateDirect( (int)(f.length()) ); bb.order( ByteOrder.LITTLE_ENDIAN ); FileChannel fc = fin.getChannel(); fc.read( bb ); bb.flip(); ByteDecoder decoder = new ByteDecoder( bb ); boolean hasAny = false; { Iterator<JSObject> checkForAny = coll.find( new JSObjectBase() , new JSObjectBase() , 0 , 1 ); if ( checkForAny != null && checkForAny.hasNext() ) hasAny = true; } JSObject o; while ( ( o = decoder.readObject() ) != null ){ if ( hasAny ) coll.save( o ); else coll.doSave( o ); } coll.find( new JSObjectBase() , null , 0 , 1 ); }
static void loadOne( File f ) throws IOException { final String ns = f.getName().replaceAll( "\\.bin$" , "" ); final String root = f.getParentFile().getName(); DBApiLayer db = DBProvider.get( root ); DBCollection coll = db.getCollection( ns ); System.out.println( "full ns : " + root + "." + ns ); FileInputStream fin = new FileInputStream( f ); ByteBuffer bb = ByteBuffer.allocateDirect( (int)(f.length()) ); bb.order( ByteOrder.LITTLE_ENDIAN ); FileChannel fc = fin.getChannel(); fc.read( bb ); bb.flip(); ByteDecoder decoder = new ByteDecoder( bb ); boolean hasAny = false; { Iterator<JSObject> checkForAny = coll.find( new JSObjectBase() , null , 0 , 2 ); if ( checkForAny != null && checkForAny.hasNext() ) hasAny = true; } System.out.println( "\t hasAny : " + hasAny ); JSObject o; while ( ( o = decoder.readObject() ) != null ){ if ( hasAny ) coll.save( o ); else coll.doSave( o ); } coll.find( new JSObjectBase() , null , 0 , 1 ); }
diff --git a/src/org/apache/xpath/functions/FuncLocalPart.java b/src/org/apache/xpath/functions/FuncLocalPart.java index 0b1b6ef5..646c097f 100644 --- a/src/org/apache/xpath/functions/FuncLocalPart.java +++ b/src/org/apache/xpath/functions/FuncLocalPart.java @@ -1,99 +1,99 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xpath.functions; import org.apache.xpath.res.XPATHErrorResources; import org.w3c.dom.Node; import org.w3c.dom.traversal.NodeIterator; import java.util.Vector; import org.apache.xpath.XPathContext; import org.apache.xpath.XPath; import org.apache.xpath.objects.XObject; import org.apache.xpath.objects.XString; /** * Execute the LocalPart() function. * <meta name="usage" content="advanced"/> */ public class FuncLocalPart extends FunctionDef1Arg { /** * Execute the function. The function must return * a valid object. * @param xctxt The current execution context. * @return A valid XObject. * * @throws javax.xml.transform.TransformerException */ public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException { Node context = getArg0AsNode(xctxt); String s = (context != null) ? xctxt.getDOMHelper().getLocalNameOfNode(context) : ""; - if(s.startsWith("#")) + if(s.startsWith("#") || s.equals("xmlns")) s = ""; return new XString(s); } }
true
true
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException { Node context = getArg0AsNode(xctxt); String s = (context != null) ? xctxt.getDOMHelper().getLocalNameOfNode(context) : ""; if(s.startsWith("#")) s = ""; return new XString(s); }
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException { Node context = getArg0AsNode(xctxt); String s = (context != null) ? xctxt.getDOMHelper().getLocalNameOfNode(context) : ""; if(s.startsWith("#") || s.equals("xmlns")) s = ""; return new XString(s); }
diff --git a/modules/cpr/src/main/java/org/atmosphere/cpr/MeteorServlet.java b/modules/cpr/src/main/java/org/atmosphere/cpr/MeteorServlet.java index 196c32d31..59f6e7298 100755 --- a/modules/cpr/src/main/java/org/atmosphere/cpr/MeteorServlet.java +++ b/modules/cpr/src/main/java/org/atmosphere/cpr/MeteorServlet.java @@ -1,110 +1,111 @@ /* * Copyright 2012 Jeanfrancois Arcand * * 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. */ /* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. * */ package org.atmosphere.cpr; import org.atmosphere.handler.ReflectorServletProcessor; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import static org.atmosphere.cpr.ApplicationConfig.FILTER_CLASS; import static org.atmosphere.cpr.ApplicationConfig.FILTER_NAME; import static org.atmosphere.cpr.ApplicationConfig.MAPPING; import static org.atmosphere.cpr.ApplicationConfig.SERVLET_CLASS; /** * Simple Servlet to use when Atmosphere {@link Meteor} are used. This Servlet will look * for a Servlet init-param named org.atmosphere.servlet or org.atmosphere.filter and will * delegate request processing to them. When used, this Servlet will ignore any * value defined in META-INF/atmosphere.xml as internally it will create a * {@link ReflectorServletProcessor} * * @author Jean-Francois Arcand */ public class MeteorServlet extends AtmosphereServlet { public MeteorServlet() { this(false); } public MeteorServlet(boolean isFilter) { super(isFilter, false); } @Override public void init(final ServletConfig sc) throws ServletException { super.init(sc); String servletClass = framework().getAtmosphereConfig().getInitParameter(SERVLET_CLASS); String mapping = framework().getAtmosphereConfig().getInitParameter(MAPPING); String filterClass = framework().getAtmosphereConfig().getInitParameter(FILTER_CLASS); String filterName = framework().getAtmosphereConfig().getInitParameter(FILTER_NAME); ReflectorServletProcessor r = new ReflectorServletProcessor(); r.setServletClassName(servletClass); r.setFilterClassName(filterClass); r.setFilterName(filterName); if (mapping == null) { mapping = "/*"; + BroadcasterFactory.getDefault().remove("/*"); } framework.addAtmosphereHandler(mapping, r).initAtmosphereHandler(sc); } @Override public void destroy() { super.destroy(); Meteor.cache.clear(); } }
true
true
public void init(final ServletConfig sc) throws ServletException { super.init(sc); String servletClass = framework().getAtmosphereConfig().getInitParameter(SERVLET_CLASS); String mapping = framework().getAtmosphereConfig().getInitParameter(MAPPING); String filterClass = framework().getAtmosphereConfig().getInitParameter(FILTER_CLASS); String filterName = framework().getAtmosphereConfig().getInitParameter(FILTER_NAME); ReflectorServletProcessor r = new ReflectorServletProcessor(); r.setServletClassName(servletClass); r.setFilterClassName(filterClass); r.setFilterName(filterName); if (mapping == null) { mapping = "/*"; } framework.addAtmosphereHandler(mapping, r).initAtmosphereHandler(sc); }
public void init(final ServletConfig sc) throws ServletException { super.init(sc); String servletClass = framework().getAtmosphereConfig().getInitParameter(SERVLET_CLASS); String mapping = framework().getAtmosphereConfig().getInitParameter(MAPPING); String filterClass = framework().getAtmosphereConfig().getInitParameter(FILTER_CLASS); String filterName = framework().getAtmosphereConfig().getInitParameter(FILTER_NAME); ReflectorServletProcessor r = new ReflectorServletProcessor(); r.setServletClassName(servletClass); r.setFilterClassName(filterClass); r.setFilterName(filterName); if (mapping == null) { mapping = "/*"; BroadcasterFactory.getDefault().remove("/*"); } framework.addAtmosphereHandler(mapping, r).initAtmosphereHandler(sc); }
diff --git a/src/za/jamie/androidffmpegcmdline/ffmpeg/FfmpegJob.java b/src/za/jamie/androidffmpegcmdline/ffmpeg/FfmpegJob.java index 2d289f7..8b8f811 100644 --- a/src/za/jamie/androidffmpegcmdline/ffmpeg/FfmpegJob.java +++ b/src/za/jamie/androidffmpegcmdline/ffmpeg/FfmpegJob.java @@ -1,173 +1,173 @@ package za.jamie.androidffmpegcmdline.ffmpeg; import java.util.LinkedList; import java.util.List; import android.text.TextUtils; public class FfmpegJob { public String inputPath; public String inputFormat; public String inputVideoCodec; public String inputAudioCodec; public String videoCodec; public int videoBitrate; public int videoWidth = -1; public int videoHeight = -1; public float videoFramerate = -1; public String videoBitStreamFilter; public String audioCodec; public int audioBitrate; public int audioSampleRate; public int audioChannels; public int audioVolume; public String audioBitStreamFilter; public String audioFilter; public String videoFilter; public long startTime = -1; public long duration = -1; public String outputPath; public String format; public boolean disableVideo; public boolean disableAudio; private final String mFfmpegPath; public FfmpegJob(String ffmpegPath) { mFfmpegPath = ffmpegPath; } public ProcessRunnable create() { if (inputPath == null || outputPath == null) { throw new IllegalStateException("Need an input and output filepath!"); } final List<String> cmd = new LinkedList<String>(); cmd.add(mFfmpegPath); cmd.add("-y"); - if (TextUtils.isEmpty(inputFormat)) { + if (!TextUtils.isEmpty(inputFormat)) { cmd.add(FFMPEGArg.ARG_FORMAT); cmd.add(inputFormat); } - if (TextUtils.isEmpty(inputVideoCodec)) { + if (!TextUtils.isEmpty(inputVideoCodec)) { cmd.add(FFMPEGArg.ARG_VIDEOCODEC); cmd.add(inputVideoCodec); } - if (TextUtils.isEmpty(inputAudioCodec)) { + if (!TextUtils.isEmpty(inputAudioCodec)) { cmd.add(FFMPEGArg.ARG_AUDIOCODEC); cmd.add(inputAudioCodec); } cmd.add("-i"); cmd.add(inputPath); if (disableVideo) { cmd.add(FFMPEGArg.ARG_DISABLE_VIDEO); } else { if (videoBitrate > 0) { cmd.add(FFMPEGArg.ARG_BITRATE_VIDEO); cmd.add(videoBitrate + "k"); } if (videoWidth > 0 && videoHeight > 0) { cmd.add(FFMPEGArg.ARG_SIZE); cmd.add(videoWidth + "x" + videoHeight); } if (videoFramerate > -1) { cmd.add(FFMPEGArg.ARG_FRAMERATE); cmd.add(String.valueOf(videoFramerate)); } - if (TextUtils.isEmpty(videoCodec)) { + if (!TextUtils.isEmpty(videoCodec)) { cmd.add(FFMPEGArg.ARG_VIDEOCODEC); cmd.add(videoCodec); } - if (TextUtils.isEmpty(videoBitStreamFilter)) { + if (!TextUtils.isEmpty(videoBitStreamFilter)) { cmd.add(FFMPEGArg.ARG_VIDEOBITSTREAMFILTER); cmd.add(videoBitStreamFilter); } - if (TextUtils.isEmpty(videoFilter)) { + if (!TextUtils.isEmpty(videoFilter)) { cmd.add(FFMPEGArg.ARG_VIDEOFILTER); cmd.add(videoFilter); } } if (disableAudio) { cmd.add(FFMPEGArg.ARG_DISABLE_AUDIO); } else { - if (TextUtils.isEmpty(audioCodec)) { + if (!TextUtils.isEmpty(audioCodec)) { cmd.add(FFMPEGArg.ARG_AUDIOCODEC); cmd.add(audioCodec); } - if (TextUtils.isEmpty(audioBitStreamFilter)) { + if (!TextUtils.isEmpty(audioBitStreamFilter)) { cmd.add(FFMPEGArg.ARG_AUDIOBITSTREAMFILTER); cmd.add(audioBitStreamFilter); } - if (TextUtils.isEmpty(audioFilter)) { + if (!TextUtils.isEmpty(audioFilter)) { cmd.add(FFMPEGArg.ARG_AUDIOFILTER); cmd.add(audioFilter); } if (audioChannels > 0) { cmd.add(FFMPEGArg.ARG_CHANNELS_AUDIO); cmd.add(String.valueOf(audioChannels)); } if (audioVolume > 0) { cmd.add(FFMPEGArg.ARG_VOLUME_AUDIO); cmd.add(String.valueOf(audioVolume)); } if (audioBitrate > 0) { cmd.add(FFMPEGArg.ARG_BITRATE_AUDIO); cmd.add(audioBitrate + "k"); } } - if (TextUtils.isEmpty(format)) { + if (!TextUtils.isEmpty(format)) { cmd.add("-f"); cmd.add(format); } cmd.add(outputPath); final ProcessBuilder pb = new ProcessBuilder(cmd); return new ProcessRunnable(pb); } public class FFMPEGArg { String key; String value; public static final String ARG_VIDEOCODEC = "-vcodec"; public static final String ARG_AUDIOCODEC = "-acodec"; public static final String ARG_VIDEOBITSTREAMFILTER = "-vbsf"; public static final String ARG_AUDIOBITSTREAMFILTER = "-absf"; public static final String ARG_VIDEOFILTER = "-vf"; public static final String ARG_AUDIOFILTER = "-af"; public static final String ARG_VERBOSITY = "-v"; public static final String ARG_FILE_INPUT = "-i"; public static final String ARG_SIZE = "-s"; public static final String ARG_FRAMERATE = "-r"; public static final String ARG_FORMAT = "-f"; public static final String ARG_BITRATE_VIDEO = "-b:v"; public static final String ARG_BITRATE_AUDIO = "-b:a"; public static final String ARG_CHANNELS_AUDIO = "-ac"; public static final String ARG_FREQ_AUDIO = "-ar"; public static final String ARG_VOLUME_AUDIO = "-vol"; public static final String ARG_STARTTIME = "-ss"; public static final String ARG_DURATION = "-t"; public static final String ARG_DISABLE_AUDIO = "-an"; public static final String ARG_DISABLE_VIDEO = "-vn"; } }
false
true
public ProcessRunnable create() { if (inputPath == null || outputPath == null) { throw new IllegalStateException("Need an input and output filepath!"); } final List<String> cmd = new LinkedList<String>(); cmd.add(mFfmpegPath); cmd.add("-y"); if (TextUtils.isEmpty(inputFormat)) { cmd.add(FFMPEGArg.ARG_FORMAT); cmd.add(inputFormat); } if (TextUtils.isEmpty(inputVideoCodec)) { cmd.add(FFMPEGArg.ARG_VIDEOCODEC); cmd.add(inputVideoCodec); } if (TextUtils.isEmpty(inputAudioCodec)) { cmd.add(FFMPEGArg.ARG_AUDIOCODEC); cmd.add(inputAudioCodec); } cmd.add("-i"); cmd.add(inputPath); if (disableVideo) { cmd.add(FFMPEGArg.ARG_DISABLE_VIDEO); } else { if (videoBitrate > 0) { cmd.add(FFMPEGArg.ARG_BITRATE_VIDEO); cmd.add(videoBitrate + "k"); } if (videoWidth > 0 && videoHeight > 0) { cmd.add(FFMPEGArg.ARG_SIZE); cmd.add(videoWidth + "x" + videoHeight); } if (videoFramerate > -1) { cmd.add(FFMPEGArg.ARG_FRAMERATE); cmd.add(String.valueOf(videoFramerate)); } if (TextUtils.isEmpty(videoCodec)) { cmd.add(FFMPEGArg.ARG_VIDEOCODEC); cmd.add(videoCodec); } if (TextUtils.isEmpty(videoBitStreamFilter)) { cmd.add(FFMPEGArg.ARG_VIDEOBITSTREAMFILTER); cmd.add(videoBitStreamFilter); } if (TextUtils.isEmpty(videoFilter)) { cmd.add(FFMPEGArg.ARG_VIDEOFILTER); cmd.add(videoFilter); } } if (disableAudio) { cmd.add(FFMPEGArg.ARG_DISABLE_AUDIO); } else { if (TextUtils.isEmpty(audioCodec)) { cmd.add(FFMPEGArg.ARG_AUDIOCODEC); cmd.add(audioCodec); } if (TextUtils.isEmpty(audioBitStreamFilter)) { cmd.add(FFMPEGArg.ARG_AUDIOBITSTREAMFILTER); cmd.add(audioBitStreamFilter); } if (TextUtils.isEmpty(audioFilter)) { cmd.add(FFMPEGArg.ARG_AUDIOFILTER); cmd.add(audioFilter); } if (audioChannels > 0) { cmd.add(FFMPEGArg.ARG_CHANNELS_AUDIO); cmd.add(String.valueOf(audioChannels)); } if (audioVolume > 0) { cmd.add(FFMPEGArg.ARG_VOLUME_AUDIO); cmd.add(String.valueOf(audioVolume)); } if (audioBitrate > 0) { cmd.add(FFMPEGArg.ARG_BITRATE_AUDIO); cmd.add(audioBitrate + "k"); } } if (TextUtils.isEmpty(format)) { cmd.add("-f"); cmd.add(format); } cmd.add(outputPath); final ProcessBuilder pb = new ProcessBuilder(cmd); return new ProcessRunnable(pb); }
public ProcessRunnable create() { if (inputPath == null || outputPath == null) { throw new IllegalStateException("Need an input and output filepath!"); } final List<String> cmd = new LinkedList<String>(); cmd.add(mFfmpegPath); cmd.add("-y"); if (!TextUtils.isEmpty(inputFormat)) { cmd.add(FFMPEGArg.ARG_FORMAT); cmd.add(inputFormat); } if (!TextUtils.isEmpty(inputVideoCodec)) { cmd.add(FFMPEGArg.ARG_VIDEOCODEC); cmd.add(inputVideoCodec); } if (!TextUtils.isEmpty(inputAudioCodec)) { cmd.add(FFMPEGArg.ARG_AUDIOCODEC); cmd.add(inputAudioCodec); } cmd.add("-i"); cmd.add(inputPath); if (disableVideo) { cmd.add(FFMPEGArg.ARG_DISABLE_VIDEO); } else { if (videoBitrate > 0) { cmd.add(FFMPEGArg.ARG_BITRATE_VIDEO); cmd.add(videoBitrate + "k"); } if (videoWidth > 0 && videoHeight > 0) { cmd.add(FFMPEGArg.ARG_SIZE); cmd.add(videoWidth + "x" + videoHeight); } if (videoFramerate > -1) { cmd.add(FFMPEGArg.ARG_FRAMERATE); cmd.add(String.valueOf(videoFramerate)); } if (!TextUtils.isEmpty(videoCodec)) { cmd.add(FFMPEGArg.ARG_VIDEOCODEC); cmd.add(videoCodec); } if (!TextUtils.isEmpty(videoBitStreamFilter)) { cmd.add(FFMPEGArg.ARG_VIDEOBITSTREAMFILTER); cmd.add(videoBitStreamFilter); } if (!TextUtils.isEmpty(videoFilter)) { cmd.add(FFMPEGArg.ARG_VIDEOFILTER); cmd.add(videoFilter); } } if (disableAudio) { cmd.add(FFMPEGArg.ARG_DISABLE_AUDIO); } else { if (!TextUtils.isEmpty(audioCodec)) { cmd.add(FFMPEGArg.ARG_AUDIOCODEC); cmd.add(audioCodec); } if (!TextUtils.isEmpty(audioBitStreamFilter)) { cmd.add(FFMPEGArg.ARG_AUDIOBITSTREAMFILTER); cmd.add(audioBitStreamFilter); } if (!TextUtils.isEmpty(audioFilter)) { cmd.add(FFMPEGArg.ARG_AUDIOFILTER); cmd.add(audioFilter); } if (audioChannels > 0) { cmd.add(FFMPEGArg.ARG_CHANNELS_AUDIO); cmd.add(String.valueOf(audioChannels)); } if (audioVolume > 0) { cmd.add(FFMPEGArg.ARG_VOLUME_AUDIO); cmd.add(String.valueOf(audioVolume)); } if (audioBitrate > 0) { cmd.add(FFMPEGArg.ARG_BITRATE_AUDIO); cmd.add(audioBitrate + "k"); } } if (!TextUtils.isEmpty(format)) { cmd.add("-f"); cmd.add(format); } cmd.add(outputPath); final ProcessBuilder pb = new ProcessBuilder(cmd); return new ProcessRunnable(pb); }
diff --git a/core/src/net/sf/openrocket/gui/simulation/SimulationEditDialog.java b/core/src/net/sf/openrocket/gui/simulation/SimulationEditDialog.java index a4a461db..ae0784c3 100644 --- a/core/src/net/sf/openrocket/gui/simulation/SimulationEditDialog.java +++ b/core/src/net/sf/openrocket/gui/simulation/SimulationEditDialog.java @@ -1,324 +1,329 @@ package net.sf.openrocket.gui.simulation; import java.awt.CardLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import net.miginfocom.swing.MigLayout; import net.sf.openrocket.document.OpenRocketDocument; import net.sf.openrocket.document.Simulation; import net.sf.openrocket.gui.adaptors.FlightConfigurationModel; import net.sf.openrocket.gui.dialogs.flightconfiguration.FlightConfigurationDialog; import net.sf.openrocket.gui.util.GUIUtil; import net.sf.openrocket.l10n.Translator; import net.sf.openrocket.rocketcomponent.Configuration; import net.sf.openrocket.simulation.SimulationOptions; import net.sf.openrocket.startup.Application; public class SimulationEditDialog extends JDialog { private final Window parentWindow; private final Simulation[] simulation; private final OpenRocketDocument document; private final SimulationOptions conditions; private final Configuration configuration; private static final Translator trans = Application.getTranslator(); JPanel cards; private final static String EDITMODE = "EDIT"; private final static String PLOTMODE = "PLOT"; public SimulationEditDialog(Window parent, final OpenRocketDocument document, Simulation... sims) { //// Edit simulation super(parent, trans.get("simedtdlg.title.Editsim"), JDialog.ModalityType.DOCUMENT_MODAL); this.document = document; this.parentWindow = parent; this.simulation = sims; this.conditions = simulation[0].getOptions(); configuration = simulation[0].getConfiguration(); this.cards = new JPanel(new CardLayout()); this.add(cards); buildEditCard(); buildPlotCard(); this.validate(); this.pack(); this.setLocationByPlatform(true); GUIUtil.setDisposableDialogOptions(this, null); } private boolean isSingleEdit() { return simulation.length == 1; } private boolean allowsPlotMode() { return simulation.length == 1 && simulation[0].hasSimulationData(); } public void setEditMode() { CardLayout cl = (CardLayout) (cards.getLayout()); cl.show(cards, EDITMODE); cards.validate(); } public void setPlotMode() { if (!allowsPlotMode()) { return; } CardLayout cl = (CardLayout) (cards.getLayout()); cl.show(cards, PLOTMODE); cards.validate(); } private void copyChangesToAllSims() { if (simulation.length > 1) { for (int i = 1; i < simulation.length; i++) { simulation[i].getOptions().copyConditionsFrom(simulation[0].getOptions()); simulation[i].getSimulationListeners().clear(); simulation[i].getSimulationListeners().addAll(simulation[0].getSimulationListeners()); } } } private void refreshView() { cards.removeAll(); buildEditCard(); buildPlotCard(); this.validate(); } private void buildEditCard() { JPanel simEditPanel = new JPanel(new MigLayout("fill")); if (isSingleEdit()) { JPanel panel = new JPanel(new MigLayout("fill, ins 0")); //// Simulation name: panel.add(new JLabel(trans.get("simedtdlg.lbl.Simname") + " "), "growx 0, gapright para"); final JTextField field = new JTextField(simulation[0].getName()); field.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { setText(); } @Override public void insertUpdate(DocumentEvent e) { setText(); } @Override public void removeUpdate(DocumentEvent e) { setText(); } private void setText() { String name = field.getText(); if (name == null || name.equals("")) return; //System.out.println("Setting name:" + name); simulation[0].setName(name); } }); panel.add(field, "growx, wrap"); //// Flight selector //// Flight configuration: JLabel label = new JLabel(trans.get("simedtdlg.lbl.Flightcfg")); //// Select the motor configuration to use. label.setToolTipText(trans.get("simedtdlg.lbl.ttip.Flightcfg")); panel.add(label, "growx 0, gapright para"); JComboBox combo = new JComboBox(new FlightConfigurationModel(configuration)); //// Select the motor configuration to use. combo.setToolTipText(trans.get("simedtdlg.combo.ttip.Flightcfg")); combo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { conditions.setMotorConfigurationID(configuration.getFlightConfigurationID()); } }); panel.add(combo, "span, split"); //// Edit button JButton button = new JButton(trans.get("simedtdlg.but.FlightcfgEdit")); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JDialog configDialog = new FlightConfigurationDialog(SimulationEditDialog.this.document.getRocket(), SwingUtilities.windowForComponent(SimulationEditDialog.this)); configDialog.setVisible(true); } }); panel.add(button, "align left"); panel.add(new JPanel(), "growx, wrap"); simEditPanel.add(panel, "growx, wrap"); } JTabbedPane tabbedPane = new JTabbedPane(); //// Launch conditions tabbedPane.addTab(trans.get("simedtdlg.tab.Launchcond"), new SimulationConditionsPanel(simulation[0])); //// Simulation options tabbedPane.addTab(trans.get("simedtdlg.tab.Simopt"), new SimulationOptionsPanel(simulation[0])); tabbedPane.setSelectedIndex(0); simEditPanel.add(tabbedPane, "spanx, grow, wrap"); //// Open Plot button JButton button = new JButton(trans.get("SimulationEditDialog.btn.plot") + " >>"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SimulationEditDialog.this.setPlotMode(); } }); simEditPanel.add(button, "spanx, split 3, align left"); if (allowsPlotMode()) { button.setVisible(true); } else { button.setVisible(false); } //// Run simulation button button = new JButton(trans.get("SimulationEditDialog.btn.simulateAndPlot")); + if (!isSingleEdit()) { + button.setText(trans.get("SimulationEditDialog.btn.simulate")); + } button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { copyChangesToAllSims(); SimulationRunDialog.runSimulations(parentWindow, SimulationEditDialog.this.document, simulation); refreshView(); if (allowsPlotMode()) { setPlotMode(); + } else { + setVisible(false); } } }); simEditPanel.add(button, " align right, tag ok"); //// Close button JButton close = new JButton(trans.get("dlg.but.close")); close.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { copyChangesToAllSims(); SimulationEditDialog.this.dispose(); } }); simEditPanel.add(close, "tag ok"); cards.add(simEditPanel, EDITMODE); } private void buildPlotCard() { if (allowsPlotMode()) { JPanel plotExportPanel = new JPanel(new MigLayout("fill")); //// Simulation name: plotExportPanel.add(new JLabel(trans.get("simedtdlg.lbl.Simname") + " "), "span, split 2, shrink"); final JTextField field = new JTextField(simulation[0].getName()); field.setEditable(false); plotExportPanel.add(field, "shrinky, growx, wrap"); final JTabbedPane tabbedPane = new JTabbedPane(); //// Plot data final SimulationPlotPanel plotTab = new SimulationPlotPanel(simulation[0]); tabbedPane.addTab(trans.get("simedtdlg.tab.Plotdata"), plotTab); //// Export data final SimulationExportPanel exportTab = new SimulationExportPanel(simulation[0]); tabbedPane.addTab(trans.get("simedtdlg.tab.Exportdata"), exportTab); plotExportPanel.add(tabbedPane, "grow, wrap"); JButton button = new JButton("<< " + trans.get("SimulationEditDialog.btn.edit")); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SimulationEditDialog.this.setEditMode(); } }); plotExportPanel.add(button, "spanx, split 3, align left"); final JButton ok = new JButton(trans.get("SimulationEditDialog.btn.plot")); tabbedPane.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { int selectedIndex = tabbedPane.getSelectedIndex(); switch (selectedIndex) { case 0: ok.setText(trans.get("SimulationEditDialog.btn.plot")); break; case 1: ok.setText(trans.get("SimulationEditDialog.btn.export")); break; } } }); ok.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // If the simulation is out of date, run the simulation. if (simulation[0].getStatus() != Simulation.Status.UPTODATE) { new SimulationRunDialog(SimulationEditDialog.this.parentWindow, document, simulation[0]).setVisible(true); } if (tabbedPane.getSelectedIndex() == 0) { JDialog plot = plotTab.doPlot(SimulationEditDialog.this.parentWindow); if (plot != null) { plot.setVisible(true); } } else { if (exportTab.doExport()) { SimulationEditDialog.this.dispose(); } } } }); plotExportPanel.add(ok, "tag ok, split 2"); //// Close button JButton close = new JButton(trans.get("dlg.but.close")); close.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SimulationEditDialog.this.dispose(); } }); plotExportPanel.add(close, "tag cancel"); //plotExportPanel.validate(); cards.add(plotExportPanel, PLOTMODE); } } }
false
true
private void buildEditCard() { JPanel simEditPanel = new JPanel(new MigLayout("fill")); if (isSingleEdit()) { JPanel panel = new JPanel(new MigLayout("fill, ins 0")); //// Simulation name: panel.add(new JLabel(trans.get("simedtdlg.lbl.Simname") + " "), "growx 0, gapright para"); final JTextField field = new JTextField(simulation[0].getName()); field.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { setText(); } @Override public void insertUpdate(DocumentEvent e) { setText(); } @Override public void removeUpdate(DocumentEvent e) { setText(); } private void setText() { String name = field.getText(); if (name == null || name.equals("")) return; //System.out.println("Setting name:" + name); simulation[0].setName(name); } }); panel.add(field, "growx, wrap"); //// Flight selector //// Flight configuration: JLabel label = new JLabel(trans.get("simedtdlg.lbl.Flightcfg")); //// Select the motor configuration to use. label.setToolTipText(trans.get("simedtdlg.lbl.ttip.Flightcfg")); panel.add(label, "growx 0, gapright para"); JComboBox combo = new JComboBox(new FlightConfigurationModel(configuration)); //// Select the motor configuration to use. combo.setToolTipText(trans.get("simedtdlg.combo.ttip.Flightcfg")); combo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { conditions.setMotorConfigurationID(configuration.getFlightConfigurationID()); } }); panel.add(combo, "span, split"); //// Edit button JButton button = new JButton(trans.get("simedtdlg.but.FlightcfgEdit")); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JDialog configDialog = new FlightConfigurationDialog(SimulationEditDialog.this.document.getRocket(), SwingUtilities.windowForComponent(SimulationEditDialog.this)); configDialog.setVisible(true); } }); panel.add(button, "align left"); panel.add(new JPanel(), "growx, wrap"); simEditPanel.add(panel, "growx, wrap"); } JTabbedPane tabbedPane = new JTabbedPane(); //// Launch conditions tabbedPane.addTab(trans.get("simedtdlg.tab.Launchcond"), new SimulationConditionsPanel(simulation[0])); //// Simulation options tabbedPane.addTab(trans.get("simedtdlg.tab.Simopt"), new SimulationOptionsPanel(simulation[0])); tabbedPane.setSelectedIndex(0); simEditPanel.add(tabbedPane, "spanx, grow, wrap"); //// Open Plot button JButton button = new JButton(trans.get("SimulationEditDialog.btn.plot") + " >>"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SimulationEditDialog.this.setPlotMode(); } }); simEditPanel.add(button, "spanx, split 3, align left"); if (allowsPlotMode()) { button.setVisible(true); } else { button.setVisible(false); } //// Run simulation button button = new JButton(trans.get("SimulationEditDialog.btn.simulateAndPlot")); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { copyChangesToAllSims(); SimulationRunDialog.runSimulations(parentWindow, SimulationEditDialog.this.document, simulation); refreshView(); if (allowsPlotMode()) { setPlotMode(); } } }); simEditPanel.add(button, " align right, tag ok"); //// Close button JButton close = new JButton(trans.get("dlg.but.close")); close.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { copyChangesToAllSims(); SimulationEditDialog.this.dispose(); } }); simEditPanel.add(close, "tag ok"); cards.add(simEditPanel, EDITMODE); }
private void buildEditCard() { JPanel simEditPanel = new JPanel(new MigLayout("fill")); if (isSingleEdit()) { JPanel panel = new JPanel(new MigLayout("fill, ins 0")); //// Simulation name: panel.add(new JLabel(trans.get("simedtdlg.lbl.Simname") + " "), "growx 0, gapright para"); final JTextField field = new JTextField(simulation[0].getName()); field.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { setText(); } @Override public void insertUpdate(DocumentEvent e) { setText(); } @Override public void removeUpdate(DocumentEvent e) { setText(); } private void setText() { String name = field.getText(); if (name == null || name.equals("")) return; //System.out.println("Setting name:" + name); simulation[0].setName(name); } }); panel.add(field, "growx, wrap"); //// Flight selector //// Flight configuration: JLabel label = new JLabel(trans.get("simedtdlg.lbl.Flightcfg")); //// Select the motor configuration to use. label.setToolTipText(trans.get("simedtdlg.lbl.ttip.Flightcfg")); panel.add(label, "growx 0, gapright para"); JComboBox combo = new JComboBox(new FlightConfigurationModel(configuration)); //// Select the motor configuration to use. combo.setToolTipText(trans.get("simedtdlg.combo.ttip.Flightcfg")); combo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { conditions.setMotorConfigurationID(configuration.getFlightConfigurationID()); } }); panel.add(combo, "span, split"); //// Edit button JButton button = new JButton(trans.get("simedtdlg.but.FlightcfgEdit")); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JDialog configDialog = new FlightConfigurationDialog(SimulationEditDialog.this.document.getRocket(), SwingUtilities.windowForComponent(SimulationEditDialog.this)); configDialog.setVisible(true); } }); panel.add(button, "align left"); panel.add(new JPanel(), "growx, wrap"); simEditPanel.add(panel, "growx, wrap"); } JTabbedPane tabbedPane = new JTabbedPane(); //// Launch conditions tabbedPane.addTab(trans.get("simedtdlg.tab.Launchcond"), new SimulationConditionsPanel(simulation[0])); //// Simulation options tabbedPane.addTab(trans.get("simedtdlg.tab.Simopt"), new SimulationOptionsPanel(simulation[0])); tabbedPane.setSelectedIndex(0); simEditPanel.add(tabbedPane, "spanx, grow, wrap"); //// Open Plot button JButton button = new JButton(trans.get("SimulationEditDialog.btn.plot") + " >>"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SimulationEditDialog.this.setPlotMode(); } }); simEditPanel.add(button, "spanx, split 3, align left"); if (allowsPlotMode()) { button.setVisible(true); } else { button.setVisible(false); } //// Run simulation button button = new JButton(trans.get("SimulationEditDialog.btn.simulateAndPlot")); if (!isSingleEdit()) { button.setText(trans.get("SimulationEditDialog.btn.simulate")); } button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { copyChangesToAllSims(); SimulationRunDialog.runSimulations(parentWindow, SimulationEditDialog.this.document, simulation); refreshView(); if (allowsPlotMode()) { setPlotMode(); } else { setVisible(false); } } }); simEditPanel.add(button, " align right, tag ok"); //// Close button JButton close = new JButton(trans.get("dlg.but.close")); close.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { copyChangesToAllSims(); SimulationEditDialog.this.dispose(); } }); simEditPanel.add(close, "tag ok"); cards.add(simEditPanel, EDITMODE); }
diff --git a/TopWordsJob/src/main/java/fr/xebia/devoxx/hadoop/mostRt/IdentifyRtMapper.java b/TopWordsJob/src/main/java/fr/xebia/devoxx/hadoop/mostRt/IdentifyRtMapper.java index bfbfd96..da4b149 100644 --- a/TopWordsJob/src/main/java/fr/xebia/devoxx/hadoop/mostRt/IdentifyRtMapper.java +++ b/TopWordsJob/src/main/java/fr/xebia/devoxx/hadoop/mostRt/IdentifyRtMapper.java @@ -1,33 +1,33 @@ package fr.xebia.devoxx.hadoop.mostRt; import fr.xebia.devoxx.hadoop.mostRt.model.TwitterStream; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; public class IdentifyRtMapper extends Mapper<LongWritable, Text, TwitterStream, Text> { private final static Logger LOG = LoggerFactory.getLogger(IdentifyRtMapper.class); @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { if (value.toString().indexOf("-") > 0 && value.toString().contains("RT")) { TwitterStream twitterStream = new TwitterStream(); - Text retwittUser = new Text(value.toString().substring(0, value.toString().indexOf("-") - 2)); + Text retwittUser = new Text(value.toString().substring(0, value.toString().indexOf("-") - 1)); // Process message String rtToProcess = value.toString().substring(value.toString().indexOf("RT") + 3); twitterStream.setUser(new Text(rtToProcess.substring(rtToProcess.indexOf("@"), rtToProcess.indexOf(":") - 1))); twitterStream.setMessage(new Text(rtToProcess.substring(rtToProcess.indexOf(":") + 1))); context.write(twitterStream, value); } else { System.out.println("Rejected : " + value.toString()); } } }
true
true
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { if (value.toString().indexOf("-") > 0 && value.toString().contains("RT")) { TwitterStream twitterStream = new TwitterStream(); Text retwittUser = new Text(value.toString().substring(0, value.toString().indexOf("-") - 2)); // Process message String rtToProcess = value.toString().substring(value.toString().indexOf("RT") + 3); twitterStream.setUser(new Text(rtToProcess.substring(rtToProcess.indexOf("@"), rtToProcess.indexOf(":") - 1))); twitterStream.setMessage(new Text(rtToProcess.substring(rtToProcess.indexOf(":") + 1))); context.write(twitterStream, value); } else { System.out.println("Rejected : " + value.toString()); } }
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { if (value.toString().indexOf("-") > 0 && value.toString().contains("RT")) { TwitterStream twitterStream = new TwitterStream(); Text retwittUser = new Text(value.toString().substring(0, value.toString().indexOf("-") - 1)); // Process message String rtToProcess = value.toString().substring(value.toString().indexOf("RT") + 3); twitterStream.setUser(new Text(rtToProcess.substring(rtToProcess.indexOf("@"), rtToProcess.indexOf(":") - 1))); twitterStream.setMessage(new Text(rtToProcess.substring(rtToProcess.indexOf(":") + 1))); context.write(twitterStream, value); } else { System.out.println("Rejected : " + value.toString()); } }
diff --git a/FileThread.java b/FileThread.java index ff2dadf..547e873 100644 --- a/FileThread.java +++ b/FileThread.java @@ -1,400 +1,401 @@ /* File worker thread handles the business of uploading, downloading, and removing files for clients with valid tokens */ import java.lang.Thread; import java.net.Socket; import java.util.List; import java.util.ArrayList; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.security.*; import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import java.io.*; //These threads are spun off by FileServer.java public class FileThread extends Thread { private final Socket socket; private FileServer my_fs; private CryptoEngine cEngine; private AESKeySet aesKey; public FileThread(FileServer _fs, Socket _socket) { my_fs = _fs; socket = _socket; cEngine = new CryptoEngine(); } public void run() { boolean proceed = true; try { //setup IO streams to bind with the sockets System.out.println("*** New connection from " + socket.getInetAddress() + ":" + socket.getPort() + "***"); final ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); final ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()); Envelope response; Envelope message = (Envelope)input.readObject(); if(message.getMessage().equals("PUBKEYREQ")) { response = new Envelope("OK"); response.addObject(my_fs.authKeys.getPublic()); output.writeObject(response); } else { System.out.println("ERROR: FILETHREAD: FAILED TO SEND PUBLIC KEY"); System.exit(-1); } - message = (Envelope)readObject(input); + //This is wrong, they are still sending this as an envelope + message = (Envelope)input.readObject(); //The Client has encrypted a message for us with our public key. if(message.getMessage().equals("AESKEY")) { byte[] aesKeyBytes = (byte[]) message.getObjContents().get(0);//This is sent as byte[] byte[] aesKeyBytesA = new byte[128]; byte[] aesKeyBytesB = new byte[128]; System.arraycopy(aesKeyBytes, 0, aesKeyBytesA, 0, 128); System.arraycopy(aesKeyBytes, 128, aesKeyBytesB, 0, 128); aesKeyBytesA = cEngine.RSADecrypt(aesKeyBytesA, my_fs.authKeys.getPrivate()); aesKeyBytesB = cEngine.RSADecrypt(aesKeyBytesB, my_fs.authKeys.getPrivate()); System.arraycopy(aesKeyBytesA, 0, aesKeyBytes, 0, 100); System.arraycopy(aesKeyBytesB, 0, aesKeyBytes, 100, 41); ByteArrayInputStream fromBytes = new ByteArrayInputStream(aesKeyBytes); ObjectInputStream localInput = new ObjectInputStream(fromBytes); aesKey = new AESKeySet((Key) localInput.readObject(), new IvParameterSpec((byte[])message.getObjContents().get(1))); //get(1) contains the IV. localinput turned the byte[] back into a key } else { System.out.println("ERROR:FILETHREAD: COULD NOT SETUP AESKEY"); System.exit(-1); } //handle messages from the input stream(ie. socket) do { Envelope e = (Envelope)input.readObject(); System.out.println("Request received: " + e.getMessage()); // Handler to list files that this user is allowed to see //--LIST FILES--------------------------------------------------------------------------------------------------------- if(e.getMessage().equals("LFILES")) { ArrayList<ShareFile> theFiles = FileServer.fileList.getFiles(); if(theFiles.size() > 0) { response = new Envelope("OK");//success (check FileClient line 140 to see why this is the message response.addObject(theFiles);//See FileClient for protocol output.writeObject(response); } else //no files exist { response = new Envelope("FAIL -- no files exist. Ask yourself why. "); output.writeObject(response); } //--TODO: Test/Finish this handler------------------------------------------------------------------------------------------- } //--UPLOAD FILE-------------------------------------------------------------------------------------------------------- if(e.getMessage().equals("UPLOADF")) { if(e.getObjContents().size() < 3) { response = new Envelope("FAIL -- bad contents. Ask yourself why. "); } else { if(e.getObjContents().get(0) == null) { response = new Envelope("FAIL -- bad path. Ask yourself why. "); } if(e.getObjContents().get(1) == null) { response = new Envelope("FAIL -- bad group. Ask yourself why. "); } if(e.getObjContents().get(2) == null) { response = new Envelope("FAIL -- bad token. Ask yourself why. "); } else { //retrieve the contents of the envelope String remotePath = (String)e.getObjContents().get(0); String group = (String)e.getObjContents().get(1); UserToken yourToken = (UserToken)e.getObjContents().get(2); //Extract token if (FileServer.fileList.checkFile(remotePath)) { System.out.printf("Error: file already exists at %s\n", remotePath); response = new Envelope("FAIL -- file already exists. "); //Success } else if (!yourToken.getGroups().contains(group)) { System.out.printf("Error: user missing valid token for group %s\n", group); response = new Envelope("FAIL -- unauthorized user token for group. Ask yourself why. "); //Success } //create file and handle upload else { File file = new File("shared_files/" + remotePath.replace('/', '_')); file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); System.out.printf("Successfully created file %s\n", remotePath.replace('/', '_')); //request file contents response = new Envelope("READY"); //Success output.writeObject(response); //recieve and write the file to the directory e = (Envelope)input.readObject(); while (e.getMessage().compareTo("CHUNK") == 0) { fos.write((byte[])e.getObjContents().get(0), 0, (Integer)e.getObjContents().get(1)); response = new Envelope("READY"); //Success output.writeObject(response); e = (Envelope)input.readObject(); } //end of file identifier expected, inform the user of status if(e.getMessage().compareTo("EOF") == 0) { System.out.printf("Transfer successful file %s\n", remotePath); FileServer.fileList.addFile(yourToken.getSubject(), group, remotePath); response = new Envelope("OK"); //Success } else { System.out.printf("Error reading file %s from client\n", remotePath); response = new Envelope("ERROR -- failed attempt at reading file from client. "); //Success } fos.close(); } } } output.writeObject(response); } //--DOWNLOAD FILE------------------------------------------------------------------------------------------------------ else if (e.getMessage().compareTo("DOWNLOADF") == 0) { //retrieve the contents of the envelope, and attampt to access the requested file String remotePath = (String)e.getObjContents().get(0); UserToken t = (UserToken)e.getObjContents().get(1); ShareFile sf = FileServer.fileList.getFile("/" + remotePath); if (sf == null) { System.out.printf("Error: File %s doesn't exist\n", remotePath); e = new Envelope("ERROR -- file missing. Ask yourself why. "); output.writeObject(e); } else if (!t.getGroups().contains(sf.getGroup())) { System.out.printf("Error user %s doesn't have permission\n", t.getSubject()); e = new Envelope("ERROR -- insufficient user permissions. Ask yourself why. "); output.writeObject(e); } else { try { //try to grab the file File f = new File("shared_files/_"+remotePath.replace('/', '_')); if (!f.exists()) { System.out.printf("Error file %s missing from disk\n", "_"+remotePath.replace('/', '_')); e = new Envelope("ERROR -- file not on disk. Ask yourself why. "); output.writeObject(e); } else { FileInputStream fis = new FileInputStream(f); //send the file in 4096 byte chunks do { byte[] buf = new byte[4096]; if (e.getMessage().compareTo("DOWNLOADF") != 0) { System.out.printf("Server error: %s\n", e.getMessage()); break; } e = new Envelope("CHUNK"); int n = fis.read(buf); //can throw an IOException if (n > 0) { System.out.printf("."); } else if (n < 0) { System.out.println("Read error. Ask yourself why. "); } //tack the chunk onto the envelope and write it e.addObject(buf); e.addObject(new Integer(n)); output.writeObject(e); //get response e = (Envelope)input.readObject(); } while (fis.available() > 0); //If server indicates success, return the member list if(e.getMessage().compareTo("DOWNLOADF") == 0) { //send the end of file identifier e = new Envelope("EOF -- end of file. Ask yourself why. "); output.writeObject(e); //accept response e = (Envelope)input.readObject(); if(e.getMessage().compareTo("OK") == 0) { System.out.printf("File data upload successful\n"); } else { System.out.printf("Upload failed: %s\n", e.getMessage()); } } else { System.out.printf("Upload failed: %s\n", e.getMessage()); } } } catch(Exception e1) { System.err.println("Error: " + e.getMessage()); e1.printStackTrace(System.err); } } } //--DELETE FILE-------------------------------------------------------------------------------------------------------- else if (e.getMessage().compareTo("DELETEF")==0) { //retrieve the contents of the envelope, and attampt to access the requested file String remotePath = (String)e.getObjContents().get(0); UserToken t = (UserToken)e.getObjContents().get(1); ShareFile sf = FileServer.fileList.getFile("/"+remotePath); if (sf == null) { System.out.printf("Error: File %s doesn't exist\n", remotePath); e = new Envelope("ERROR -- file does not exists. "); } else if (!t.getGroups().contains(sf.getGroup())) { System.out.printf("Error user %s doesn't have permission\n", t.getSubject()); e = new Envelope("ERROR -- insufficient user permissions. Ask yourself why. "); } else { //attempt to delete the file try { File f = new File("shared_files/"+"_"+remotePath.replace('/', '_')); if (!f.exists()) { System.out.printf("Error file %s missing from disk\n", "_"+remotePath.replace('/', '_')); e = new Envelope("ERROR -- insufficient user permissions. Ask yourself why. "); } else if (f.delete()) { System.out.printf("File %s deleted from disk\n", "_"+remotePath.replace('/', '_')); FileServer.fileList.removeFile("/"+remotePath); e = new Envelope("OK"); } else { System.out.printf("Error deleting file %s from disk\n", "_"+remotePath.replace('/', '_')); e = new Envelope("ERROR -- file unable to be deleted from disk. "); } } catch(Exception e1) { System.err.println("Error: " + e1.getMessage()); e1.printStackTrace(System.err); e = new Envelope(e1.getMessage()); } } output.writeObject(e); } else if(e.getMessage().equals("DISCONNECT")) { socket.close(); proceed = false; } } while(proceed); } catch(Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(System.err); } } private Object readObject(ObjectInputStream input) { Object obj = null; try { byte[] eData = (byte[])input.readObject(); byte[] data = cEngine.AESDecrypt(eData, aesKey); ByteArrayInputStream fromBytes = new ByteArrayInputStream(data); ObjectInputStream localInput = new ObjectInputStream(fromBytes); obj = localInput.readObject(); } catch(Exception e) { e.printStackTrace(); } return obj; } private boolean writeObject(ObjectOutputStream output, Object obj) { try { ByteArrayOutputStream toBytes = new ByteArrayOutputStream();//create ByteArrayOutputStream ObjectOutputStream localOutput = new ObjectOutputStream(toBytes);//Make an object outputstream to that bytestream localOutput.writeObject(obj);//write to the bytearrayoutputstream byte[] data = toBytes.toByteArray();//turn our object into byte[] byte[] eData = cEngine.AESEncrypt(data, aesKey);//encrypt the data output.writeObject(eData);//write the data to the client toBytes.close(); localOutput.close(); } catch(Exception e) { e.printStackTrace(); return false; } return true; } }
true
true
public void run() { boolean proceed = true; try { //setup IO streams to bind with the sockets System.out.println("*** New connection from " + socket.getInetAddress() + ":" + socket.getPort() + "***"); final ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); final ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()); Envelope response; Envelope message = (Envelope)input.readObject(); if(message.getMessage().equals("PUBKEYREQ")) { response = new Envelope("OK"); response.addObject(my_fs.authKeys.getPublic()); output.writeObject(response); } else { System.out.println("ERROR: FILETHREAD: FAILED TO SEND PUBLIC KEY"); System.exit(-1); } message = (Envelope)readObject(input); //The Client has encrypted a message for us with our public key. if(message.getMessage().equals("AESKEY")) { byte[] aesKeyBytes = (byte[]) message.getObjContents().get(0);//This is sent as byte[] byte[] aesKeyBytesA = new byte[128]; byte[] aesKeyBytesB = new byte[128]; System.arraycopy(aesKeyBytes, 0, aesKeyBytesA, 0, 128); System.arraycopy(aesKeyBytes, 128, aesKeyBytesB, 0, 128); aesKeyBytesA = cEngine.RSADecrypt(aesKeyBytesA, my_fs.authKeys.getPrivate()); aesKeyBytesB = cEngine.RSADecrypt(aesKeyBytesB, my_fs.authKeys.getPrivate()); System.arraycopy(aesKeyBytesA, 0, aesKeyBytes, 0, 100); System.arraycopy(aesKeyBytesB, 0, aesKeyBytes, 100, 41); ByteArrayInputStream fromBytes = new ByteArrayInputStream(aesKeyBytes); ObjectInputStream localInput = new ObjectInputStream(fromBytes); aesKey = new AESKeySet((Key) localInput.readObject(), new IvParameterSpec((byte[])message.getObjContents().get(1))); //get(1) contains the IV. localinput turned the byte[] back into a key } else { System.out.println("ERROR:FILETHREAD: COULD NOT SETUP AESKEY"); System.exit(-1); } //handle messages from the input stream(ie. socket) do { Envelope e = (Envelope)input.readObject(); System.out.println("Request received: " + e.getMessage()); // Handler to list files that this user is allowed to see //--LIST FILES--------------------------------------------------------------------------------------------------------- if(e.getMessage().equals("LFILES")) { ArrayList<ShareFile> theFiles = FileServer.fileList.getFiles(); if(theFiles.size() > 0) { response = new Envelope("OK");//success (check FileClient line 140 to see why this is the message response.addObject(theFiles);//See FileClient for protocol output.writeObject(response); } else //no files exist { response = new Envelope("FAIL -- no files exist. Ask yourself why. "); output.writeObject(response); } //--TODO: Test/Finish this handler------------------------------------------------------------------------------------------- } //--UPLOAD FILE-------------------------------------------------------------------------------------------------------- if(e.getMessage().equals("UPLOADF")) { if(e.getObjContents().size() < 3) { response = new Envelope("FAIL -- bad contents. Ask yourself why. "); } else { if(e.getObjContents().get(0) == null) { response = new Envelope("FAIL -- bad path. Ask yourself why. "); } if(e.getObjContents().get(1) == null) { response = new Envelope("FAIL -- bad group. Ask yourself why. "); } if(e.getObjContents().get(2) == null) { response = new Envelope("FAIL -- bad token. Ask yourself why. "); } else { //retrieve the contents of the envelope String remotePath = (String)e.getObjContents().get(0); String group = (String)e.getObjContents().get(1); UserToken yourToken = (UserToken)e.getObjContents().get(2); //Extract token if (FileServer.fileList.checkFile(remotePath)) { System.out.printf("Error: file already exists at %s\n", remotePath); response = new Envelope("FAIL -- file already exists. "); //Success } else if (!yourToken.getGroups().contains(group)) { System.out.printf("Error: user missing valid token for group %s\n", group); response = new Envelope("FAIL -- unauthorized user token for group. Ask yourself why. "); //Success } //create file and handle upload else { File file = new File("shared_files/" + remotePath.replace('/', '_')); file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); System.out.printf("Successfully created file %s\n", remotePath.replace('/', '_')); //request file contents response = new Envelope("READY"); //Success output.writeObject(response); //recieve and write the file to the directory e = (Envelope)input.readObject(); while (e.getMessage().compareTo("CHUNK") == 0) { fos.write((byte[])e.getObjContents().get(0), 0, (Integer)e.getObjContents().get(1)); response = new Envelope("READY"); //Success output.writeObject(response); e = (Envelope)input.readObject(); } //end of file identifier expected, inform the user of status if(e.getMessage().compareTo("EOF") == 0) { System.out.printf("Transfer successful file %s\n", remotePath); FileServer.fileList.addFile(yourToken.getSubject(), group, remotePath); response = new Envelope("OK"); //Success } else { System.out.printf("Error reading file %s from client\n", remotePath); response = new Envelope("ERROR -- failed attempt at reading file from client. "); //Success } fos.close(); } } } output.writeObject(response); } //--DOWNLOAD FILE------------------------------------------------------------------------------------------------------ else if (e.getMessage().compareTo("DOWNLOADF") == 0) { //retrieve the contents of the envelope, and attampt to access the requested file String remotePath = (String)e.getObjContents().get(0); UserToken t = (UserToken)e.getObjContents().get(1); ShareFile sf = FileServer.fileList.getFile("/" + remotePath); if (sf == null) { System.out.printf("Error: File %s doesn't exist\n", remotePath); e = new Envelope("ERROR -- file missing. Ask yourself why. "); output.writeObject(e); } else if (!t.getGroups().contains(sf.getGroup())) { System.out.printf("Error user %s doesn't have permission\n", t.getSubject()); e = new Envelope("ERROR -- insufficient user permissions. Ask yourself why. "); output.writeObject(e); } else { try { //try to grab the file File f = new File("shared_files/_"+remotePath.replace('/', '_')); if (!f.exists()) { System.out.printf("Error file %s missing from disk\n", "_"+remotePath.replace('/', '_')); e = new Envelope("ERROR -- file not on disk. Ask yourself why. "); output.writeObject(e); } else { FileInputStream fis = new FileInputStream(f); //send the file in 4096 byte chunks do { byte[] buf = new byte[4096]; if (e.getMessage().compareTo("DOWNLOADF") != 0) { System.out.printf("Server error: %s\n", e.getMessage()); break; } e = new Envelope("CHUNK"); int n = fis.read(buf); //can throw an IOException if (n > 0) { System.out.printf("."); } else if (n < 0) { System.out.println("Read error. Ask yourself why. "); } //tack the chunk onto the envelope and write it e.addObject(buf); e.addObject(new Integer(n)); output.writeObject(e); //get response e = (Envelope)input.readObject(); } while (fis.available() > 0); //If server indicates success, return the member list if(e.getMessage().compareTo("DOWNLOADF") == 0) { //send the end of file identifier e = new Envelope("EOF -- end of file. Ask yourself why. "); output.writeObject(e); //accept response e = (Envelope)input.readObject(); if(e.getMessage().compareTo("OK") == 0) { System.out.printf("File data upload successful\n"); } else { System.out.printf("Upload failed: %s\n", e.getMessage()); } } else { System.out.printf("Upload failed: %s\n", e.getMessage()); } } } catch(Exception e1) { System.err.println("Error: " + e.getMessage()); e1.printStackTrace(System.err); } } } //--DELETE FILE-------------------------------------------------------------------------------------------------------- else if (e.getMessage().compareTo("DELETEF")==0) { //retrieve the contents of the envelope, and attampt to access the requested file String remotePath = (String)e.getObjContents().get(0); UserToken t = (UserToken)e.getObjContents().get(1); ShareFile sf = FileServer.fileList.getFile("/"+remotePath); if (sf == null) { System.out.printf("Error: File %s doesn't exist\n", remotePath); e = new Envelope("ERROR -- file does not exists. "); } else if (!t.getGroups().contains(sf.getGroup())) { System.out.printf("Error user %s doesn't have permission\n", t.getSubject()); e = new Envelope("ERROR -- insufficient user permissions. Ask yourself why. "); } else { //attempt to delete the file try { File f = new File("shared_files/"+"_"+remotePath.replace('/', '_')); if (!f.exists()) { System.out.printf("Error file %s missing from disk\n", "_"+remotePath.replace('/', '_')); e = new Envelope("ERROR -- insufficient user permissions. Ask yourself why. "); } else if (f.delete()) { System.out.printf("File %s deleted from disk\n", "_"+remotePath.replace('/', '_')); FileServer.fileList.removeFile("/"+remotePath); e = new Envelope("OK"); } else { System.out.printf("Error deleting file %s from disk\n", "_"+remotePath.replace('/', '_')); e = new Envelope("ERROR -- file unable to be deleted from disk. "); } } catch(Exception e1) { System.err.println("Error: " + e1.getMessage()); e1.printStackTrace(System.err); e = new Envelope(e1.getMessage()); } } output.writeObject(e); } else if(e.getMessage().equals("DISCONNECT")) { socket.close(); proceed = false; } } while(proceed); } catch(Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(System.err); } }
public void run() { boolean proceed = true; try { //setup IO streams to bind with the sockets System.out.println("*** New connection from " + socket.getInetAddress() + ":" + socket.getPort() + "***"); final ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); final ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()); Envelope response; Envelope message = (Envelope)input.readObject(); if(message.getMessage().equals("PUBKEYREQ")) { response = new Envelope("OK"); response.addObject(my_fs.authKeys.getPublic()); output.writeObject(response); } else { System.out.println("ERROR: FILETHREAD: FAILED TO SEND PUBLIC KEY"); System.exit(-1); } //This is wrong, they are still sending this as an envelope message = (Envelope)input.readObject(); //The Client has encrypted a message for us with our public key. if(message.getMessage().equals("AESKEY")) { byte[] aesKeyBytes = (byte[]) message.getObjContents().get(0);//This is sent as byte[] byte[] aesKeyBytesA = new byte[128]; byte[] aesKeyBytesB = new byte[128]; System.arraycopy(aesKeyBytes, 0, aesKeyBytesA, 0, 128); System.arraycopy(aesKeyBytes, 128, aesKeyBytesB, 0, 128); aesKeyBytesA = cEngine.RSADecrypt(aesKeyBytesA, my_fs.authKeys.getPrivate()); aesKeyBytesB = cEngine.RSADecrypt(aesKeyBytesB, my_fs.authKeys.getPrivate()); System.arraycopy(aesKeyBytesA, 0, aesKeyBytes, 0, 100); System.arraycopy(aesKeyBytesB, 0, aesKeyBytes, 100, 41); ByteArrayInputStream fromBytes = new ByteArrayInputStream(aesKeyBytes); ObjectInputStream localInput = new ObjectInputStream(fromBytes); aesKey = new AESKeySet((Key) localInput.readObject(), new IvParameterSpec((byte[])message.getObjContents().get(1))); //get(1) contains the IV. localinput turned the byte[] back into a key } else { System.out.println("ERROR:FILETHREAD: COULD NOT SETUP AESKEY"); System.exit(-1); } //handle messages from the input stream(ie. socket) do { Envelope e = (Envelope)input.readObject(); System.out.println("Request received: " + e.getMessage()); // Handler to list files that this user is allowed to see //--LIST FILES--------------------------------------------------------------------------------------------------------- if(e.getMessage().equals("LFILES")) { ArrayList<ShareFile> theFiles = FileServer.fileList.getFiles(); if(theFiles.size() > 0) { response = new Envelope("OK");//success (check FileClient line 140 to see why this is the message response.addObject(theFiles);//See FileClient for protocol output.writeObject(response); } else //no files exist { response = new Envelope("FAIL -- no files exist. Ask yourself why. "); output.writeObject(response); } //--TODO: Test/Finish this handler------------------------------------------------------------------------------------------- } //--UPLOAD FILE-------------------------------------------------------------------------------------------------------- if(e.getMessage().equals("UPLOADF")) { if(e.getObjContents().size() < 3) { response = new Envelope("FAIL -- bad contents. Ask yourself why. "); } else { if(e.getObjContents().get(0) == null) { response = new Envelope("FAIL -- bad path. Ask yourself why. "); } if(e.getObjContents().get(1) == null) { response = new Envelope("FAIL -- bad group. Ask yourself why. "); } if(e.getObjContents().get(2) == null) { response = new Envelope("FAIL -- bad token. Ask yourself why. "); } else { //retrieve the contents of the envelope String remotePath = (String)e.getObjContents().get(0); String group = (String)e.getObjContents().get(1); UserToken yourToken = (UserToken)e.getObjContents().get(2); //Extract token if (FileServer.fileList.checkFile(remotePath)) { System.out.printf("Error: file already exists at %s\n", remotePath); response = new Envelope("FAIL -- file already exists. "); //Success } else if (!yourToken.getGroups().contains(group)) { System.out.printf("Error: user missing valid token for group %s\n", group); response = new Envelope("FAIL -- unauthorized user token for group. Ask yourself why. "); //Success } //create file and handle upload else { File file = new File("shared_files/" + remotePath.replace('/', '_')); file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); System.out.printf("Successfully created file %s\n", remotePath.replace('/', '_')); //request file contents response = new Envelope("READY"); //Success output.writeObject(response); //recieve and write the file to the directory e = (Envelope)input.readObject(); while (e.getMessage().compareTo("CHUNK") == 0) { fos.write((byte[])e.getObjContents().get(0), 0, (Integer)e.getObjContents().get(1)); response = new Envelope("READY"); //Success output.writeObject(response); e = (Envelope)input.readObject(); } //end of file identifier expected, inform the user of status if(e.getMessage().compareTo("EOF") == 0) { System.out.printf("Transfer successful file %s\n", remotePath); FileServer.fileList.addFile(yourToken.getSubject(), group, remotePath); response = new Envelope("OK"); //Success } else { System.out.printf("Error reading file %s from client\n", remotePath); response = new Envelope("ERROR -- failed attempt at reading file from client. "); //Success } fos.close(); } } } output.writeObject(response); } //--DOWNLOAD FILE------------------------------------------------------------------------------------------------------ else if (e.getMessage().compareTo("DOWNLOADF") == 0) { //retrieve the contents of the envelope, and attampt to access the requested file String remotePath = (String)e.getObjContents().get(0); UserToken t = (UserToken)e.getObjContents().get(1); ShareFile sf = FileServer.fileList.getFile("/" + remotePath); if (sf == null) { System.out.printf("Error: File %s doesn't exist\n", remotePath); e = new Envelope("ERROR -- file missing. Ask yourself why. "); output.writeObject(e); } else if (!t.getGroups().contains(sf.getGroup())) { System.out.printf("Error user %s doesn't have permission\n", t.getSubject()); e = new Envelope("ERROR -- insufficient user permissions. Ask yourself why. "); output.writeObject(e); } else { try { //try to grab the file File f = new File("shared_files/_"+remotePath.replace('/', '_')); if (!f.exists()) { System.out.printf("Error file %s missing from disk\n", "_"+remotePath.replace('/', '_')); e = new Envelope("ERROR -- file not on disk. Ask yourself why. "); output.writeObject(e); } else { FileInputStream fis = new FileInputStream(f); //send the file in 4096 byte chunks do { byte[] buf = new byte[4096]; if (e.getMessage().compareTo("DOWNLOADF") != 0) { System.out.printf("Server error: %s\n", e.getMessage()); break; } e = new Envelope("CHUNK"); int n = fis.read(buf); //can throw an IOException if (n > 0) { System.out.printf("."); } else if (n < 0) { System.out.println("Read error. Ask yourself why. "); } //tack the chunk onto the envelope and write it e.addObject(buf); e.addObject(new Integer(n)); output.writeObject(e); //get response e = (Envelope)input.readObject(); } while (fis.available() > 0); //If server indicates success, return the member list if(e.getMessage().compareTo("DOWNLOADF") == 0) { //send the end of file identifier e = new Envelope("EOF -- end of file. Ask yourself why. "); output.writeObject(e); //accept response e = (Envelope)input.readObject(); if(e.getMessage().compareTo("OK") == 0) { System.out.printf("File data upload successful\n"); } else { System.out.printf("Upload failed: %s\n", e.getMessage()); } } else { System.out.printf("Upload failed: %s\n", e.getMessage()); } } } catch(Exception e1) { System.err.println("Error: " + e.getMessage()); e1.printStackTrace(System.err); } } } //--DELETE FILE-------------------------------------------------------------------------------------------------------- else if (e.getMessage().compareTo("DELETEF")==0) { //retrieve the contents of the envelope, and attampt to access the requested file String remotePath = (String)e.getObjContents().get(0); UserToken t = (UserToken)e.getObjContents().get(1); ShareFile sf = FileServer.fileList.getFile("/"+remotePath); if (sf == null) { System.out.printf("Error: File %s doesn't exist\n", remotePath); e = new Envelope("ERROR -- file does not exists. "); } else if (!t.getGroups().contains(sf.getGroup())) { System.out.printf("Error user %s doesn't have permission\n", t.getSubject()); e = new Envelope("ERROR -- insufficient user permissions. Ask yourself why. "); } else { //attempt to delete the file try { File f = new File("shared_files/"+"_"+remotePath.replace('/', '_')); if (!f.exists()) { System.out.printf("Error file %s missing from disk\n", "_"+remotePath.replace('/', '_')); e = new Envelope("ERROR -- insufficient user permissions. Ask yourself why. "); } else if (f.delete()) { System.out.printf("File %s deleted from disk\n", "_"+remotePath.replace('/', '_')); FileServer.fileList.removeFile("/"+remotePath); e = new Envelope("OK"); } else { System.out.printf("Error deleting file %s from disk\n", "_"+remotePath.replace('/', '_')); e = new Envelope("ERROR -- file unable to be deleted from disk. "); } } catch(Exception e1) { System.err.println("Error: " + e1.getMessage()); e1.printStackTrace(System.err); e = new Envelope(e1.getMessage()); } } output.writeObject(e); } else if(e.getMessage().equals("DISCONNECT")) { socket.close(); proceed = false; } } while(proceed); } catch(Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(System.err); } }
diff --git a/src/main/java/com/sonyericsson/jenkins/plugins/bfa/GerritMessageProviderExtension.java b/src/main/java/com/sonyericsson/jenkins/plugins/bfa/GerritMessageProviderExtension.java index 76cd102..d2e5632 100644 --- a/src/main/java/com/sonyericsson/jenkins/plugins/bfa/GerritMessageProviderExtension.java +++ b/src/main/java/com/sonyericsson/jenkins/plugins/bfa/GerritMessageProviderExtension.java @@ -1,62 +1,62 @@ /* * The MIT License * * Copyright 2012 Sony Mobile Communications AB. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.sonyericsson.jenkins.plugins.bfa; import com.sonyericsson.hudson.plugins.gerrit.trigger.gerritnotifier.GerritMessageProvider; import com.sonyericsson.jenkins.plugins.bfa.model.FailureCauseBuildAction; import com.sonyericsson.jenkins.plugins.bfa.model.FoundFailureCause; import hudson.Extension; import hudson.model.AbstractBuild; /** * ExtensionPoint that allows BFA to send the failure cause description * directly to Gerrit. * * @author Gustaf Lundh &lt;[email protected]&gt; */ @Extension(optional = true) public class GerritMessageProviderExtension extends GerritMessageProvider { @Override public String getBuildCompletedMessage(AbstractBuild build) { if (PluginImpl.getInstance().isGerritTriggerEnabled()) { StringBuilder customMessage = new StringBuilder(); if (build != null) { FailureCauseBuildAction action = build.getAction(FailureCauseBuildAction.class); if (action != null) { for (FoundFailureCause failureCause : action.getFoundFailureCauses()) { if (customMessage.length() > 0) { customMessage.append(" \n "); } customMessage.append(failureCause.getDescription()); } if (customMessage.length() > 0) { - return customMessage.toString(); + return customMessage.toString().replaceAll("'", "\\'"); } } } } return null; } }
true
true
public String getBuildCompletedMessage(AbstractBuild build) { if (PluginImpl.getInstance().isGerritTriggerEnabled()) { StringBuilder customMessage = new StringBuilder(); if (build != null) { FailureCauseBuildAction action = build.getAction(FailureCauseBuildAction.class); if (action != null) { for (FoundFailureCause failureCause : action.getFoundFailureCauses()) { if (customMessage.length() > 0) { customMessage.append(" \n "); } customMessage.append(failureCause.getDescription()); } if (customMessage.length() > 0) { return customMessage.toString(); } } } } return null; }
public String getBuildCompletedMessage(AbstractBuild build) { if (PluginImpl.getInstance().isGerritTriggerEnabled()) { StringBuilder customMessage = new StringBuilder(); if (build != null) { FailureCauseBuildAction action = build.getAction(FailureCauseBuildAction.class); if (action != null) { for (FoundFailureCause failureCause : action.getFoundFailureCauses()) { if (customMessage.length() > 0) { customMessage.append(" \n "); } customMessage.append(failureCause.getDescription()); } if (customMessage.length() > 0) { return customMessage.toString().replaceAll("'", "\\'"); } } } } return null; }
diff --git a/core/src/java/liquibase/preconditions/RunningAsPrecondition.java b/core/src/java/liquibase/preconditions/RunningAsPrecondition.java index 23c4c988..178ce8c8 100644 --- a/core/src/java/liquibase/preconditions/RunningAsPrecondition.java +++ b/core/src/java/liquibase/preconditions/RunningAsPrecondition.java @@ -1,45 +1,47 @@ package liquibase.preconditions; import liquibase.DatabaseChangeLog; import liquibase.exception.PreconditionFailedException; import liquibase.migrator.Migrator; import java.sql.SQLException; /** * Precondition that checks the name of the user executing the change log. */ public class RunningAsPrecondition implements Precondition { private String username; public RunningAsPrecondition() { username = ""; } public void setUsername(String aUserName) { username = aUserName; } public String getUsername() { return username; } public void check(Migrator migrator, DatabaseChangeLog changeLog) throws PreconditionFailedException { try { String loggedusername = migrator.getDatabase().getConnection().getMetaData().getUserName(); - loggedusername = loggedusername.substring(0, loggedusername.indexOf('@')); + if (loggedusername.indexOf('@') >= 0) { + loggedusername = loggedusername.substring(0, loggedusername.indexOf('@')); + } if (!username.equals(loggedusername)) { throw new PreconditionFailedException("RunningAs Precondition failed: expected "+username+", was "+loggedusername, changeLog, this); } } catch (SQLException e) { throw new RuntimeException("Cannot determine username", e); } } public String getTagName() { return "runningAs"; } }
true
true
public void check(Migrator migrator, DatabaseChangeLog changeLog) throws PreconditionFailedException { try { String loggedusername = migrator.getDatabase().getConnection().getMetaData().getUserName(); loggedusername = loggedusername.substring(0, loggedusername.indexOf('@')); if (!username.equals(loggedusername)) { throw new PreconditionFailedException("RunningAs Precondition failed: expected "+username+", was "+loggedusername, changeLog, this); } } catch (SQLException e) { throw new RuntimeException("Cannot determine username", e); } }
public void check(Migrator migrator, DatabaseChangeLog changeLog) throws PreconditionFailedException { try { String loggedusername = migrator.getDatabase().getConnection().getMetaData().getUserName(); if (loggedusername.indexOf('@') >= 0) { loggedusername = loggedusername.substring(0, loggedusername.indexOf('@')); } if (!username.equals(loggedusername)) { throw new PreconditionFailedException("RunningAs Precondition failed: expected "+username+", was "+loggedusername, changeLog, this); } } catch (SQLException e) { throw new RuntimeException("Cannot determine username", e); } }
diff --git a/docs/tutorials/tutorial1/chatapp/Client.java b/docs/tutorials/tutorial1/chatapp/Client.java index 67608cb..3d40d6f 100644 --- a/docs/tutorials/tutorial1/chatapp/Client.java +++ b/docs/tutorials/tutorial1/chatapp/Client.java @@ -1,63 +1,64 @@ package chatapp; import java.io.BufferedReader; import java.io.IOException; import java.io.EOFException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; //import edu.berkeley.xtrace.XTraceContext; //import edu.berkeley.xtrace.XTraceMetadata; public class Client{ public static int PORT=8888; public static void main(String argv[]) throws IOException, ClassNotFoundException{ /* Setting up X-Tracing */ //XTraceContext.startTrace("ChatClient", "Run Tutorial 1" , "tutorial"); /* Set up the connection to the server */ Socket s = new Socket("localhost", PORT); ObjectInputStream in = new ObjectInputStream(s.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream()); /* Setup up input from the client user */ BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); + System.out.println("Welcome to the X-Trace tutorial 1 chat app client, type bye to exit"); /* Talk to the server */ ChatMessage msgObjIn = new ChatMessage(); String input; while (true){ /* Get input from user and send it */ System.out.print("YOU: "); ChatMessage msgObjOut = new ChatMessage(stdin.readLine()); //XTraceContext.logEvent("ChatClient", "SendUsersMessage", "Message", msgObjOut.message); //msgObjOut.xtraceMD = XTraceContext.getThreadContext().pack(); out.writeObject(msgObjOut); msgObjOut = null; /* Collect reply message from server and display it to user */ try{ msgObjIn = (ChatMessage) in.readObject(); //XTraceContext.setThreadContext(XTraceMetadata.createFromBytes(msgObjIn.xtraceMD,0,16)); //XTraceContext.logEvent("ChatClient", "ReceivedServersMessage"); input = msgObjIn.message; System.out.println("SERVER: " + input); } catch (EOFException e){ System.out.println("Server terminated your connection"); break; } } /* clean up */ in.close(); stdin.close(); s.close(); } }
true
true
public static void main(String argv[]) throws IOException, ClassNotFoundException{ /* Setting up X-Tracing */ //XTraceContext.startTrace("ChatClient", "Run Tutorial 1" , "tutorial"); /* Set up the connection to the server */ Socket s = new Socket("localhost", PORT); ObjectInputStream in = new ObjectInputStream(s.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream()); /* Setup up input from the client user */ BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); /* Talk to the server */ ChatMessage msgObjIn = new ChatMessage(); String input; while (true){ /* Get input from user and send it */ System.out.print("YOU: "); ChatMessage msgObjOut = new ChatMessage(stdin.readLine()); //XTraceContext.logEvent("ChatClient", "SendUsersMessage", "Message", msgObjOut.message); //msgObjOut.xtraceMD = XTraceContext.getThreadContext().pack(); out.writeObject(msgObjOut); msgObjOut = null; /* Collect reply message from server and display it to user */ try{ msgObjIn = (ChatMessage) in.readObject(); //XTraceContext.setThreadContext(XTraceMetadata.createFromBytes(msgObjIn.xtraceMD,0,16)); //XTraceContext.logEvent("ChatClient", "ReceivedServersMessage"); input = msgObjIn.message; System.out.println("SERVER: " + input); } catch (EOFException e){ System.out.println("Server terminated your connection"); break; } } /* clean up */ in.close(); stdin.close(); s.close(); }
public static void main(String argv[]) throws IOException, ClassNotFoundException{ /* Setting up X-Tracing */ //XTraceContext.startTrace("ChatClient", "Run Tutorial 1" , "tutorial"); /* Set up the connection to the server */ Socket s = new Socket("localhost", PORT); ObjectInputStream in = new ObjectInputStream(s.getInputStream()); ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream()); /* Setup up input from the client user */ BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); System.out.println("Welcome to the X-Trace tutorial 1 chat app client, type bye to exit"); /* Talk to the server */ ChatMessage msgObjIn = new ChatMessage(); String input; while (true){ /* Get input from user and send it */ System.out.print("YOU: "); ChatMessage msgObjOut = new ChatMessage(stdin.readLine()); //XTraceContext.logEvent("ChatClient", "SendUsersMessage", "Message", msgObjOut.message); //msgObjOut.xtraceMD = XTraceContext.getThreadContext().pack(); out.writeObject(msgObjOut); msgObjOut = null; /* Collect reply message from server and display it to user */ try{ msgObjIn = (ChatMessage) in.readObject(); //XTraceContext.setThreadContext(XTraceMetadata.createFromBytes(msgObjIn.xtraceMD,0,16)); //XTraceContext.logEvent("ChatClient", "ReceivedServersMessage"); input = msgObjIn.message; System.out.println("SERVER: " + input); } catch (EOFException e){ System.out.println("Server terminated your connection"); break; } } /* clean up */ in.close(); stdin.close(); s.close(); }
diff --git a/pn-dispatcher/src/main/java/info/papyri/dispatch/BiblioSearch.java b/pn-dispatcher/src/main/java/info/papyri/dispatch/BiblioSearch.java index 7cacfa84..61bd272d 100644 --- a/pn-dispatcher/src/main/java/info/papyri/dispatch/BiblioSearch.java +++ b/pn-dispatcher/src/main/java/info/papyri/dispatch/BiblioSearch.java @@ -1,190 +1,190 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package info.papyri.dispatch; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLEncoder; import java.net.MalformedURLException; import javax.servlet.ServletConfig; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.request.QueryRequest; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.client.solrj.SolrRequest.METHOD; /** * * @author hcayless */ public class BiblioSearch extends HttpServlet { private String solrUrl; private URL searchURL; private String xmlPath = ""; private String htmlPath = ""; private String home = ""; private FileUtils util; private SolrUtils solrutil; private static String BiblioSearch = "biblio-search/"; @Override public void init(ServletConfig config) throws ServletException { super.init(config); solrUrl = config.getInitParameter("solrUrl"); xmlPath = config.getInitParameter("xmlPath"); htmlPath = config.getInitParameter("htmlPath"); home = config.getInitParameter("home"); util = new FileUtils(xmlPath, htmlPath); solrutil = new SolrUtils(config); try { searchURL = new URL("file://" + home + "/" + "bibliosearch.html"); } catch (MalformedURLException e) { throw new ServletException(e); } } /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); BufferedReader reader = null; try { String q = request.getParameter("q"); reader = new BufferedReader(new InputStreamReader(searchURL.openStream())); String line = ""; while ((line = reader.readLine()) != null) { if (line.contains("<!-- Results -->") && !("".equals(q) || q == null)) { SolrServer solr = new CommonsHttpSolrServer(solrUrl + BiblioSearch); int rows = 30; try { rows = Integer.parseInt(request.getParameter("rows")); } catch (Exception e) { } int start = 0; try { start = Integer.parseInt(request.getParameter("start")); } catch (Exception e) {} SolrQuery sq = new SolrQuery(); try { - sq.setQuery(q); + sq.setQuery(q.toLowerCase()); sq.setStart(start); sq.setRows(rows); sq.addSortField("date", SolrQuery.ORDER.asc); sq.addSortField("sort", SolrQuery.ORDER.asc); QueryRequest req = new QueryRequest(sq); req.setMethod(METHOD.POST); QueryResponse rs = req.process(solr); SolrDocumentList docs = rs.getResults(); out.println("<p>" + docs.getNumFound() + " hits on \"" + q.toString() + "\".</p>"); out.println("<table>"); String uq = q; try { uq = URLEncoder.encode(q, "UTF-8"); } catch (Exception e) { } for (SolrDocument doc : docs) { StringBuilder row = new StringBuilder("<tr class=\"result-record\"><td>"); row.append("<a href=\""); row.append("/biblio/"); row.append(((String) doc.getFieldValue("id"))); row.append("/?q="); row.append(uq); row.append("\">"); row.append(doc.getFieldValue("display")); row.append("</a>"); row.append("</td>"); row.append("</tr>"); out.print(row); } out.println("</table>"); if (docs.getNumFound() > rows) { out.println("<div id=\"pagination\">"); int pages = (int) Math.ceil((double) docs.getNumFound() / (double) rows); int p = 0; while (p < pages) { if ((p * rows) == start) { out.print("<div class=\"page current\">"); out.print((p + 1) + " "); out.print("</div>"); } else { StringBuilder plink = new StringBuilder(uq + "&start=" + p * rows + "&rows=" + rows); out.print("<div class=\"page\"><a href=\"/bibliosearch?q=" + plink + "\">" + (p + 1) + "</a></div>"); } p++; } out.println("</div>"); } } catch (SolrServerException e) { out.println("<p>Unable to execute query. Please try again.</p>"); throw new ServletException(e); } } else { out.println(line); } } } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
true
true
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); BufferedReader reader = null; try { String q = request.getParameter("q"); reader = new BufferedReader(new InputStreamReader(searchURL.openStream())); String line = ""; while ((line = reader.readLine()) != null) { if (line.contains("<!-- Results -->") && !("".equals(q) || q == null)) { SolrServer solr = new CommonsHttpSolrServer(solrUrl + BiblioSearch); int rows = 30; try { rows = Integer.parseInt(request.getParameter("rows")); } catch (Exception e) { } int start = 0; try { start = Integer.parseInt(request.getParameter("start")); } catch (Exception e) {} SolrQuery sq = new SolrQuery(); try { sq.setQuery(q); sq.setStart(start); sq.setRows(rows); sq.addSortField("date", SolrQuery.ORDER.asc); sq.addSortField("sort", SolrQuery.ORDER.asc); QueryRequest req = new QueryRequest(sq); req.setMethod(METHOD.POST); QueryResponse rs = req.process(solr); SolrDocumentList docs = rs.getResults(); out.println("<p>" + docs.getNumFound() + " hits on \"" + q.toString() + "\".</p>"); out.println("<table>"); String uq = q; try { uq = URLEncoder.encode(q, "UTF-8"); } catch (Exception e) { } for (SolrDocument doc : docs) { StringBuilder row = new StringBuilder("<tr class=\"result-record\"><td>"); row.append("<a href=\""); row.append("/biblio/"); row.append(((String) doc.getFieldValue("id"))); row.append("/?q="); row.append(uq); row.append("\">"); row.append(doc.getFieldValue("display")); row.append("</a>"); row.append("</td>"); row.append("</tr>"); out.print(row); } out.println("</table>"); if (docs.getNumFound() > rows) { out.println("<div id=\"pagination\">"); int pages = (int) Math.ceil((double) docs.getNumFound() / (double) rows); int p = 0; while (p < pages) { if ((p * rows) == start) { out.print("<div class=\"page current\">"); out.print((p + 1) + " "); out.print("</div>"); } else { StringBuilder plink = new StringBuilder(uq + "&start=" + p * rows + "&rows=" + rows); out.print("<div class=\"page\"><a href=\"/bibliosearch?q=" + plink + "\">" + (p + 1) + "</a></div>"); } p++; } out.println("</div>"); } } catch (SolrServerException e) { out.println("<p>Unable to execute query. Please try again.</p>"); throw new ServletException(e); } } else { out.println(line); } } } finally { out.close(); } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); BufferedReader reader = null; try { String q = request.getParameter("q"); reader = new BufferedReader(new InputStreamReader(searchURL.openStream())); String line = ""; while ((line = reader.readLine()) != null) { if (line.contains("<!-- Results -->") && !("".equals(q) || q == null)) { SolrServer solr = new CommonsHttpSolrServer(solrUrl + BiblioSearch); int rows = 30; try { rows = Integer.parseInt(request.getParameter("rows")); } catch (Exception e) { } int start = 0; try { start = Integer.parseInt(request.getParameter("start")); } catch (Exception e) {} SolrQuery sq = new SolrQuery(); try { sq.setQuery(q.toLowerCase()); sq.setStart(start); sq.setRows(rows); sq.addSortField("date", SolrQuery.ORDER.asc); sq.addSortField("sort", SolrQuery.ORDER.asc); QueryRequest req = new QueryRequest(sq); req.setMethod(METHOD.POST); QueryResponse rs = req.process(solr); SolrDocumentList docs = rs.getResults(); out.println("<p>" + docs.getNumFound() + " hits on \"" + q.toString() + "\".</p>"); out.println("<table>"); String uq = q; try { uq = URLEncoder.encode(q, "UTF-8"); } catch (Exception e) { } for (SolrDocument doc : docs) { StringBuilder row = new StringBuilder("<tr class=\"result-record\"><td>"); row.append("<a href=\""); row.append("/biblio/"); row.append(((String) doc.getFieldValue("id"))); row.append("/?q="); row.append(uq); row.append("\">"); row.append(doc.getFieldValue("display")); row.append("</a>"); row.append("</td>"); row.append("</tr>"); out.print(row); } out.println("</table>"); if (docs.getNumFound() > rows) { out.println("<div id=\"pagination\">"); int pages = (int) Math.ceil((double) docs.getNumFound() / (double) rows); int p = 0; while (p < pages) { if ((p * rows) == start) { out.print("<div class=\"page current\">"); out.print((p + 1) + " "); out.print("</div>"); } else { StringBuilder plink = new StringBuilder(uq + "&start=" + p * rows + "&rows=" + rows); out.print("<div class=\"page\"><a href=\"/bibliosearch?q=" + plink + "\">" + (p + 1) + "</a></div>"); } p++; } out.println("</div>"); } } catch (SolrServerException e) { out.println("<p>Unable to execute query. Please try again.</p>"); throw new ServletException(e); } } else { out.println(line); } } } finally { out.close(); } }
diff --git a/src/com/redhat/ceylon/compiler/codegen/AbstractTransformer.java b/src/com/redhat/ceylon/compiler/codegen/AbstractTransformer.java index 72f23bb37..ccff77602 100755 --- a/src/com/redhat/ceylon/compiler/codegen/AbstractTransformer.java +++ b/src/com/redhat/ceylon/compiler/codegen/AbstractTransformer.java @@ -1,1094 +1,1094 @@ /* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * 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 distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.redhat.ceylon.compiler.codegen; import static com.sun.tools.javac.code.Flags.FINAL; import java.util.HashMap; import java.util.Map; import org.antlr.runtime.Token; import com.redhat.ceylon.compiler.loader.CeylonModelLoader; import com.redhat.ceylon.compiler.loader.ModelLoader.DeclarationType; import com.redhat.ceylon.compiler.loader.TypeFactory; import com.redhat.ceylon.compiler.tools.CeylonLog; import com.redhat.ceylon.compiler.typechecker.model.BottomType; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.IntersectionType; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.UnionType; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression; import com.redhat.ceylon.compiler.util.Util; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.TypeTags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.Factory; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCLiteral; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.LetExpr; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Name; import com.sun.tools.javac.util.Position; import com.sun.tools.javac.util.Position.LineMap; /** * Base class for all delegating transformers */ public abstract class AbstractTransformer implements Transformation { private Context context; private TreeMaker make; private Name.Table names; private Symtab syms; private CeylonModelLoader loader; private TypeFactory typeFact; protected Log log; public AbstractTransformer(Context context) { this.context = context; make = TreeMaker.instance(context); names = Name.Table.instance(context); syms = Symtab.instance(context); loader = CeylonModelLoader.instance(context); typeFact = TypeFactory.instance(context); log = CeylonLog.instance(context); } @Override public TreeMaker make() { return make; } private static JavaPositionsRetriever javaPositionsRetriever = null; public static void trackNodePositions(JavaPositionsRetriever positionsRetriever) { javaPositionsRetriever = positionsRetriever; } @Override public Factory at(Node node) { if (node == null) { make.at(Position.NOPOS); } else { Token token = node.getToken(); if (token != null) { int tokenStartPosition = getMap().getStartPosition(token.getLine()) + token.getCharPositionInLine(); make().at(tokenStartPosition); if (javaPositionsRetriever != null) { javaPositionsRetriever.addCeylonNode(tokenStartPosition, node); } } } return make(); } @Override public Symtab syms() { return syms; } @Override public Name.Table names() { return names; } @Override public CeylonModelLoader loader() { return loader; } @Override public TypeFactory typeFact() { return typeFact; } public void setMap(LineMap map) { gen().setMap(map); } protected LineMap getMap() { return gen().getMap(); } @Override public CeylonTransformer gen() { return CeylonTransformer.getInstance(context); } @Override public ExpressionTransformer expressionGen() { return ExpressionTransformer.getInstance(context); } @Override public StatementTransformer statementGen() { return StatementTransformer.getInstance(context); } @Override public ClassTransformer classGen() { return ClassTransformer.getInstance(context); } protected JCExpression makeIdent(String nameAsString) { return makeIdent(nameAsString.split("\\.")); } protected JCExpression makeIdent(Iterable<String> components) { JCExpression type = null; for (String component : components) { if (type == null) type = make().Ident(names().fromString(component)); else type = makeSelect(type, component); } return type; } protected JCExpression makeIdent(String... components) { JCExpression type = null; for (String component : components) { if (type == null) type = make().Ident(names().fromString(component)); else type = makeSelect(type, component); } return type; } protected JCExpression makeFQIdent(String... components) { JCExpression type = make().Ident(names.empty); for (String component : components) { if (type == null) type = make().Ident(names().fromString(component)); else type = makeSelect(type, component); } return type; } protected JCExpression makeIdent(Type type) { return make().QualIdent(type.tsym); } protected JCLiteral makeNull() { return make().Literal(TypeTags.BOT, null); } protected JCExpression makeInteger(int i) { return make().Literal(Integer.valueOf(i)); } protected JCExpression makeLong(long i) { return make().Literal(Long.valueOf(i)); } protected JCExpression makeBoolean(boolean b) { JCExpression expr; if (b) { expr = make().Literal(TypeTags.BOOLEAN, Integer.valueOf(1)); } else { expr = make().Literal(TypeTags.BOOLEAN, Integer.valueOf(0)); } return expr; } protected JCFieldAccess makeSelect(JCExpression s1, String s2) { return make().Select(s1, names().fromString(s2)); } protected JCExpression makeSelect(JCExpression s1, String... rest) { JCExpression result = s1; for (String s : rest) { result = makeSelect(result, s); } return result; } protected JCFieldAccess makeSelect(String s1, String s2) { return makeSelect(make().Ident(names().fromString(s1)), s2); } protected JCFieldAccess makeSelect(String s1, String s2, String... rest) { return makeSelect(makeSelect(s1, s2), rest); } protected JCFieldAccess makeSelect(JCFieldAccess s1, String[] rest) { JCFieldAccess acc = s1; for (String s : rest) acc = makeSelect(acc, s); return acc; } // Creates a "foo foo = new foo();" protected JCTree.JCVariableDecl makeLocalIdentityInstance(String varName, boolean isShared) { JCTree.JCIdent name = make().Ident(names().fromString(varName)); JCExpression initValue = makeNewClass(varName); List<JCAnnotation> annots = List.<JCAnnotation>nil(); int modifiers = isShared ? 0 : FINAL; JCTree.JCVariableDecl var = make().VarDef( make().Modifiers(modifiers, annots), names().fromString(varName), name, initValue); return var; } // Creates a "new foo();" protected JCTree.JCNewClass makeNewClass(String className) { return makeNewClass(className, List.<JCTree.JCExpression>nil()); } // Creates a "new foo(arg1, arg2, ...);" protected JCTree.JCNewClass makeNewClass(String className, List<JCTree.JCExpression> args) { JCTree.JCIdent name = make().Ident(names().fromString(className)); return makeNewClass(name, args); } // Creates a "new foo(arg1, arg2, ...);" protected JCTree.JCNewClass makeNewClass(JCExpression clazz, List<JCTree.JCExpression> args) { return make().NewClass(null, null, clazz, args, null); } // Creates a "( let var1=expr1,var2=expr2,...,varN=exprN in varN; )" // or a "( let var1=expr1,var2=expr2,...,varN=exprN,exprO in exprO; )" protected JCExpression makeLetExpr(JCExpression... args) { return makeLetExpr(tempName(), null, args); } // Creates a "( let var1=expr1,var2=expr2,...,varN=exprN in statements; varN; )" // or a "( let var1=expr1,var2=expr2,...,varN=exprN,exprO in statements; exprO; )" protected JCExpression makeLetExpr(String varBaseName, List<JCStatement> statements, JCExpression... args) { Name varName = null; List<JCVariableDecl> decls = List.nil(); int i; for (i = 0; (i + 1) < args.length; i += 2) { JCExpression typeExpr = args[i]; JCExpression valueExpr = args[i+1]; varName = names().fromString(varBaseName + "$" + i); JCVariableDecl varDecl = make().VarDef(make().Modifiers(0), varName, typeExpr, valueExpr); decls = decls.append(varDecl); } JCExpression result; if (i == args.length) { result = make().Ident(varName); } else { result = args[i]; } if (statements != null) { return make().LetExpr(decls, statements, result); } else { return make().LetExpr(decls, result); } } /* * Methods for making unique temporary and alias names */ static class UniqueId { private long id = 0; private long nextId() { return id++; } } private long nextUniqueId() { UniqueId id = context.get(UniqueId.class); if (id == null) { id = new UniqueId(); context.put(UniqueId.class, id); } return id.nextId(); } protected String tempName() { String result = "$ceylontmp" + nextUniqueId(); return result; } protected String tempName(String prefix) { String result = "$ceylontmp" + prefix + nextUniqueId(); return result; } protected String aliasName(String name) { String result = "$" + name + "$" + nextUniqueId(); return result; } /* * Type handling */ protected boolean isBooleanTrue(Declaration decl) { return decl == loader().getDeclaration("ceylon.language.$true", DeclarationType.VALUE); } protected boolean isBooleanFalse(Declaration decl) { return decl == loader().getDeclaration("ceylon.language.$false", DeclarationType.VALUE); } // A type is optional when it is a union of Nothing|Type... protected boolean isOptional(ProducedType type) { return typeFact().isOptionalType(type); } protected boolean isNothing(ProducedType type) { return typeFact.getNothingDeclaration().getType().isExactly(type); } protected ProducedType simplifyType(ProducedType type) { if (isOptional(type)) { // For an optional type T?: // - The Ceylon type T? results in the Java type T // Nasty cast because we just so happen to know that nothingType is a Class type = typeFact().getDefiniteType(type); } TypeDeclaration tdecl = type.getDeclaration(); if (tdecl instanceof UnionType && tdecl.getCaseTypes().size() == 1) { // Special case when the Union contains only a single CaseType // FIXME This is not correct! We might lose information about type arguments! type = tdecl.getCaseTypes().get(0); } else if (tdecl instanceof IntersectionType && tdecl.getSatisfiedTypes().size() == 1) { // Special case when the Intersection contains only a single SatisfiedType // FIXME This is not correct! We might lose information about type arguments! type = tdecl.getSatisfiedTypes().get(0); } return type; } protected ProducedType actualType(Tree.TypedDeclaration decl) { return decl.getType().getTypeModel(); } protected ProducedType toPType(com.sun.tools.javac.code.Type t) { return loader().getType(t.tsym.getQualifiedName().toString(), null); } protected boolean sameType(Type t1, ProducedType t2) { return toPType(t1).isExactly(t2); } // Determines if a type will be erased to java.lang.Object once converted to Java protected boolean willEraseToObject(ProducedType type) { type = simplifyType(type); return (sameType(syms().ceylonVoidType, type) || sameType(syms().ceylonObjectType, type) || sameType(syms().ceylonNothingType, type) || sameType(syms().ceylonEqualityType, type) || sameType(syms().ceylonIdentifiableObjectType, type) || type.getDeclaration() instanceof BottomType || typeFact().isUnion(type)|| typeFact().isIntersection(type)); } protected boolean willEraseToException(ProducedType type) { type = simplifyType(type); return (sameType(syms().ceylonExceptionType, type)); } protected boolean isCeylonString(ProducedType type) { return (sameType(syms().ceylonStringType, type)); } protected boolean isCeylonBoolean(ProducedType type) { return (sameType(syms().ceylonBooleanType, type)); } protected boolean isCeylonNatural(ProducedType type) { return (sameType(syms().ceylonNaturalType, type)); } protected boolean isCeylonInteger(ProducedType type) { return (sameType(syms().ceylonIntegerType, type)); } protected boolean isCeylonFloat(ProducedType type) { return (sameType(syms().ceylonFloatType, type)); } protected boolean isCeylonCharacter(ProducedType type) { return (sameType(syms().ceylonCharacterType, type)); } protected boolean isCeylonBasicType(ProducedType type) { return (isCeylonString(type) || isCeylonBoolean(type) || isCeylonNatural(type) || isCeylonInteger(type) || isCeylonFloat(type) || isCeylonCharacter(type)); } /* * Java Type creation */ static final int SATISFIES = 1 << 0; static final int EXTENDS = 1 << 1; static final int TYPE_ARGUMENT = 1 << 2; static final int NO_PRIMITIVES = 1 << 2; // Yes, same as TYPE_ARGUMENT static final int WANT_RAW_TYPE = 1 << 3; static final int CATCH = 1 << 4; static final int SMALL_TYPE = 1 << 5; static final int CLASS_NEW = 1 << 6; protected JCExpression makeJavaType(TypedDeclaration typeDecl) { boolean isGenericsType = isGenericsImplementation(typeDecl); return makeJavaType(typeDecl.getType(), isGenericsType ? AbstractTransformer.TYPE_ARGUMENT : 0); } protected JCExpression makeJavaType(ProducedType producedType) { return makeJavaType(producedType, 0); } protected JCExpression makeJavaType(ProducedType type, int flags) { if(type == null) return make().Erroneous(); // ERASURE if (willEraseToObject(type)) { // For an erased type: // - Any of the Ceylon types Void, Object, Nothing, Equality, // IdentifiableObject, and Bottom result in the Java type Object // For any other union type U|V (U nor V is Optional): // - The Ceylon type U|V results in the Java type Object ProducedType iterType = typeFact().getNonemptyIterableType(typeFact().getDefiniteType(type)); if (iterType != null) { // We special case the erasure of X[] and X[]? type = iterType; } else { if ((flags & SATISFIES) != 0) { return null; } else { return make().Type(syms().objectType); } } } else if (willEraseToException(type)) { if ((flags & CLASS_NEW) != 0 || (flags & EXTENDS) != 0) { return make().Type(syms().ceylonExceptionType); } else if ((flags & CATCH) != 0) { return make().Type(syms().exceptionType); } else { return make().Type(syms().throwableType); } } else if ((flags & (SATISFIES | EXTENDS | TYPE_ARGUMENT | CLASS_NEW)) == 0 && !isOptional(type)) { if (isCeylonString(type)) { return make().Type(syms().stringType); } else if (isCeylonBoolean(type)) { return make().TypeIdent(TypeTags.BOOLEAN); } else if (isCeylonNatural(type) || isCeylonInteger(type)) { if ((flags & SMALL_TYPE) != 0) { return make().TypeIdent(TypeTags.INT); } else { return make().TypeIdent(TypeTags.LONG); } } else if (isCeylonFloat(type)) { if ((flags & SMALL_TYPE) != 0) { return make().TypeIdent(TypeTags.FLOAT); } else { return make().TypeIdent(TypeTags.DOUBLE); } } else if (isCeylonCharacter(type)) { return make().TypeIdent(TypeTags.INT); } } JCExpression jt; type = simplifyType(type); TypeDeclaration tdecl = type.getDeclaration(); java.util.List<ProducedType> tal = type.getTypeArgumentList(); if (((flags & WANT_RAW_TYPE) == 0) && tal != null && !tal.isEmpty()) { // GENERIC TYPES ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>(); int idx = 0; for (ProducedType ta : tal) { if (isOptional(ta)) { // For an optional type T?: // - The Ceylon type Foo<T?> results in the Java type Foo<T>. ta = typeFact().getDefiniteType(ta); } if (typeFact().isUnion(ta) || typeFact().isIntersection(ta)) { // For any other union type U|V (U nor V is Optional): // - The Ceylon type Foo<U|V> results in the raw Java type Foo. // For any other intersection type U|V: // - The Ceylon type Foo<U&V> results in the raw Java type Foo. // A bit ugly, but we need to escape from the loop and create a raw type, no generics typeArgs = null; break; } JCExpression jta; if (sameType(syms().ceylonVoidType, ta)) { // For the root type Void: if ((flags & (SATISFIES | EXTENDS)) != 0) { // - The Ceylon type Foo<Void> appearing in an extends or satisfies // clause results in the Java raw type Foo<Object> jta = make().Type(syms().objectType); } else { // - The Ceylon type Foo<Void> appearing anywhere else results in the Java type // - Foo<Object> if Foo<T> is invariant in T // - Foo<?> if Foo<T> is covariant in T, or // - Foo<Object> if Foo<T> is contravariant in T TypeParameter tp = tdecl.getTypeParameters().get(idx); if (tp.isContravariant()) { jta = make().Type(syms().objectType); } else if (tp.isCovariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta, flags)); } else { jta = make().Type(syms().objectType); } } } else if (ta.getDeclaration() instanceof BottomType) { // For the bottom type Bottom: if ((flags & (SATISFIES | EXTENDS)) != 0) { // - The Ceylon type Foo<Bottom> appearing in an extends or satisfies // clause results in the Java raw type Foo // A bit ugly, but we need to escape from the loop and create a raw type, no generics typeArgs = null; break; } else { // - The Ceylon type Foo<Bottom> appearing anywhere else results in the Java type // - raw Foo if Foo<T> is invariant in T, // - raw Foo if Foo<T> is covariant in T, or // - Foo<?> if Foo<T> is contravariant in T TypeParameter tp = tdecl.getTypeParameters().get(idx); if (tp.isContravariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta)); } else { // A bit ugly, but we need to escape from the loop and create a raw type, no generics typeArgs = null; break; } } } else { // For an ordinary class or interface type T: if ((flags & (SATISFIES | EXTENDS)) != 0) { // - The Ceylon type Foo<T> appearing in an extends or satisfies clause // results in the Java type Foo<T> - jta = makeJavaType(ta, (flags & (SATISFIES | EXTENDS))); + jta = makeJavaType(ta, TYPE_ARGUMENT); } else { // - The Ceylon type Foo<T> appearing anywhere else results in the Java type // - Foo<T> if Foo is invariant in T, // - Foo<? extends T> if Foo is covariant in T, or // - Foo<? super T> if Foo is contravariant in T TypeParameter tp = tdecl.getTypeParameters().get(idx); if (((flags & CLASS_NEW) == 0) && tp.isContravariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), makeJavaType(ta, TYPE_ARGUMENT)); } else if (((flags & CLASS_NEW) == 0) && tp.isCovariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), makeJavaType(ta, TYPE_ARGUMENT)); } else { jta = makeJavaType(ta, TYPE_ARGUMENT); } } } typeArgs.add(jta); idx++; } if (typeArgs != null && typeArgs.size() > 0) { jt = make().TypeApply(makeIdent(getDeclarationName(tdecl)), typeArgs.toList()); } else { jt = makeIdent(getDeclarationName(tdecl)); } } else { // For an ordinary class or interface type T: // - The Ceylon type T results in the Java type T if(tdecl instanceof TypeParameter) jt = makeIdent(tdecl.getName()); else jt = makeIdent(getDeclarationName(tdecl)); } return jt; } private String getDeclarationName(Declaration decl) { if (decl.getContainer() instanceof Method) { return decl.getName(); } else { return decl.getQualifiedNameString(); } } /* * Annotation generation */ List<JCAnnotation> makeAtOverride() { return List.<JCAnnotation> of(make().Annotation(makeIdent(syms().overrideType), List.<JCExpression> nil())); } // FIXME public static boolean disableModelAnnotations = false; public boolean checkCompilerAnnotations(Tree.Declaration decl){ boolean old = disableModelAnnotations; if(Util.hasCompilerAnnotation(decl, "nomodel")) disableModelAnnotations = true; return old; } public void resetCompilerAnnotations(boolean value){ disableModelAnnotations = value; } private List<JCAnnotation> makeModelAnnotation(Type annotationType, List<JCExpression> annotationArgs) { if (disableModelAnnotations) return List.nil(); return List.of(make().Annotation(makeIdent(annotationType), annotationArgs)); } private List<JCAnnotation> makeModelAnnotation(Type annotationType) { return makeModelAnnotation(annotationType, List.<JCExpression>nil()); } protected List<JCAnnotation> makeAtCeylon() { return makeModelAnnotation(syms().ceylonAtCeylonType); } protected List<JCAnnotation> makeAtModule(Module module) { String name = module.getNameAsString(); String version = module.getVersion(); java.util.List<Module> dependencies = module.getDependencies(); ListBuffer<JCExpression> imports = new ListBuffer<JCTree.JCExpression>(); for(Module dependency : dependencies){ JCExpression dependencyName = make().Assign(makeIdent("name"), make().Literal(dependency.getNameAsString())); JCExpression dependencyVersion = null; if(dependency.getVersion() != null) dependencyVersion = make().Assign(makeIdent("version"), make().Literal(dependency.getVersion())); List<JCExpression> spec; if(dependencyVersion != null) spec = List.<JCExpression>of(dependencyName, dependencyVersion); else spec = List.<JCExpression>of(dependencyName); JCAnnotation atImport = make().Annotation(makeIdent(syms().ceylonAtImportType), spec); imports.add(atImport); } JCExpression nameAttribute = make().Assign(makeIdent("name"), make().Literal(name)); JCExpression versionAttribute = make().Assign(makeIdent("version"), make().Literal(version)); JCExpression importAttribute = make().Assign(makeIdent("dependencies"), make().NewArray(null, null, imports.toList())); return makeModelAnnotation(syms().ceylonAtModuleType, List.<JCExpression>of(nameAttribute, versionAttribute, importAttribute)); } protected List<JCAnnotation> makeAtPackage(Package pkg) { String name = pkg.getNameAsString(); boolean shared = pkg.isShared(); JCExpression nameAttribute = make().Assign(makeIdent("name"), make().Literal(name)); JCExpression sharedAttribute = make().Assign(makeIdent("shared"), makeBoolean(shared)); return makeModelAnnotation(syms().ceylonAtPackageType, List.<JCExpression>of(nameAttribute, sharedAttribute)); } protected List<JCAnnotation> makeAtName(String name) { return makeModelAnnotation(syms().ceylonAtNameType, List.<JCExpression>of(make().Literal(name))); } protected List<JCAnnotation> makeAtType(String name) { return makeModelAnnotation(syms().ceylonAtTypeInfoType, List.<JCExpression>of(make().Literal(name))); } public JCAnnotation makeAtTypeParameter(String name, java.util.List<ProducedType> satisfiedTypes, boolean covariant, boolean contravariant) { JCExpression nameAttribute = make().Assign(makeIdent("value"), make().Literal(name)); // variance String variance = "NONE"; if(covariant) variance = "OUT"; else if(contravariant) variance = "IN"; JCExpression varianceAttribute = make().Assign(makeIdent("variance"), make().Select(makeIdent(syms().ceylonVarianceType), names().fromString(variance))); // upper bounds ListBuffer<JCExpression> upperBounds = new ListBuffer<JCTree.JCExpression>(); for(ProducedType satisfiedType : satisfiedTypes){ String type = serialiseTypeSignature(satisfiedType); upperBounds.append(make().Literal(type)); } JCExpression satisfiesAttribute = make().Assign(makeIdent("satisfies"), make().NewArray(null, null, upperBounds.toList())); // all done return make().Annotation(makeIdent(syms().ceylonAtTypeParameter), List.<JCExpression>of(nameAttribute, varianceAttribute, satisfiesAttribute)); } public List<JCAnnotation> makeAtTypeParameters(List<JCExpression> typeParameters) { JCExpression value = make().NewArray(null, null, typeParameters); return makeModelAnnotation(syms().ceylonAtTypeParameters, List.of(value)); } protected List<JCAnnotation> makeAtSequenced() { return makeModelAnnotation(syms().ceylonAtSequencedType); } protected List<JCAnnotation> makeAtAttribute() { return makeModelAnnotation(syms().ceylonAtAttributeType); } protected List<JCAnnotation> makeAtMethod() { return makeModelAnnotation(syms().ceylonAtMethodType); } protected List<JCAnnotation> makeAtObject() { return makeModelAnnotation(syms().ceylonAtObjectType); } protected List<JCAnnotation> makeAtIgnore() { return makeModelAnnotation(syms().ceylonAtIgnore); } protected boolean needsAnnotations(Declaration decl) { Declaration reqdecl = decl; if (reqdecl instanceof Parameter) { Parameter p = (Parameter)reqdecl; reqdecl = p.getDeclaration(); } return reqdecl.isToplevel() || (reqdecl.isClassOrInterfaceMember() && reqdecl.isShared()); } protected List<JCTree.JCAnnotation> makeJavaTypeAnnotations(TypedDeclaration decl) { if(decl.getType() == null) return List.nil(); return makeJavaTypeAnnotations(decl.getType(), needsAnnotations(decl)); } protected List<JCTree.JCAnnotation> makeJavaTypeAnnotations(ProducedType type, boolean required) { if (!required) return List.nil(); // Add the original type to the annotations return makeAtType(serialiseTypeSignature(type)); } protected String serialiseTypeSignature(ProducedType type){ if(isTypeParameter(type)) return type.getProducedTypeName(); return type.getProducedTypeQualifiedName(); } /* * Boxing */ public enum BoxingStrategy { UNBOXED, BOXED, INDIFFERENT; } protected JCExpression boxUnboxIfNecessary(JCExpression javaExpr, Tree.Term expr, ProducedType exprType, BoxingStrategy boxingStrategy) { boolean exprBoxed = !Util.isUnBoxed(expr); return boxUnboxIfNecessary(javaExpr, exprBoxed, exprType, boxingStrategy); } protected JCExpression boxUnboxIfNecessary(JCExpression javaExpr, boolean exprBoxed, ProducedType exprType, BoxingStrategy boxingStrategy) { if(boxingStrategy == BoxingStrategy.INDIFFERENT) return javaExpr; boolean targetBoxed = boxingStrategy == BoxingStrategy.BOXED; // only box if the two differ if(targetBoxed == exprBoxed) return javaExpr; if (targetBoxed) { // box javaExpr = boxType(javaExpr, exprType); } else { // unbox javaExpr = unboxType(javaExpr, exprType); } return javaExpr; } protected boolean isTypeParameter(ProducedType type) { return type.getDeclaration() instanceof TypeParameter; } protected JCExpression unboxType(JCExpression expr, ProducedType targetType) { if (isCeylonNatural(targetType)) { expr = unboxNatural(expr); } else if (isCeylonInteger(targetType)) { expr = unboxInteger(expr); } else if (isCeylonFloat(targetType)) { expr = unboxFloat(expr); } else if (isCeylonString(targetType)) { expr = unboxString(expr); } else if (isCeylonCharacter(targetType)) { expr = unboxCharacter(expr); } else if (isCeylonBoolean(targetType)) { expr = unboxBoolean(expr); } return expr; } protected JCExpression boxType(JCExpression expr, ProducedType exprType) { if (isCeylonNatural(exprType)) { expr = boxNatural(expr); } else if (isCeylonInteger(exprType)) { expr = boxInteger(expr); } else if (isCeylonFloat(exprType)) { expr = boxFloat(expr); } else if (isCeylonString(exprType)) { expr = boxString(expr); } else if (isCeylonCharacter(exprType)) { expr = boxCharacter(expr); } else if (isCeylonBoolean(exprType)) { expr = boxBoolean(expr); } return expr; } private JCTree.JCMethodInvocation boxNatural(JCExpression value) { return makeBoxType(value, syms().ceylonNaturalType); } private JCTree.JCMethodInvocation boxInteger(JCExpression value) { return makeBoxType(value, syms().ceylonIntegerType); } private JCTree.JCMethodInvocation boxFloat(JCExpression value) { return makeBoxType(value, syms().ceylonFloatType); } private JCTree.JCMethodInvocation boxString(JCExpression value) { return makeBoxType(value, syms().ceylonStringType); } private JCTree.JCMethodInvocation boxCharacter(JCExpression value) { return makeBoxType(value, syms().ceylonCharacterType); } private JCTree.JCMethodInvocation boxBoolean(JCExpression value) { return makeBoxType(value, syms().ceylonBooleanType); } private JCTree.JCMethodInvocation makeBoxType(JCExpression value, Type type) { return make().Apply(null, makeSelect(makeIdent(type), "instance"), List.<JCExpression>of(value)); } private JCTree.JCMethodInvocation unboxNatural(JCExpression value) { return makeUnboxType(value, "longValue"); } private JCTree.JCMethodInvocation unboxInteger(JCExpression value) { return makeUnboxType(value, "longValue"); } private JCTree.JCMethodInvocation unboxFloat(JCExpression value) { return makeUnboxType(value, "doubleValue"); } private JCTree.JCMethodInvocation unboxString(JCExpression value) { return makeUnboxType(value, "toString"); } private JCTree.JCMethodInvocation unboxCharacter(JCExpression value) { return makeUnboxType(value, "intValue"); } private JCTree.JCMethodInvocation unboxBoolean(JCExpression value) { return makeUnboxType(value, "booleanValue"); } private JCTree.JCMethodInvocation makeUnboxType(JCExpression value, String unboxMethodName) { return make().Apply(null, makeSelect(value, unboxMethodName), List.<JCExpression>nil()); } protected ProducedType determineExpressionType(Tree.Expression expr) { return determineExpressionType(expr.getTerm()); } protected ProducedType determineExpressionType(Tree.Term term) { ProducedType exprType = term.getTypeModel(); if (term instanceof Tree.InvocationExpression) { Declaration decl = ((Tree.InvocationExpression)term).getPrimary().getDeclaration().getRefinedDeclaration(); if (decl instanceof Method) { exprType = ((Method)decl).getType(); } } return exprType; } protected boolean isGenericsImplementation(TypedDeclaration decl) { return Util.getTopmostRefinedDeclaration(decl).getTypeDeclaration() instanceof TypeParameter; } /* * Sequences */ /** * Returns a JCExpression along the lines of * {@code new ArraySequence<seqElemType>(list...)} * @param list The elements in the sequence * @param seqElemType The sequence type parameter * @return a JCExpression * @see #makeSequenceRaw(java.util.List) */ protected JCExpression makeSequence(java.util.List<Expression> list, ProducedType seqElemType) { ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>(); for (Expression expr : list) { // no need for erasure casts here elems.append(expressionGen().transformExpression(expr)); } ProducedType seqType = typeFact().getDefaultSequenceType(seqElemType); JCExpression typeExpr = makeJavaType(seqType, CeylonTransformer.TYPE_ARGUMENT); return makeNewClass(typeExpr, elems.toList()); } /** * Returns a JCExpression along the lines of * {@code new ArraySequence(list...)} * @param list The elements in the sequence * @return a JCExpression * @see #makeSequence(java.util.List, ProducedType) */ protected JCExpression makeSequenceRaw(java.util.List<Expression> list) { ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>(); for (Expression expr : list) { // no need for erasure casts here elems.append(expressionGen().transformExpression(expr)); } ProducedType seqType = typeFact().getDefaultSequenceType(typeFact().getObjectDeclaration().getType()); JCExpression typeExpr = makeJavaType(seqType, CeylonTransformer.WANT_RAW_TYPE); return makeNewClass(typeExpr, elems.toList()); } protected JCExpression makeEmpty() { return make().Apply( List.<JCTree.JCExpression>nil(), makeSelect(makeIdent("ceylon", "language"), Util.quoteIfJavaKeyword("$empty"), Util.getGetterName("$empty")), List.<JCTree.JCExpression>nil()); } /* * Variable name substitution */ @SuppressWarnings("serial") protected static class VarMapper extends HashMap<String, String> { } private Map<String, String> getVarMapper() { VarMapper map = context.get(VarMapper.class); if (map == null) { map = new VarMapper(); context.put(VarMapper.class, map); } return map; } String addVariableSubst(String origVarName, String substVarName) { return getVarMapper().put(origVarName, substVarName); } void removeVariableSubst(String origVarName, String prevSubst) { if (prevSubst != null) { getVarMapper().put(origVarName, prevSubst); } else { getVarMapper().remove(origVarName); } } /* * Checks a global map of variable name substitutions and returns * either the original name if none was found or the substitute. */ String substitute(String varName) { if (getVarMapper().containsKey(varName)) { return getVarMapper().get(varName); } else { return varName; } } protected JCExpression makeTypeTest(JCExpression testExpr, ProducedType type) { JCExpression result = null; if (typeFact().isUnion(type)) { UnionType union = (UnionType)type.getDeclaration(); for (ProducedType pt : union.getCaseTypes()) { JCExpression partExpr = makeTypeTest(testExpr, pt); if (result == null) { result = partExpr; } else { result = make().Binary(JCTree.OR, result, partExpr); } } } else if (typeFact().isIntersection(type)) { IntersectionType union = (IntersectionType)type.getDeclaration(); for (ProducedType pt : union.getSatisfiedTypes()) { JCExpression partExpr = makeTypeTest(testExpr, pt); if (result == null) { result = partExpr; } else { result = make().Binary(JCTree.AND, result, partExpr); } } } else if (type.isExactly(typeFact().getNothingDeclaration().getType())){ // is Nothing => is null return make().Binary(JCTree.EQ, testExpr, makeNull()); } else if (type.isExactly(typeFact().getVoidDeclaration().getType())){ // everything is Void, it's the root of the hierarchy return makeIgnoredEvalAndReturn(testExpr, makeBoolean(true)); } else if (type.getDeclaration() instanceof BottomType){ // nothing is Bottom return makeIgnoredEvalAndReturn(testExpr, makeBoolean(false)); } else { JCExpression rawTypeExpr = makeJavaType(type, NO_PRIMITIVES | WANT_RAW_TYPE); result = make().TypeTest(testExpr, rawTypeExpr); } return result; } protected LetExpr makeIgnoredEvalAndReturn(JCExpression toEval, JCExpression toReturn){ // define a variable of type j.l.Object to hold the result of the evaluation JCVariableDecl def = make().VarDef(make().Modifiers(0), names.fromString(tempName()), make().Type(syms().objectType), toEval); // then ignore this result and return something else return make().LetExpr(def, toReturn); } }
true
true
protected JCExpression makeJavaType(ProducedType type, int flags) { if(type == null) return make().Erroneous(); // ERASURE if (willEraseToObject(type)) { // For an erased type: // - Any of the Ceylon types Void, Object, Nothing, Equality, // IdentifiableObject, and Bottom result in the Java type Object // For any other union type U|V (U nor V is Optional): // - The Ceylon type U|V results in the Java type Object ProducedType iterType = typeFact().getNonemptyIterableType(typeFact().getDefiniteType(type)); if (iterType != null) { // We special case the erasure of X[] and X[]? type = iterType; } else { if ((flags & SATISFIES) != 0) { return null; } else { return make().Type(syms().objectType); } } } else if (willEraseToException(type)) { if ((flags & CLASS_NEW) != 0 || (flags & EXTENDS) != 0) { return make().Type(syms().ceylonExceptionType); } else if ((flags & CATCH) != 0) { return make().Type(syms().exceptionType); } else { return make().Type(syms().throwableType); } } else if ((flags & (SATISFIES | EXTENDS | TYPE_ARGUMENT | CLASS_NEW)) == 0 && !isOptional(type)) { if (isCeylonString(type)) { return make().Type(syms().stringType); } else if (isCeylonBoolean(type)) { return make().TypeIdent(TypeTags.BOOLEAN); } else if (isCeylonNatural(type) || isCeylonInteger(type)) { if ((flags & SMALL_TYPE) != 0) { return make().TypeIdent(TypeTags.INT); } else { return make().TypeIdent(TypeTags.LONG); } } else if (isCeylonFloat(type)) { if ((flags & SMALL_TYPE) != 0) { return make().TypeIdent(TypeTags.FLOAT); } else { return make().TypeIdent(TypeTags.DOUBLE); } } else if (isCeylonCharacter(type)) { return make().TypeIdent(TypeTags.INT); } } JCExpression jt; type = simplifyType(type); TypeDeclaration tdecl = type.getDeclaration(); java.util.List<ProducedType> tal = type.getTypeArgumentList(); if (((flags & WANT_RAW_TYPE) == 0) && tal != null && !tal.isEmpty()) { // GENERIC TYPES ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>(); int idx = 0; for (ProducedType ta : tal) { if (isOptional(ta)) { // For an optional type T?: // - The Ceylon type Foo<T?> results in the Java type Foo<T>. ta = typeFact().getDefiniteType(ta); } if (typeFact().isUnion(ta) || typeFact().isIntersection(ta)) { // For any other union type U|V (U nor V is Optional): // - The Ceylon type Foo<U|V> results in the raw Java type Foo. // For any other intersection type U|V: // - The Ceylon type Foo<U&V> results in the raw Java type Foo. // A bit ugly, but we need to escape from the loop and create a raw type, no generics typeArgs = null; break; } JCExpression jta; if (sameType(syms().ceylonVoidType, ta)) { // For the root type Void: if ((flags & (SATISFIES | EXTENDS)) != 0) { // - The Ceylon type Foo<Void> appearing in an extends or satisfies // clause results in the Java raw type Foo<Object> jta = make().Type(syms().objectType); } else { // - The Ceylon type Foo<Void> appearing anywhere else results in the Java type // - Foo<Object> if Foo<T> is invariant in T // - Foo<?> if Foo<T> is covariant in T, or // - Foo<Object> if Foo<T> is contravariant in T TypeParameter tp = tdecl.getTypeParameters().get(idx); if (tp.isContravariant()) { jta = make().Type(syms().objectType); } else if (tp.isCovariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta, flags)); } else { jta = make().Type(syms().objectType); } } } else if (ta.getDeclaration() instanceof BottomType) { // For the bottom type Bottom: if ((flags & (SATISFIES | EXTENDS)) != 0) { // - The Ceylon type Foo<Bottom> appearing in an extends or satisfies // clause results in the Java raw type Foo // A bit ugly, but we need to escape from the loop and create a raw type, no generics typeArgs = null; break; } else { // - The Ceylon type Foo<Bottom> appearing anywhere else results in the Java type // - raw Foo if Foo<T> is invariant in T, // - raw Foo if Foo<T> is covariant in T, or // - Foo<?> if Foo<T> is contravariant in T TypeParameter tp = tdecl.getTypeParameters().get(idx); if (tp.isContravariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta)); } else { // A bit ugly, but we need to escape from the loop and create a raw type, no generics typeArgs = null; break; } } } else { // For an ordinary class or interface type T: if ((flags & (SATISFIES | EXTENDS)) != 0) { // - The Ceylon type Foo<T> appearing in an extends or satisfies clause // results in the Java type Foo<T> jta = makeJavaType(ta, (flags & (SATISFIES | EXTENDS))); } else { // - The Ceylon type Foo<T> appearing anywhere else results in the Java type // - Foo<T> if Foo is invariant in T, // - Foo<? extends T> if Foo is covariant in T, or // - Foo<? super T> if Foo is contravariant in T TypeParameter tp = tdecl.getTypeParameters().get(idx); if (((flags & CLASS_NEW) == 0) && tp.isContravariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), makeJavaType(ta, TYPE_ARGUMENT)); } else if (((flags & CLASS_NEW) == 0) && tp.isCovariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), makeJavaType(ta, TYPE_ARGUMENT)); } else { jta = makeJavaType(ta, TYPE_ARGUMENT); } } } typeArgs.add(jta); idx++; } if (typeArgs != null && typeArgs.size() > 0) { jt = make().TypeApply(makeIdent(getDeclarationName(tdecl)), typeArgs.toList()); } else { jt = makeIdent(getDeclarationName(tdecl)); } } else { // For an ordinary class or interface type T: // - The Ceylon type T results in the Java type T if(tdecl instanceof TypeParameter) jt = makeIdent(tdecl.getName()); else jt = makeIdent(getDeclarationName(tdecl)); } return jt; }
protected JCExpression makeJavaType(ProducedType type, int flags) { if(type == null) return make().Erroneous(); // ERASURE if (willEraseToObject(type)) { // For an erased type: // - Any of the Ceylon types Void, Object, Nothing, Equality, // IdentifiableObject, and Bottom result in the Java type Object // For any other union type U|V (U nor V is Optional): // - The Ceylon type U|V results in the Java type Object ProducedType iterType = typeFact().getNonemptyIterableType(typeFact().getDefiniteType(type)); if (iterType != null) { // We special case the erasure of X[] and X[]? type = iterType; } else { if ((flags & SATISFIES) != 0) { return null; } else { return make().Type(syms().objectType); } } } else if (willEraseToException(type)) { if ((flags & CLASS_NEW) != 0 || (flags & EXTENDS) != 0) { return make().Type(syms().ceylonExceptionType); } else if ((flags & CATCH) != 0) { return make().Type(syms().exceptionType); } else { return make().Type(syms().throwableType); } } else if ((flags & (SATISFIES | EXTENDS | TYPE_ARGUMENT | CLASS_NEW)) == 0 && !isOptional(type)) { if (isCeylonString(type)) { return make().Type(syms().stringType); } else if (isCeylonBoolean(type)) { return make().TypeIdent(TypeTags.BOOLEAN); } else if (isCeylonNatural(type) || isCeylonInteger(type)) { if ((flags & SMALL_TYPE) != 0) { return make().TypeIdent(TypeTags.INT); } else { return make().TypeIdent(TypeTags.LONG); } } else if (isCeylonFloat(type)) { if ((flags & SMALL_TYPE) != 0) { return make().TypeIdent(TypeTags.FLOAT); } else { return make().TypeIdent(TypeTags.DOUBLE); } } else if (isCeylonCharacter(type)) { return make().TypeIdent(TypeTags.INT); } } JCExpression jt; type = simplifyType(type); TypeDeclaration tdecl = type.getDeclaration(); java.util.List<ProducedType> tal = type.getTypeArgumentList(); if (((flags & WANT_RAW_TYPE) == 0) && tal != null && !tal.isEmpty()) { // GENERIC TYPES ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>(); int idx = 0; for (ProducedType ta : tal) { if (isOptional(ta)) { // For an optional type T?: // - The Ceylon type Foo<T?> results in the Java type Foo<T>. ta = typeFact().getDefiniteType(ta); } if (typeFact().isUnion(ta) || typeFact().isIntersection(ta)) { // For any other union type U|V (U nor V is Optional): // - The Ceylon type Foo<U|V> results in the raw Java type Foo. // For any other intersection type U|V: // - The Ceylon type Foo<U&V> results in the raw Java type Foo. // A bit ugly, but we need to escape from the loop and create a raw type, no generics typeArgs = null; break; } JCExpression jta; if (sameType(syms().ceylonVoidType, ta)) { // For the root type Void: if ((flags & (SATISFIES | EXTENDS)) != 0) { // - The Ceylon type Foo<Void> appearing in an extends or satisfies // clause results in the Java raw type Foo<Object> jta = make().Type(syms().objectType); } else { // - The Ceylon type Foo<Void> appearing anywhere else results in the Java type // - Foo<Object> if Foo<T> is invariant in T // - Foo<?> if Foo<T> is covariant in T, or // - Foo<Object> if Foo<T> is contravariant in T TypeParameter tp = tdecl.getTypeParameters().get(idx); if (tp.isContravariant()) { jta = make().Type(syms().objectType); } else if (tp.isCovariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta, flags)); } else { jta = make().Type(syms().objectType); } } } else if (ta.getDeclaration() instanceof BottomType) { // For the bottom type Bottom: if ((flags & (SATISFIES | EXTENDS)) != 0) { // - The Ceylon type Foo<Bottom> appearing in an extends or satisfies // clause results in the Java raw type Foo // A bit ugly, but we need to escape from the loop and create a raw type, no generics typeArgs = null; break; } else { // - The Ceylon type Foo<Bottom> appearing anywhere else results in the Java type // - raw Foo if Foo<T> is invariant in T, // - raw Foo if Foo<T> is covariant in T, or // - Foo<?> if Foo<T> is contravariant in T TypeParameter tp = tdecl.getTypeParameters().get(idx); if (tp.isContravariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta)); } else { // A bit ugly, but we need to escape from the loop and create a raw type, no generics typeArgs = null; break; } } } else { // For an ordinary class or interface type T: if ((flags & (SATISFIES | EXTENDS)) != 0) { // - The Ceylon type Foo<T> appearing in an extends or satisfies clause // results in the Java type Foo<T> jta = makeJavaType(ta, TYPE_ARGUMENT); } else { // - The Ceylon type Foo<T> appearing anywhere else results in the Java type // - Foo<T> if Foo is invariant in T, // - Foo<? extends T> if Foo is covariant in T, or // - Foo<? super T> if Foo is contravariant in T TypeParameter tp = tdecl.getTypeParameters().get(idx); if (((flags & CLASS_NEW) == 0) && tp.isContravariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), makeJavaType(ta, TYPE_ARGUMENT)); } else if (((flags & CLASS_NEW) == 0) && tp.isCovariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), makeJavaType(ta, TYPE_ARGUMENT)); } else { jta = makeJavaType(ta, TYPE_ARGUMENT); } } } typeArgs.add(jta); idx++; } if (typeArgs != null && typeArgs.size() > 0) { jt = make().TypeApply(makeIdent(getDeclarationName(tdecl)), typeArgs.toList()); } else { jt = makeIdent(getDeclarationName(tdecl)); } } else { // For an ordinary class or interface type T: // - The Ceylon type T results in the Java type T if(tdecl instanceof TypeParameter) jt = makeIdent(tdecl.getName()); else jt = makeIdent(getDeclarationName(tdecl)); } return jt; }
diff --git a/hbc-core/src/main/java/com/twitter/hbc/core/processor/AbstractProcessor.java b/hbc-core/src/main/java/com/twitter/hbc/core/processor/AbstractProcessor.java index 27fb5ed..04030ee 100644 --- a/hbc-core/src/main/java/com/twitter/hbc/core/processor/AbstractProcessor.java +++ b/hbc-core/src/main/java/com/twitter/hbc/core/processor/AbstractProcessor.java @@ -1,55 +1,53 @@ /** * Copyright 2013 Twitter, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.twitter.hbc.core.processor; import javax.annotation.Nullable; import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; /** * An abstract class for processing the stream and putting it onto the blockingQueue. * This class should probably not be extended externally, unless you want to process messages * yourself. */ public abstract class AbstractProcessor<T> implements HosebirdMessageProcessor { public static final long DEFAULT_OFFER_TIMEOUT_MILLIS = 500; protected final BlockingQueue<T> queue; protected final long offerTimeoutMillis; public AbstractProcessor(BlockingQueue<T> queue) { this(queue, DEFAULT_OFFER_TIMEOUT_MILLIS); } public AbstractProcessor(BlockingQueue<T> queue, long offerTimeoutMillis) { this.queue = queue; this.offerTimeoutMillis = offerTimeoutMillis; } @Override public boolean process() throws IOException, InterruptedException { T msg = processNextMessage(); - if (msg != null) { - return queue.offer(msg, offerTimeoutMillis, TimeUnit.MILLISECONDS); - } else { - // if its null, just try again - return process(); + while (msg == null) { + msg = processNextMessage(); } + return queue.offer(msg, offerTimeoutMillis, TimeUnit.MILLISECONDS); } @Nullable protected abstract T processNextMessage() throws IOException; }
false
true
public boolean process() throws IOException, InterruptedException { T msg = processNextMessage(); if (msg != null) { return queue.offer(msg, offerTimeoutMillis, TimeUnit.MILLISECONDS); } else { // if its null, just try again return process(); } }
public boolean process() throws IOException, InterruptedException { T msg = processNextMessage(); while (msg == null) { msg = processNextMessage(); } return queue.offer(msg, offerTimeoutMillis, TimeUnit.MILLISECONDS); }
diff --git a/src/main/java/org/apache/tika/sax/xpath/XPathParser.java b/src/main/java/org/apache/tika/sax/xpath/XPathParser.java index 5a0671de0..bb1667e26 100644 --- a/src/main/java/org/apache/tika/sax/xpath/XPathParser.java +++ b/src/main/java/org/apache/tika/sax/xpath/XPathParser.java @@ -1,114 +1,114 @@ /* * 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.tika.sax.xpath; import java.util.HashMap; import java.util.Map; /** * Parser for a very simple XPath subset. Only the following XPath constructs * (with namespaces) are supported: * <ul> * <li><code>.../text()</code></li> * <li><code>.../@*</code></li> * <li><code>.../@name</code></li> * <li><code>.../*...</code></li> * <li><code>.../name...</code></li> * <li><code>...//*...</code></li> * <li><code>...//name...</code></li> * </ul> */ public class XPathParser { private final Map<String, String> prefixes = new HashMap<String, String>(); public XPathParser() { } public XPathParser(String prefix, String namespace) { addPrefix(prefix, namespace); } public void addPrefix(String prefix, String namespace) { prefixes.put(prefix, namespace); } /** * Parses the given simple XPath expression to an evaluation state * initialized at the document node. Invalid expressions are not flagged * as errors, they just result in a failing evaluation state. * * @param xpath simple XPath expression * @return XPath evaluation state */ public Matcher parse(String xpath) { if (xpath.equals("/text()")) { return TextMatcher.INSTANCE; } else if (xpath.equals("/node()")) { return NodeMatcher.INSTANCE; } else if (xpath.equals("/descendant:node()")) { return new CompositeMatcher( - NodeMatcher.INSTANCE, + TextMatcher.INSTANCE, new ChildMatcher(new SubtreeMatcher(NodeMatcher.INSTANCE))); } else if (xpath.equals("/@*")) { return AttributeMatcher.INSTANCE; } else if (xpath.length() == 0) { return ElementMatcher.INSTANCE; } else if (xpath.startsWith("/@")) { String name = xpath.substring(2); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedAttributeMatcher(prefixes.get(prefix), name); } else { return Matcher.FAIL; } } else if (xpath.startsWith("/*")) { return new ChildMatcher(parse(xpath.substring(2))); } else if (xpath.startsWith("///")) { return Matcher.FAIL; } else if (xpath.startsWith("//")) { return new SubtreeMatcher(parse(xpath.substring(1))); } else if (xpath.startsWith("/")) { int slash = xpath.indexOf('/', 1); if (slash == -1) { slash = xpath.length(); } String name = xpath.substring(1, slash); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedElementMatcher( prefixes.get(prefix), name, parse(xpath.substring(slash))); } else { return Matcher.FAIL; } } else { return Matcher.FAIL; } } }
true
true
public Matcher parse(String xpath) { if (xpath.equals("/text()")) { return TextMatcher.INSTANCE; } else if (xpath.equals("/node()")) { return NodeMatcher.INSTANCE; } else if (xpath.equals("/descendant:node()")) { return new CompositeMatcher( NodeMatcher.INSTANCE, new ChildMatcher(new SubtreeMatcher(NodeMatcher.INSTANCE))); } else if (xpath.equals("/@*")) { return AttributeMatcher.INSTANCE; } else if (xpath.length() == 0) { return ElementMatcher.INSTANCE; } else if (xpath.startsWith("/@")) { String name = xpath.substring(2); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedAttributeMatcher(prefixes.get(prefix), name); } else { return Matcher.FAIL; } } else if (xpath.startsWith("/*")) { return new ChildMatcher(parse(xpath.substring(2))); } else if (xpath.startsWith("///")) { return Matcher.FAIL; } else if (xpath.startsWith("//")) { return new SubtreeMatcher(parse(xpath.substring(1))); } else if (xpath.startsWith("/")) { int slash = xpath.indexOf('/', 1); if (slash == -1) { slash = xpath.length(); } String name = xpath.substring(1, slash); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedElementMatcher( prefixes.get(prefix), name, parse(xpath.substring(slash))); } else { return Matcher.FAIL; } } else { return Matcher.FAIL; } }
public Matcher parse(String xpath) { if (xpath.equals("/text()")) { return TextMatcher.INSTANCE; } else if (xpath.equals("/node()")) { return NodeMatcher.INSTANCE; } else if (xpath.equals("/descendant:node()")) { return new CompositeMatcher( TextMatcher.INSTANCE, new ChildMatcher(new SubtreeMatcher(NodeMatcher.INSTANCE))); } else if (xpath.equals("/@*")) { return AttributeMatcher.INSTANCE; } else if (xpath.length() == 0) { return ElementMatcher.INSTANCE; } else if (xpath.startsWith("/@")) { String name = xpath.substring(2); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedAttributeMatcher(prefixes.get(prefix), name); } else { return Matcher.FAIL; } } else if (xpath.startsWith("/*")) { return new ChildMatcher(parse(xpath.substring(2))); } else if (xpath.startsWith("///")) { return Matcher.FAIL; } else if (xpath.startsWith("//")) { return new SubtreeMatcher(parse(xpath.substring(1))); } else if (xpath.startsWith("/")) { int slash = xpath.indexOf('/', 1); if (slash == -1) { slash = xpath.length(); } String name = xpath.substring(1, slash); String prefix = null; int colon = name.indexOf(':'); if (colon != -1) { prefix = name.substring(0, colon); name = name.substring(colon + 1); } if (prefixes.containsKey(prefix)) { return new NamedElementMatcher( prefixes.get(prefix), name, parse(xpath.substring(slash))); } else { return Matcher.FAIL; } } else { return Matcher.FAIL; } }
diff --git a/src/main/java/org/jenkinsci/plugins/IPMessengerNotifier.java b/src/main/java/org/jenkinsci/plugins/IPMessengerNotifier.java index 3b4406b..8072707 100644 --- a/src/main/java/org/jenkinsci/plugins/IPMessengerNotifier.java +++ b/src/main/java/org/jenkinsci/plugins/IPMessengerNotifier.java @@ -1,194 +1,194 @@ package org.jenkinsci.plugins; import hudson.Extension; import hudson.Launcher; import hudson.model.BuildListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import java.io.IOException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import net.sf.json.JSONObject; import org.jenkinsci.plugins.tokenmacro.MacroEvaluationException; import org.jenkinsci.plugins.tokenmacro.TokenMacro; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; public class IPMessengerNotifier extends Notifier { private String fromHost = ""; private final String charset = "MS932"; private final int port = 2425; private final String messageTemplate; private final String recipientHosts; @DataBoundConstructor public IPMessengerNotifier(String messageTemplate, String recipientHosts) { this.messageTemplate = messageTemplate; this.recipientHosts = recipientHosts; } public String getRecipientHosts() { return recipientHosts; } public String getMessageTemplate() { return messageTemplate; } public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { PrintStream logger = listener.getLogger(); - String message = "Build " + build.getResult().toString() + "\n"; + String message = "BUILD " + build.getResult().toString() + "\n"; try { fromHost = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { logger.println(this.getClass().getSimpleName() + ": Can't get hostname of jenkins."); } try { message += TokenMacro.expandAll(build, listener, messageTemplate); sendNooperation(logger); Thread.sleep(1500); for (String toHost : createRecipientHostList(recipientHosts)) { sendMsg(message, toHost, logger); } } catch (MacroEvaluationException e) { logger.println(this.getClass().getSimpleName() + "IPMessengerNotifier: MacroEvaluationException happened. " + "Is message template correct ?"); } catch (IOException e) { logger.println(this.getClass().getSimpleName() + "IPMessengerNotifier: IOException happened. "); } catch (InterruptedException e) { logger.println(this.getClass().getSimpleName() + "IPMessengerNotifier: InterruptedException happened. "); } // always return true; return true; } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> { private String jenkinsUserName; @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } @Override public String getDisplayName() { return "Notify by IPMessenger"; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { jenkinsUserName = formData.getString("jenkinsUserName"); save(); return super.configure(req, formData); } public String getJenkinsUserName() { return jenkinsUserName; } } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } private ArrayList<String> createRecipientHostList(String recipientHosts) { ArrayList<String> result = new ArrayList<String>(); for (String s : recipientHosts.split("\n")) { result.add(s.replaceAll("\\s+", "")); } return result; } private void sendMsg(String message, String toHost, PrintStream logger) { message = createTeregram(0x00000020, message); sendPacket(message, toHost, logger); } private void sendNooperation(PrintStream logger) { String message = createTeregram(0x00000000, null); sendPacket(message, "255.255.255.255", logger); } private String createTeregram(int command, String message) { String userName = getDescriptor().getJenkinsUserName(); if (userName == null || "".equals(userName)) { userName = "jenkins-ci"; } StringBuffer sb = new StringBuffer(); sb.append(1);// ipmessenger protocol version sb.append(":"); // packet serial number sb.append((int) Math.floor(Math.random() * Integer.MAX_VALUE)); sb.append(":"); sb.append(userName);// sender username sb.append(":"); sb.append(fromHost);// sender hostname sb.append(":"); sb.append(command);// command number sb.append(":"); sb.append(message); return sb.toString(); } private void sendPacket(String message, String toHost, PrintStream logger) { byte[] byteMsg = null; DatagramPacket packet = null; DatagramSocket socket = null; try { byteMsg = message.getBytes(charset); socket = new DatagramSocket(port); packet = new DatagramPacket(byteMsg, byteMsg.length, InetAddress.getByName(toHost), port); socket.send(packet); } catch (UnsupportedEncodingException e) { logger.println(this.getClass().getSimpleName() + ": UnsupportedEncodingException happened. You should change message template."); } catch (SocketException e) { logger.println(this.getClass().getSimpleName() + ": SocketException happened"); } catch (UnknownHostException e) { logger.println(this.getClass().getSimpleName() + ": UnknownHostException: " + toHost); } catch (IOException e) { logger.println(this.getClass().getSimpleName() + ": IOException happened"); } finally { if (socket != null) { socket.close(); } } } }
true
true
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { PrintStream logger = listener.getLogger(); String message = "Build " + build.getResult().toString() + "\n"; try { fromHost = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { logger.println(this.getClass().getSimpleName() + ": Can't get hostname of jenkins."); } try { message += TokenMacro.expandAll(build, listener, messageTemplate); sendNooperation(logger); Thread.sleep(1500); for (String toHost : createRecipientHostList(recipientHosts)) { sendMsg(message, toHost, logger); } } catch (MacroEvaluationException e) { logger.println(this.getClass().getSimpleName() + "IPMessengerNotifier: MacroEvaluationException happened. " + "Is message template correct ?"); } catch (IOException e) { logger.println(this.getClass().getSimpleName() + "IPMessengerNotifier: IOException happened. "); } catch (InterruptedException e) { logger.println(this.getClass().getSimpleName() + "IPMessengerNotifier: InterruptedException happened. "); } // always return true; return true; }
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { PrintStream logger = listener.getLogger(); String message = "BUILD " + build.getResult().toString() + "\n"; try { fromHost = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { logger.println(this.getClass().getSimpleName() + ": Can't get hostname of jenkins."); } try { message += TokenMacro.expandAll(build, listener, messageTemplate); sendNooperation(logger); Thread.sleep(1500); for (String toHost : createRecipientHostList(recipientHosts)) { sendMsg(message, toHost, logger); } } catch (MacroEvaluationException e) { logger.println(this.getClass().getSimpleName() + "IPMessengerNotifier: MacroEvaluationException happened. " + "Is message template correct ?"); } catch (IOException e) { logger.println(this.getClass().getSimpleName() + "IPMessengerNotifier: IOException happened. "); } catch (InterruptedException e) { logger.println(this.getClass().getSimpleName() + "IPMessengerNotifier: InterruptedException happened. "); } // always return true; return true; }
diff --git a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java index 3dcadb848..ca8d87df8 100644 --- a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java +++ b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java @@ -1,425 +1,426 @@ /* * Copyright (c) 2002-2009 Gargoyle Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gargoylesoftware.htmlunit.javascript; import static org.junit.Assert.fail; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.lang.ClassUtils; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import com.gargoylesoftware.htmlunit.BrowserRunner; import com.gargoylesoftware.htmlunit.CollectingAlertHandler; import com.gargoylesoftware.htmlunit.MockWebConnection; import com.gargoylesoftware.htmlunit.ScriptException; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.WebTestCase; import com.gargoylesoftware.htmlunit.BrowserRunner.Alerts; import com.gargoylesoftware.htmlunit.BrowserRunner.Browser; import com.gargoylesoftware.htmlunit.BrowserRunner.Browsers; import com.gargoylesoftware.htmlunit.BrowserRunner.NotYetImplemented; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration; /** * Tests for {@link SimpleScriptable}. * * @version $Revision$ * @author <a href="mailto:[email protected]">Mike Bowler</a> * @author <a href="mailto:[email protected]">Barnaby Court</a> * @author David K. Taylor * @author <a href="mailto:[email protected]">Ben Curren</a> * @author Marc Guillemot * @author Chris Erskine * @author Ahmed Ashour * @author Sudhan Moghe * @author <a href="mailto:[email protected]">Mike Dirolf</a> */ @RunWith(BrowserRunner.class) public class SimpleScriptableTest extends WebTestCase { /** * @throws Exception if the test fails */ @Test public void callInheritedFunction() throws Exception { final WebClient client = getWebClient(); final MockWebConnection webConnection = new MockWebConnection(); final String content = "<html><head><title>foo</title><script>\n" + "function doTest() {\n" + " document.form1.textfield1.focus();\n" + " alert('past focus');\n" + "}\n" + "</script></head><body onload='doTest()'>\n" + "<p>hello world</p>\n" + "<form name='form1'>\n" + " <input type='text' name='textfield1' id='textfield1' value='foo'/>\n" + "</form>\n" + "</body></html>"; webConnection.setDefaultResponse(content); client.setWebConnection(webConnection); final List<String> expectedAlerts = Collections.singletonList("past focus"); createTestPageForRealBrowserIfNeeded(content, expectedAlerts); final List<String> collectedAlerts = new ArrayList<String>(); client.setAlertHandler(new CollectingAlertHandler(collectedAlerts)); final HtmlPage page = client.getPage(URL_GARGOYLE); assertEquals("foo", page.getTitleText()); Assert.assertEquals("focus not changed to textfield1", page.getFormByName("form1").getInputByName("textfield1"), page.getFocusedElement()); assertEquals(expectedAlerts, collectedAlerts); } /** * Test. */ @Test @Browsers(Browser.NONE) public void htmlJavaScriptMapping_AllJavaScriptClassesArePresent() { final Map<Class < ? extends HtmlElement>, Class < ? extends SimpleScriptable>> map = JavaScriptConfiguration.getHtmlJavaScriptMapping(); final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host"; final Set<String> names = getFileNames(directoryName.replace('/', File.separatorChar)); // Now pull out those names that we know don't have HTML equivalents names.remove("ActiveXObject"); names.remove("ActiveXObjectImpl"); names.remove("BoxObject"); + names.remove("ClipboardData"); names.remove("ComputedCSSStyleDeclaration"); names.remove("CSSRule"); names.remove("CSSRuleList"); names.remove("CSSStyleDeclaration"); names.remove("CSSStyleRule"); names.remove("Document"); names.remove("DOMImplementation"); names.remove("DOMParser"); names.remove("Event"); names.remove("EventNode"); names.remove("EventHandler"); names.remove("EventListenersContainer"); names.remove("FormField"); names.remove("History"); names.remove("HTMLCollection"); names.remove("HTMLCollectionTags"); names.remove("HTMLDocument"); names.remove("HTMLOptionsCollection"); names.remove("JavaScriptBackgroundJob"); names.remove("Location"); names.remove("MimeType"); names.remove("MimeTypeArray"); names.remove("MouseEvent"); names.remove("Namespace"); names.remove("Navigator"); names.remove("Node"); names.remove("NodeFilter"); names.remove("Plugin"); names.remove("PluginArray"); names.remove("Popup"); names.remove("Range"); names.remove("RowContainer"); names.remove("Screen"); names.remove("ScoperFunctionObject"); names.remove("Selection"); names.remove("SimpleArray"); names.remove("Stylesheet"); names.remove("StyleSheetList"); names.remove("TextRange"); names.remove("TextRectangle"); names.remove("TreeWalker"); names.remove("UIEvent"); names.remove("Window"); names.remove("WindowProxy"); names.remove("XMLDocument"); names.remove("XMLDOMParseError"); names.remove("XMLHttpRequest"); names.remove("XMLSerializer"); names.remove("XPathNSResolver"); names.remove("XPathResult"); names.remove("XSLTProcessor"); names.remove("XSLTemplate"); names.remove("XMLAttr"); final Collection<String> hostClassNames = new ArrayList<String>(); for (final Class< ? extends SimpleScriptable> clazz : map.values()) { hostClassNames.add(ClassUtils.getShortClassName(clazz)); } assertEquals(new TreeSet<String>(names).toString(), new TreeSet<String>(hostClassNames).toString()); } private Set<String> getFileNames(final String directoryName) { File directory = new File("." + File.separatorChar + directoryName); if (!directory.exists()) { directory = new File("./src/main/java/".replace('/', File.separatorChar) + directoryName); } assertTrue("directory exists", directory.exists()); assertTrue("is a directory", directory.isDirectory()); final Set<String> collection = new HashSet<String>(); for (final String name : directory.list()) { if (name.endsWith(".java")) { collection.add(name.substring(0, name.length() - 5)); } } return collection; } /** * This test fails on IE and FF but not by HtmlUnit because according to Ecma standard, * attempts to set read only properties should be silently ignored. * Furthermore document.body = document.body will work on FF but not on IE * @throws Exception if the test fails */ @Test @NotYetImplemented public void setNonWritableProperty() throws Exception { final String content = "<html><head><title>foo</title></head><body onload='document.body=123456'>" + "</body></html>"; try { loadPage(getBrowserVersion(), content, null); fail("Exception should have been thrown"); } catch (final ScriptException e) { // it's ok } } /** * Works since Rhino 1.7. * @throws Exception if the test fails */ @Test @Alerts("[object Object]") public void arguments_toString() throws Exception { final String html = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " alert(arguments);\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * @throws Exception if the test fails */ @Test @Alerts("3") public void stringWithExclamationMark() throws Exception { final String html = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " var x = '<!>';\n" + " alert(x.length);\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * Test the host class names match the Firefox (w3c names). * @see <a * href="http://java.sun.com/j2se/1.5.0/docs/guide/plugin/dom/org/w3c/dom/html/package-summary.html">DOM API</a> * @throws Exception if the test fails */ @Test @Browsers(Browser.FF) @NotYetImplemented public void hostClassNames() throws Exception { testHostClassNames("HTMLAnchorElement"); } private void testHostClassNames(final String className) throws Exception { final String content = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " alert(" + className + ");\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; final String[] expectedAlerts = {'[' + className + ']'}; final List<String> collectedAlerts = new ArrayList<String>(); loadPage(getBrowserVersion(), content, collectedAlerts); assertEquals(expectedAlerts, collectedAlerts); } /** * Blocked by Rhino bug 419090 (https://bugzilla.mozilla.org/show_bug.cgi?id=419090). * @throws Exception if the test fails */ @Test @Alerts({ "x1", "x2", "x3", "x4", "x5" }) public void arrayedMap() throws Exception { final String html = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " var map = {};\n" + " map['x1'] = 'y1';\n" + " map['x2'] = 'y2';\n" + " map['x3'] = 'y3';\n" + " map['x4'] = 'y4';\n" + " map['x5'] = 'y5';\n" + " for (var i in map) {\n" + " alert(i);\n" + " }" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * @throws Exception if the test fails */ @Test @Browsers(Browser.FF) public void isParentOf() throws Exception { isParentOf("Node", "Element", true); isParentOf("Document", "XMLDocument", true); isParentOf("Node", "XPathResult", false); isParentOf("Element", "HTMLElement", true); isParentOf("HTMLElement", "HTMLHtmlElement", true); isParentOf("CSSStyleDeclaration", "ComputedCSSStyleDeclaration", true); //although Image != HTMLImageElement, they seem to be synonyms!!! isParentOf("Image", "HTMLImageElement", true); isParentOf("HTMLImageElement", "Image", true); } private void isParentOf(final String object1, final String object2, final boolean status) throws Exception { final String html = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " alert(isParentOf(" + object1 + ", " + object2 + "));\n" + " }\n" + " /**\n" + " * Returns true if o1 prototype is parent/grandparent of o2 prototype\n" + " */\n" + " function isParentOf(o1, o2) {\n" + " o1.prototype.myCustomFunction = function() {};\n" + " return o2.prototype.myCustomFunction != undefined;\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; final String[] expectedAlerts = {Boolean.toString(status)}; final List<String> collectedAlerts = new ArrayList<String>(); loadPage(getBrowserVersion(), html, collectedAlerts); assertEquals(expectedAlerts, collectedAlerts); } /** * This is related to HtmlUnitContextFactory.hasFeature(Context.FEATURE_PARENT_PROTO_PROPERTIES). * @throws Exception if the test fails */ @Test @Alerts(IE = "false", FF = "true") public void parentProtoFeature() throws Exception { final String html = "<html><head><title>First</title><script>\n" + "function test() {\n" + " alert(document.createElement('div').__proto__ != undefined);\n" + "}\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * Test for https://sourceforge.net/tracker/index.php?func=detail&aid=1933943&group_id=47038&atid=448266. * See also http://groups.google.com/group/mozilla.dev.tech.js-engine.rhino/browse_thread/thread/1f1c24f58f662c58. * @throws Exception if the test fails */ @Test @Alerts("1") public void passFunctionAsParameter() throws Exception { final String html = "<html><head><title>First</title><script>\n" + " function run(fun) {\n" + " fun('alert(1)');\n" + " }\n" + "\n" + " function test() {\n" + " run(eval);\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * Test JavaScript: 'new Date().getTimezoneOffset()' compared to java.text.SimpleDateFormat.format(). * * @throws Exception if the test fails */ @Test @Browsers(Browser.NONE) public void dateGetTimezoneOffset() throws Exception { final String content = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " var offset = Math.abs(new Date().getTimezoneOffset());\n" + " var timezone = '' + (offset/60);\n" + " if (timezone.length == 1)\n" + " timezone = '0' + timezone;\n" + " alert(timezone);\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; final String timeZone = new SimpleDateFormat("Z").format(Calendar.getInstance().getTime()); final String hour = timeZone.substring(1, 3); String strMinutes = timeZone.substring(3, 5); final int minutes = Integer.parseInt(strMinutes); final StringBuilder sb = new StringBuilder(); if (minutes != 0) { sb.append(hour.substring(1)); strMinutes = String.valueOf((double) minutes / 60); strMinutes = strMinutes.substring(1); sb.append(strMinutes); } else { sb.append(hour); } final String[] expectedAlerts = {sb.toString()}; final List<String> collectedAlerts = new ArrayList<String>(); createTestPageForRealBrowserIfNeeded(content, expectedAlerts); loadPage(content, collectedAlerts); assertEquals(expectedAlerts, collectedAlerts); } }
true
true
public void htmlJavaScriptMapping_AllJavaScriptClassesArePresent() { final Map<Class < ? extends HtmlElement>, Class < ? extends SimpleScriptable>> map = JavaScriptConfiguration.getHtmlJavaScriptMapping(); final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host"; final Set<String> names = getFileNames(directoryName.replace('/', File.separatorChar)); // Now pull out those names that we know don't have HTML equivalents names.remove("ActiveXObject"); names.remove("ActiveXObjectImpl"); names.remove("BoxObject"); names.remove("ComputedCSSStyleDeclaration"); names.remove("CSSRule"); names.remove("CSSRuleList"); names.remove("CSSStyleDeclaration"); names.remove("CSSStyleRule"); names.remove("Document"); names.remove("DOMImplementation"); names.remove("DOMParser"); names.remove("Event"); names.remove("EventNode"); names.remove("EventHandler"); names.remove("EventListenersContainer"); names.remove("FormField"); names.remove("History"); names.remove("HTMLCollection"); names.remove("HTMLCollectionTags"); names.remove("HTMLDocument"); names.remove("HTMLOptionsCollection"); names.remove("JavaScriptBackgroundJob"); names.remove("Location"); names.remove("MimeType"); names.remove("MimeTypeArray"); names.remove("MouseEvent"); names.remove("Namespace"); names.remove("Navigator"); names.remove("Node"); names.remove("NodeFilter"); names.remove("Plugin"); names.remove("PluginArray"); names.remove("Popup"); names.remove("Range"); names.remove("RowContainer"); names.remove("Screen"); names.remove("ScoperFunctionObject"); names.remove("Selection"); names.remove("SimpleArray"); names.remove("Stylesheet"); names.remove("StyleSheetList"); names.remove("TextRange"); names.remove("TextRectangle"); names.remove("TreeWalker"); names.remove("UIEvent"); names.remove("Window"); names.remove("WindowProxy"); names.remove("XMLDocument"); names.remove("XMLDOMParseError"); names.remove("XMLHttpRequest"); names.remove("XMLSerializer"); names.remove("XPathNSResolver"); names.remove("XPathResult"); names.remove("XSLTProcessor"); names.remove("XSLTemplate"); names.remove("XMLAttr"); final Collection<String> hostClassNames = new ArrayList<String>(); for (final Class< ? extends SimpleScriptable> clazz : map.values()) { hostClassNames.add(ClassUtils.getShortClassName(clazz)); } assertEquals(new TreeSet<String>(names).toString(), new TreeSet<String>(hostClassNames).toString()); }
public void htmlJavaScriptMapping_AllJavaScriptClassesArePresent() { final Map<Class < ? extends HtmlElement>, Class < ? extends SimpleScriptable>> map = JavaScriptConfiguration.getHtmlJavaScriptMapping(); final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host"; final Set<String> names = getFileNames(directoryName.replace('/', File.separatorChar)); // Now pull out those names that we know don't have HTML equivalents names.remove("ActiveXObject"); names.remove("ActiveXObjectImpl"); names.remove("BoxObject"); names.remove("ClipboardData"); names.remove("ComputedCSSStyleDeclaration"); names.remove("CSSRule"); names.remove("CSSRuleList"); names.remove("CSSStyleDeclaration"); names.remove("CSSStyleRule"); names.remove("Document"); names.remove("DOMImplementation"); names.remove("DOMParser"); names.remove("Event"); names.remove("EventNode"); names.remove("EventHandler"); names.remove("EventListenersContainer"); names.remove("FormField"); names.remove("History"); names.remove("HTMLCollection"); names.remove("HTMLCollectionTags"); names.remove("HTMLDocument"); names.remove("HTMLOptionsCollection"); names.remove("JavaScriptBackgroundJob"); names.remove("Location"); names.remove("MimeType"); names.remove("MimeTypeArray"); names.remove("MouseEvent"); names.remove("Namespace"); names.remove("Navigator"); names.remove("Node"); names.remove("NodeFilter"); names.remove("Plugin"); names.remove("PluginArray"); names.remove("Popup"); names.remove("Range"); names.remove("RowContainer"); names.remove("Screen"); names.remove("ScoperFunctionObject"); names.remove("Selection"); names.remove("SimpleArray"); names.remove("Stylesheet"); names.remove("StyleSheetList"); names.remove("TextRange"); names.remove("TextRectangle"); names.remove("TreeWalker"); names.remove("UIEvent"); names.remove("Window"); names.remove("WindowProxy"); names.remove("XMLDocument"); names.remove("XMLDOMParseError"); names.remove("XMLHttpRequest"); names.remove("XMLSerializer"); names.remove("XPathNSResolver"); names.remove("XPathResult"); names.remove("XSLTProcessor"); names.remove("XSLTemplate"); names.remove("XMLAttr"); final Collection<String> hostClassNames = new ArrayList<String>(); for (final Class< ? extends SimpleScriptable> clazz : map.values()) { hostClassNames.add(ClassUtils.getShortClassName(clazz)); } assertEquals(new TreeSet<String>(names).toString(), new TreeSet<String>(hostClassNames).toString()); }
diff --git a/NCore/src/main/java/fr/ribesg/bukkit/ncore/common/AsyncPermAccessor.java b/NCore/src/main/java/fr/ribesg/bukkit/ncore/common/AsyncPermAccessor.java index 2b06de87..81ee2b43 100644 --- a/NCore/src/main/java/fr/ribesg/bukkit/ncore/common/AsyncPermAccessor.java +++ b/NCore/src/main/java/fr/ribesg/bukkit/ncore/common/AsyncPermAccessor.java @@ -1,173 +1,175 @@ package fr.ribesg.bukkit.ncore.common; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitRunnable; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * This tool allow Asynchronous access to a Player's permission. * The {@link #init(org.bukkit.plugin.Plugin, int)} method should be * called by at least one Plugin synchronously before any sync or async * access. * <b> * Note: There is a maximum of {@link #updateDelay} seconds delay between * this tool's state and the reality. This tool should not be used for * critical checks. * </b> * * @author Ribesg */ public final class AsyncPermAccessor { // ########################### // // ## Public static methods ## // // ########################### // /** * Checks if a Player had a Permission on the last update. * * @param playerName the player's name * @param permissionNode the permission to check * * @return true if the provided Player had the provided Permission on * the last update, false otherwise */ public static boolean has(final String playerName, final String permissionNode) { checkState(); return instance._has(playerName, permissionNode); } /** * Checks if a Player was Op on the last update. * * @param playerName the player's name * * @return true if the provided Player was Op on the last update, * false otherwise */ public static boolean isOp(final String playerName) { checkState(); return instance._isOp(playerName); } /** * Create the unique instance. * <p/> * Should be called sync. * * @param updateDelay the delay between updates, in seconds. * The lower, the heaviest. */ public static void init(final Plugin plugin, final int updateDelay) { if (instance == null) { instance = new AsyncPermAccessor(plugin, updateDelay); } } // ################### // // ## Static object ## // // ################### // /** The unique instance of this tool. */ private static AsyncPermAccessor instance; /** Checks if the tool has been initialized. */ private static void checkState() { if (instance == null) { throw new IllegalStateException("AsyncPermAccessor has not been initialized"); } } // ######################## // // ## Non-static content ## // // ######################## // /** * Will store the permissions per player. Sets will be backed by * Concurrent maps. */ private final ConcurrentMap<String, Set<String>> permissions; /** * Will store all connected op players. This Set will be backed by * a Concurrent map. */ private final Set<String> ops; /** The plugin on which the task is attached. */ private final Plugin plugin; /** The update rate, in seconds. */ private final int updateDelay; /** * Construct the AsyncPermAccessor. * * @param plugin the plugin on which the taks will be attached * @param updateDelay the update rate, in seconds */ private AsyncPermAccessor(final Plugin plugin, final int updateDelay) { this.permissions = new ConcurrentHashMap<>(); this.ops = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); this.plugin = plugin; this.updateDelay = updateDelay; update(); launchUpdateTask(); } /** @see #has(String, String) */ private boolean _has(final String playerName, final String permissionNode) { final Set<String> playerPerms = this.permissions.get(playerName); return playerPerms != null && playerPerms.contains(permissionNode); } /** @see #isOp(String) */ private boolean _isOp(final String playerName) { return this.ops.contains(playerName); } /** Update all permissions and op state of all connected players. */ private void update() { for (final Player player : Bukkit.getOnlinePlayers()) { updatePlayer(player); } } /** Update all permissions and op state of the provided player. */ private void updatePlayer(final Player player) { final String playerName = player.getName(); if (player.isOp()) { this.ops.add(playerName); } else { this.ops.remove(playerName); } Set<String> playerPerms = this.permissions.get(playerName); if (playerPerms == null) { playerPerms = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); } for (final PermissionAttachmentInfo perm : player.getEffectivePermissions()) { - playerPerms.add(perm.getPermission()); + if (perm.getValue()) { + playerPerms.add(perm.getPermission()); + } } this.permissions.put(playerName, playerPerms); } /** Launch the update task. */ private void launchUpdateTask() { final long tickDelay = this.updateDelay * 20L; Bukkit.getScheduler().runTaskTimer(this.plugin, new BukkitRunnable() { @Override public void run() { AsyncPermAccessor.this.update(); } }, tickDelay, tickDelay); } }
true
true
private void updatePlayer(final Player player) { final String playerName = player.getName(); if (player.isOp()) { this.ops.add(playerName); } else { this.ops.remove(playerName); } Set<String> playerPerms = this.permissions.get(playerName); if (playerPerms == null) { playerPerms = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); } for (final PermissionAttachmentInfo perm : player.getEffectivePermissions()) { playerPerms.add(perm.getPermission()); } this.permissions.put(playerName, playerPerms); }
private void updatePlayer(final Player player) { final String playerName = player.getName(); if (player.isOp()) { this.ops.add(playerName); } else { this.ops.remove(playerName); } Set<String> playerPerms = this.permissions.get(playerName); if (playerPerms == null) { playerPerms = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); } for (final PermissionAttachmentInfo perm : player.getEffectivePermissions()) { if (perm.getValue()) { playerPerms.add(perm.getPermission()); } } this.permissions.put(playerName, playerPerms); }
diff --git a/src/main/java/com/minecraftdimensions/bungeechatfilter/Rule.java b/src/main/java/com/minecraftdimensions/bungeechatfilter/Rule.java index ceafff9..fa9454d 100644 --- a/src/main/java/com/minecraftdimensions/bungeechatfilter/Rule.java +++ b/src/main/java/com/minecraftdimensions/bungeechatfilter/Rule.java @@ -1,122 +1,123 @@ package com.minecraftdimensions.bungeechatfilter; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.ChatEvent; import java.util.HashMap; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Rule { Pattern regex; Pattern ignore; HashMap<String, String[]> actions; String permission = null; boolean needsPerm; public Rule( String regex, HashMap<String, String[]> actions, String permission, String ignores ) { this.regex = Pattern.compile( regex ); if ( ignores == null ) { ignores = ""; } this.ignore = Pattern.compile( ignores ); this.actions = actions; if(permission!=null && permission.startsWith( "!" )){ permission = permission.substring( 1,permission.length() ); needsPerm = true; } this.permission = permission; } public Pattern getRegex() { return regex; } public String getStringRegex() { return regex.pattern(); } public Matcher getMatcher( String message ) { return regex.matcher( message ); } public boolean doesMessageContainRegex( String message ) { return getMatcher( message ).find(); } public void performActions( ChatEvent event, ProxiedPlayer player ) { String message = event.getMessage(); - if(message.matches( ignore.pattern() )){ + Matcher ig =Pattern.compile(ignore.pattern()).matcher(message); + while(ig.find()){ return; } for ( String action : actions.keySet() ) { if ( action.equals( "deny" ) ) { event.setCancelled( true ); } else if ( action.equals( "message" ) ) { player.sendMessage( color( actions.get( action )[0] ) ); } else if ( action.equals( "kick" ) ) { player.disconnect( color( actions.get( action )[0] ) ); } else if ( action.equals( "alert" ) ) { String alert = actions.get( action )[0].replace( "{player}", player.getDisplayName() ); if(message.split( " ", 2 ).length>1){ alert =alert.replace("{arguments}", message.split( " ", 2 )[1] ) ; } ProxyServer.getInstance().broadcast( color( alert )); } else if ( action.equals( "scommand" ) ) { player.chat( actions.get( action )[0] ); } else if ( action.equals( "pcommand" ) ) { ProxyServer.getInstance().getPluginManager().dispatchCommand( player, actions.get( action )[0] ); } else if( action.equals( "ccommand" )){ ProxyServer.getInstance().getPluginManager().dispatchCommand( ProxyServer.getInstance().getConsole(), actions.get( action )[0].replace( "{player}", player.getName() ) ); } else if ( action.equals( "remove" ) ) { message = message.replaceAll( regex.pattern(), "" ); } else if ( action.equals( "replace" ) ) { Random rand = new Random(); Matcher m = getMatcher( message ); StringBuilder sb = new StringBuilder(); int last = 0; while ( m.find() ) { int n = rand.nextInt( actions.get( action ).length ); sb.append( message.substring( last, m.start() ) ); sb.append( actions.get( action )[n] ); last = m.end(); } sb.append( message.substring( last ) ); message = sb.toString(); } else if ( action.equals( "lower" ) ) { Matcher m = getMatcher( message ); StringBuilder sb = new StringBuilder(); int last = 0; while ( m.find() ) { sb.append( message.substring( last, m.start() ) ); sb.append( m.group( 0 ).toLowerCase() ); last = m.end(); } sb.append( message.substring( last ) ); message = sb.toString(); } } event.setMessage( message ); } public String color( String s ) { return ChatColor.translateAlternateColorCodes( '&', s ); } public boolean hasPermission() { return permission != null; } public boolean needsPermission(){ return needsPerm; } public String getPermission() { return permission; } }
true
true
public void performActions( ChatEvent event, ProxiedPlayer player ) { String message = event.getMessage(); if(message.matches( ignore.pattern() )){ return; } for ( String action : actions.keySet() ) { if ( action.equals( "deny" ) ) { event.setCancelled( true ); } else if ( action.equals( "message" ) ) { player.sendMessage( color( actions.get( action )[0] ) ); } else if ( action.equals( "kick" ) ) { player.disconnect( color( actions.get( action )[0] ) ); } else if ( action.equals( "alert" ) ) { String alert = actions.get( action )[0].replace( "{player}", player.getDisplayName() ); if(message.split( " ", 2 ).length>1){ alert =alert.replace("{arguments}", message.split( " ", 2 )[1] ) ; } ProxyServer.getInstance().broadcast( color( alert )); } else if ( action.equals( "scommand" ) ) { player.chat( actions.get( action )[0] ); } else if ( action.equals( "pcommand" ) ) { ProxyServer.getInstance().getPluginManager().dispatchCommand( player, actions.get( action )[0] ); } else if( action.equals( "ccommand" )){ ProxyServer.getInstance().getPluginManager().dispatchCommand( ProxyServer.getInstance().getConsole(), actions.get( action )[0].replace( "{player}", player.getName() ) ); } else if ( action.equals( "remove" ) ) { message = message.replaceAll( regex.pattern(), "" ); } else if ( action.equals( "replace" ) ) { Random rand = new Random(); Matcher m = getMatcher( message ); StringBuilder sb = new StringBuilder(); int last = 0; while ( m.find() ) { int n = rand.nextInt( actions.get( action ).length ); sb.append( message.substring( last, m.start() ) ); sb.append( actions.get( action )[n] ); last = m.end(); } sb.append( message.substring( last ) ); message = sb.toString(); } else if ( action.equals( "lower" ) ) { Matcher m = getMatcher( message ); StringBuilder sb = new StringBuilder(); int last = 0; while ( m.find() ) { sb.append( message.substring( last, m.start() ) ); sb.append( m.group( 0 ).toLowerCase() ); last = m.end(); } sb.append( message.substring( last ) ); message = sb.toString(); } } event.setMessage( message ); }
public void performActions( ChatEvent event, ProxiedPlayer player ) { String message = event.getMessage(); Matcher ig =Pattern.compile(ignore.pattern()).matcher(message); while(ig.find()){ return; } for ( String action : actions.keySet() ) { if ( action.equals( "deny" ) ) { event.setCancelled( true ); } else if ( action.equals( "message" ) ) { player.sendMessage( color( actions.get( action )[0] ) ); } else if ( action.equals( "kick" ) ) { player.disconnect( color( actions.get( action )[0] ) ); } else if ( action.equals( "alert" ) ) { String alert = actions.get( action )[0].replace( "{player}", player.getDisplayName() ); if(message.split( " ", 2 ).length>1){ alert =alert.replace("{arguments}", message.split( " ", 2 )[1] ) ; } ProxyServer.getInstance().broadcast( color( alert )); } else if ( action.equals( "scommand" ) ) { player.chat( actions.get( action )[0] ); } else if ( action.equals( "pcommand" ) ) { ProxyServer.getInstance().getPluginManager().dispatchCommand( player, actions.get( action )[0] ); } else if( action.equals( "ccommand" )){ ProxyServer.getInstance().getPluginManager().dispatchCommand( ProxyServer.getInstance().getConsole(), actions.get( action )[0].replace( "{player}", player.getName() ) ); } else if ( action.equals( "remove" ) ) { message = message.replaceAll( regex.pattern(), "" ); } else if ( action.equals( "replace" ) ) { Random rand = new Random(); Matcher m = getMatcher( message ); StringBuilder sb = new StringBuilder(); int last = 0; while ( m.find() ) { int n = rand.nextInt( actions.get( action ).length ); sb.append( message.substring( last, m.start() ) ); sb.append( actions.get( action )[n] ); last = m.end(); } sb.append( message.substring( last ) ); message = sb.toString(); } else if ( action.equals( "lower" ) ) { Matcher m = getMatcher( message ); StringBuilder sb = new StringBuilder(); int last = 0; while ( m.find() ) { sb.append( message.substring( last, m.start() ) ); sb.append( m.group( 0 ).toLowerCase() ); last = m.end(); } sb.append( message.substring( last ) ); message = sb.toString(); } } event.setMessage( message ); }
diff --git a/src/net/azib/ipscan/gui/actions/StartStopScanningAction.java b/src/net/azib/ipscan/gui/actions/StartStopScanningAction.java index 4841c8c..dbc86ae 100755 --- a/src/net/azib/ipscan/gui/actions/StartStopScanningAction.java +++ b/src/net/azib/ipscan/gui/actions/StartStopScanningAction.java @@ -1,238 +1,250 @@ /** * This file is a part of Angry IP Scanner source code, * see http://www.azib.net/ for more information. * Licensed under GPLv2. */ package net.azib.ipscan.gui.actions; import java.net.InetAddress; import net.azib.ipscan.config.GlobalConfig; import net.azib.ipscan.config.Labels; import net.azib.ipscan.core.ScannerThread; import net.azib.ipscan.core.ScannerThreadFactory; import net.azib.ipscan.core.ScanningProgressCallback; import net.azib.ipscan.core.ScanningResult; import net.azib.ipscan.core.ScanningResultsCallback; import net.azib.ipscan.core.ScanningResult.ResultType; import net.azib.ipscan.core.net.PingerRegistry; import net.azib.ipscan.core.state.ScanningState; import net.azib.ipscan.core.state.StateMachine; import net.azib.ipscan.core.state.StateTransitionListener; import net.azib.ipscan.gui.ResultTable; import net.azib.ipscan.gui.StatusBar; import net.azib.ipscan.gui.feeders.FeederGUIRegistry; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.MessageBox; /** * Start/Stop button action class. * It listens to presses on the buttons as well as updates gui statuses * * @author Anton Keks */ public class StartStopScanningAction implements SelectionListener, ScanningProgressCallback, StateTransitionListener { private ScannerThreadFactory scannerThreadFactory; private ScannerThread scannerThread; private GlobalConfig globalConfig; private PingerRegistry pingerRegistry; private StatusBar statusBar; private ResultTable resultTable; private FeederGUIRegistry feederRegistry; private Button button; Image[] buttonImages = new Image[ScanningState.values().length]; String[] buttonTexts = new String[ScanningState.values().length]; private Display display; private StateMachine stateMachine; /** * Creates internal stuff independent from all other external dependencies */ StartStopScanningAction() { // pre-load button images buttonImages[ScanningState.IDLE.ordinal()] = new Image(null, Labels.getInstance().getImageAsStream("button.start.img")); buttonImages[ScanningState.SCANNING.ordinal()] = new Image(null, Labels.getInstance().getImageAsStream("button.stop.img")); buttonImages[ScanningState.STARTING.ordinal()] = buttonImages[ScanningState.SCANNING.ordinal()]; buttonImages[ScanningState.RESTARTING.ordinal()] = buttonImages[ScanningState.SCANNING.ordinal()]; buttonImages[ScanningState.STOPPING.ordinal()] = new Image(null, Labels.getInstance().getImageAsStream("button.kill.img")); buttonImages[ScanningState.KILLING.ordinal()] = buttonImages[ScanningState.STOPPING.ordinal()]; // pre-load button texts buttonTexts[ScanningState.IDLE.ordinal()] = Labels.getLabel("button.start"); buttonTexts[ScanningState.SCANNING.ordinal()] = Labels.getLabel("button.stop"); buttonTexts[ScanningState.STARTING.ordinal()] = buttonTexts[ScanningState.SCANNING.ordinal()]; buttonTexts[ScanningState.RESTARTING.ordinal()] = buttonTexts[ScanningState.SCANNING.ordinal()]; buttonTexts[ScanningState.STOPPING.ordinal()] = Labels.getLabel("button.kill"); buttonTexts[ScanningState.KILLING.ordinal()] = Labels.getLabel("button.kill"); } public StartStopScanningAction(ScannerThreadFactory scannerThreadFactory, StateMachine stateMachine, ResultTable resultTable, StatusBar statusBar, FeederGUIRegistry feederRegistry, PingerRegistry pingerRegistry, Button startStopButton, GlobalConfig globalConfig) { this(); this.scannerThreadFactory = scannerThreadFactory; this.resultTable = resultTable; this.statusBar = statusBar; this.feederRegistry = feederRegistry; this.pingerRegistry = pingerRegistry; this.button = startStopButton; this.display = button.getDisplay(); this.stateMachine = stateMachine; this.globalConfig = globalConfig; // add listeners to all state changes stateMachine.addTransitionListener(this); // set the defaultimage ScanningState state = stateMachine.getState(); button.setImage(buttonImages[state.ordinal()]); button.setText(buttonTexts[state.ordinal()]); } /** * Called when scanning button is clicked */ public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } /** * Called when scanning button is clicked */ public void widgetSelected(SelectionEvent event) { // ask for confirmation before erasing scanning results if (stateMachine.inState(ScanningState.IDLE)) { if (!preScanChecks()) return; } stateMachine.transitionToNext(); } private final boolean preScanChecks() { // autodetect usable pingers and silently ignore any changes - // user must see any errors only if they have explicitly selected a pinger pingerRegistry.checkSelectedPinger(); // ask user for confirmation if needed if (globalConfig.askScanConfirmation && resultTable.getItemCount() > 0) { MessageBox box = new MessageBox(Display.getCurrent().getActiveShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO); box.setText(Labels.getLabel("text.scan.new")); box.setMessage(Labels.getLabel("text.scan.confirmation")); if (box.open() != SWT.YES) { return false; } } return true; } public void transitionTo(final ScanningState state) { if (display.isDisposed()) return; display.syncExec(new Runnable() { public void run() { if (statusBar.isDisposed()) return; // TODO: separate GUI and non-GUI stuff switch (state) { case IDLE: // reset state text button.setEnabled(true); statusBar.setStatusText(null); statusBar.setProgress(0); break; case STARTING: // start the scan from scratch! resultTable.removeAll(); - scannerThread = scannerThreadFactory.createScannerThread(feederRegistry.current().getFeeder(), StartStopScanningAction.this, createResultsCallback()); - stateMachine.startScanning(); + try { + scannerThread = scannerThreadFactory.createScannerThread(feederRegistry.current().getFeeder(), StartStopScanningAction.this, createResultsCallback()); + stateMachine.startScanning(); + } + catch (RuntimeException e) { + stateMachine.reset(); + throw e; + } break; case RESTARTING: // restart the scanning - rescan resultTable.resetSelection(); - scannerThread = scannerThreadFactory.createScannerThread(feederRegistry.createRescanFeeder(resultTable.getSelection()), StartStopScanningAction.this, createResultsCallback()); - stateMachine.startScanning(); + try { + scannerThread = scannerThreadFactory.createScannerThread(feederRegistry.createRescanFeeder(resultTable.getSelection()), StartStopScanningAction.this, createResultsCallback()); + stateMachine.startScanning(); + } + catch (RuntimeException e) { + stateMachine.reset(); + throw e; + } break; case SCANNING: scannerThread.start(); break; case STOPPING: statusBar.setStatusText(Labels.getLabel("state.waitForThreads")); break; case KILLING: button.setEnabled(false); statusBar.setStatusText(Labels.getLabel("state.killingThreads")); break; } // change button image button.setImage(buttonImages[state.ordinal()]); button.setText(buttonTexts[state.ordinal()]); } }); } /** * @return the appropriate ResultsCallback instance, depending on the configured display method. */ private final ScanningResultsCallback createResultsCallback() { switch (globalConfig.displayMethod) { default: return new ScanningResultsCallback() { public void prepareForResults(ScanningResult result) { resultTable.addOrUpdateResultRow(result); } public void consumeResults(ScanningResult result) { resultTable.addOrUpdateResultRow(result); } }; case ALIVE: return new ScanningResultsCallback() { public void prepareForResults(ScanningResult result) { } public void consumeResults(ScanningResult result) { if (result.getType().ordinal() >= ResultType.ALIVE.ordinal()) resultTable.addOrUpdateResultRow(result); } }; case PORTS: return new ScanningResultsCallback() { public void prepareForResults(ScanningResult result) { } public void consumeResults(ScanningResult result) { if (result.getType() == ResultType.WITH_PORTS) resultTable.addOrUpdateResultRow(result); } }; } } public void updateProgress(final InetAddress currentAddress, final int runningThreads, final int percentageComplete) { if (display.isDisposed()) return; display.asyncExec(new Runnable() { public void run() { if (statusBar.isDisposed()) return; if (currentAddress != null) { statusBar.setStatusText(Labels.getLabel("state.scanning") + currentAddress.getHostAddress()); } statusBar.setRunningThreads(runningThreads); statusBar.setProgress(percentageComplete); // change button image button.setImage(buttonImages[stateMachine.getState().ordinal()]); } }); } }
false
true
public void transitionTo(final ScanningState state) { if (display.isDisposed()) return; display.syncExec(new Runnable() { public void run() { if (statusBar.isDisposed()) return; // TODO: separate GUI and non-GUI stuff switch (state) { case IDLE: // reset state text button.setEnabled(true); statusBar.setStatusText(null); statusBar.setProgress(0); break; case STARTING: // start the scan from scratch! resultTable.removeAll(); scannerThread = scannerThreadFactory.createScannerThread(feederRegistry.current().getFeeder(), StartStopScanningAction.this, createResultsCallback()); stateMachine.startScanning(); break; case RESTARTING: // restart the scanning - rescan resultTable.resetSelection(); scannerThread = scannerThreadFactory.createScannerThread(feederRegistry.createRescanFeeder(resultTable.getSelection()), StartStopScanningAction.this, createResultsCallback()); stateMachine.startScanning(); break; case SCANNING: scannerThread.start(); break; case STOPPING: statusBar.setStatusText(Labels.getLabel("state.waitForThreads")); break; case KILLING: button.setEnabled(false); statusBar.setStatusText(Labels.getLabel("state.killingThreads")); break; } // change button image button.setImage(buttonImages[state.ordinal()]); button.setText(buttonTexts[state.ordinal()]); } }); }
public void transitionTo(final ScanningState state) { if (display.isDisposed()) return; display.syncExec(new Runnable() { public void run() { if (statusBar.isDisposed()) return; // TODO: separate GUI and non-GUI stuff switch (state) { case IDLE: // reset state text button.setEnabled(true); statusBar.setStatusText(null); statusBar.setProgress(0); break; case STARTING: // start the scan from scratch! resultTable.removeAll(); try { scannerThread = scannerThreadFactory.createScannerThread(feederRegistry.current().getFeeder(), StartStopScanningAction.this, createResultsCallback()); stateMachine.startScanning(); } catch (RuntimeException e) { stateMachine.reset(); throw e; } break; case RESTARTING: // restart the scanning - rescan resultTable.resetSelection(); try { scannerThread = scannerThreadFactory.createScannerThread(feederRegistry.createRescanFeeder(resultTable.getSelection()), StartStopScanningAction.this, createResultsCallback()); stateMachine.startScanning(); } catch (RuntimeException e) { stateMachine.reset(); throw e; } break; case SCANNING: scannerThread.start(); break; case STOPPING: statusBar.setStatusText(Labels.getLabel("state.waitForThreads")); break; case KILLING: button.setEnabled(false); statusBar.setStatusText(Labels.getLabel("state.killingThreads")); break; } // change button image button.setImage(buttonImages[state.ordinal()]); button.setText(buttonTexts[state.ordinal()]); } }); }
diff --git a/src/com/android/deskclock/DeskClock.java b/src/com/android/deskclock/DeskClock.java index f8b7129..e7060b5 100644 --- a/src/com/android/deskclock/DeskClock.java +++ b/src/com/android/deskclock/DeskClock.java @@ -1,733 +1,739 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.deskclock; import android.app.Activity; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.os.PowerManager; import android.provider.Settings; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.view.ContextMenu.ContextMenuInfo; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View.OnClickListener; import android.view.View.OnCreateContextMenuListener; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.TranslateAnimation; import android.widget.AbsoluteLayout; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import static android.os.BatteryManager.BATTERY_STATUS_CHARGING; import static android.os.BatteryManager.BATTERY_STATUS_FULL; import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.Random; /** * DeskClock clock view for desk docks. */ public class DeskClock extends Activity { private static final boolean DEBUG = false; private static final String LOG_TAG = "DeskClock"; // Package ID of the music player. private static final String MUSIC_PACKAGE_ID = "com.android.music"; // Alarm action for midnight (so we can update the date display). private static final String ACTION_MIDNIGHT = "com.android.deskclock.MIDNIGHT"; // Interval between polls of the weather widget. Its refresh period is // likely to be much longer (~3h), but we want to pick up any changes // within 5 minutes. private final long FETCH_WEATHER_DELAY = 5 * 60 * 1000; // 5 min // Delay before engaging the burn-in protection mode (green-on-black). private final long SCREEN_SAVER_TIMEOUT = 10 * 60 * 1000; // 10 min // Repositioning delay in screen saver. private final long SCREEN_SAVER_MOVE_DELAY = 60 * 1000; // 1 min // Color to use for text & graphics in screen saver mode. private final int SCREEN_SAVER_COLOR = 0xFF308030; private final int SCREEN_SAVER_COLOR_DIM = 0xFF183018; // Internal message IDs. private final int FETCH_WEATHER_DATA_MSG = 0x1000; private final int UPDATE_WEATHER_DISPLAY_MSG = 0x1001; private final int SCREEN_SAVER_TIMEOUT_MSG = 0x2000; private final int SCREEN_SAVER_MOVE_MSG = 0x2001; // Weather widget query information. private static final String GENIE_PACKAGE_ID = "com.google.android.apps.genie.geniewidget"; private static final String WEATHER_CONTENT_AUTHORITY = GENIE_PACKAGE_ID + ".weather"; private static final String WEATHER_CONTENT_PATH = "/weather/current"; private static final String[] WEATHER_CONTENT_COLUMNS = new String[] { "location", "timestamp", "temperature", "highTemperature", "lowTemperature", "iconUrl", "iconResId", "description", }; // State variables follow. private DigitalClock mTime; private TextView mDate; private TextView mNextAlarm = null; private TextView mBatteryDisplay; private TextView mWeatherCurrentTemperature; private TextView mWeatherHighTemperature; private TextView mWeatherLowTemperature; private TextView mWeatherLocation; private ImageView mWeatherIcon; private String mWeatherCurrentTemperatureString; private String mWeatherHighTemperatureString; private String mWeatherLowTemperatureString; private String mWeatherLocationString; private Drawable mWeatherIconDrawable; private Resources mGenieResources = null; private boolean mDimmed = false; private boolean mScreenSaverMode = false; private DateFormat mDateFormat; private int mBatteryLevel = -1; private boolean mPluggedIn = false; private boolean mInDock = false; private int mIdleTimeoutEpoch = 0; private boolean mWeatherFetchScheduled = false; private Random mRNG; private PendingIntent mMidnightIntent; private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (Intent.ACTION_DATE_CHANGED.equals(action)) { refreshDate(); } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { handleBatteryUpdate( intent.getIntExtra("status", BATTERY_STATUS_UNKNOWN), intent.getIntExtra("level", 0)); } } }; private final Handler mHandy = new Handler() { @Override public void handleMessage(Message m) { if (m.what == FETCH_WEATHER_DATA_MSG) { if (!mWeatherFetchScheduled) return; mWeatherFetchScheduled = false; new Thread() { public void run() { fetchWeatherData(); } }.start(); scheduleWeatherFetchDelayed(FETCH_WEATHER_DELAY); } else if (m.what == UPDATE_WEATHER_DISPLAY_MSG) { updateWeatherDisplay(); } else if (m.what == SCREEN_SAVER_TIMEOUT_MSG) { if (m.arg1 == mIdleTimeoutEpoch) { saveScreen(); } } else if (m.what == SCREEN_SAVER_MOVE_MSG) { moveScreenSaver(); } } }; private void moveScreenSaver() { moveScreenSaverTo(-1,-1); } private void moveScreenSaverTo(int x, int y) { if (!mScreenSaverMode) return; final View saver_view = findViewById(R.id.saver_view); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); if (x < 0 || y < 0) { int myWidth = saver_view.getMeasuredWidth(); int myHeight = saver_view.getMeasuredHeight(); x = (int)(mRNG.nextFloat()*(metrics.widthPixels - myWidth)); y = (int)(mRNG.nextFloat()*(metrics.heightPixels - myHeight)); } if (DEBUG) Log.d(LOG_TAG, String.format("screen saver: %d: jumping to (%d,%d)", System.currentTimeMillis(), x, y)); saver_view.setLayoutParams(new AbsoluteLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, x, y)); // Synchronize our jumping so that it happens exactly on the second. mHandy.sendEmptyMessageDelayed(SCREEN_SAVER_MOVE_MSG, SCREEN_SAVER_MOVE_DELAY + (1000 - (System.currentTimeMillis() % 1000))); } private void setWakeLock(boolean hold) { if (DEBUG) Log.d(LOG_TAG, (hold ? "hold" : " releas") + "ing wake lock"); Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); winParams.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD; winParams.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED; winParams.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON; if (hold) winParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; else winParams.flags &= (~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); win.setAttributes(winParams); } private void restoreScreen() { if (!mScreenSaverMode) return; if (DEBUG) Log.d(LOG_TAG, "restoreScreen"); mScreenSaverMode = false; initViews(); doDim(false); // restores previous dim mode refreshAll(); } // Special screen-saver mode for OLED displays that burn in quickly private void saveScreen() { if (mScreenSaverMode) return; if (DEBUG) Log.d(LOG_TAG, "saveScreen"); // quickly stash away the x/y of the current date final View oldTimeDate = findViewById(R.id.time_date); int oldLoc[] = new int[2]; oldTimeDate.getLocationOnScreen(oldLoc); mScreenSaverMode = true; Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; win.setAttributes(winParams); // give up any internal focus before we switch layouts final View focused = getCurrentFocus(); if (focused != null) focused.clearFocus(); setContentView(R.layout.desk_clock_saver); mTime = (DigitalClock) findViewById(R.id.time); mDate = (TextView) findViewById(R.id.date); mNextAlarm = (TextView) findViewById(R.id.nextAlarm); final int color = mDimmed ? SCREEN_SAVER_COLOR_DIM : SCREEN_SAVER_COLOR; ((TextView)findViewById(R.id.timeDisplay)).setTextColor(color); ((TextView)findViewById(R.id.am_pm)).setTextColor(color); mDate.setTextColor(color); mNextAlarm.setTextColor(color); mNextAlarm.setCompoundDrawablesWithIntrinsicBounds( getResources().getDrawable(mDimmed ? R.drawable.ic_lock_idle_alarm_saver_dim : R.drawable.ic_lock_idle_alarm_saver), null, null, null); mBatteryDisplay = mWeatherCurrentTemperature = mWeatherHighTemperature = mWeatherLowTemperature = mWeatherLocation = null; mWeatherIcon = null; refreshDate(); refreshAlarm(); moveScreenSaverTo(oldLoc[0], oldLoc[1]); } @Override public void onUserInteraction() { if (mScreenSaverMode) restoreScreen(); } private boolean supportsWeather() { return (mGenieResources != null); } private void scheduleWeatherFetchDelayed(long delay) { if (mWeatherFetchScheduled) return; if (DEBUG) Log.d(LOG_TAG, "scheduling weather fetch message for " + delay + "ms from now"); mWeatherFetchScheduled = true; mHandy.sendEmptyMessageDelayed(FETCH_WEATHER_DATA_MSG, delay); } private void unscheduleWeatherFetch() { mWeatherFetchScheduled = false; } private static final boolean sCelsius; static { String cc = Locale.getDefault().getCountry().toLowerCase(); sCelsius = !("us".equals(cc) || "bz".equals(cc) || "jm".equals(cc)); } private static int celsiusToLocal(int tempC) { return sCelsius ? tempC : (int) Math.round(tempC * 1.8f + 32); } private void fetchWeatherData() { // if we couldn't load the weather widget's resources, we simply // assume it's not present on the device. if (mGenieResources == null) return; Uri queryUri = new Uri.Builder() .scheme(android.content.ContentResolver.SCHEME_CONTENT) .authority(WEATHER_CONTENT_AUTHORITY) .path(WEATHER_CONTENT_PATH) .appendPath(new Long(System.currentTimeMillis()).toString()) .build(); if (DEBUG) Log.d(LOG_TAG, "querying genie: " + queryUri); Cursor cur; try { cur = managedQuery( queryUri, WEATHER_CONTENT_COLUMNS, null, null, null); } catch (RuntimeException e) { Log.e(LOG_TAG, "Weather query failed", e); cur = null; } if (cur != null && cur.moveToFirst()) { if (DEBUG) { java.lang.StringBuilder sb = new java.lang.StringBuilder("Weather query result: {"); for(int i=0; i<cur.getColumnCount(); i++) { if (i>0) sb.append(", "); sb.append(cur.getColumnName(i)) .append("=") .append(cur.getString(i)); } sb.append("}"); Log.d(LOG_TAG, sb.toString()); } mWeatherIconDrawable = mGenieResources.getDrawable(cur.getInt( cur.getColumnIndexOrThrow("iconResId"))); mWeatherCurrentTemperatureString = String.format("%d\u00b0", celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("temperature")))); mWeatherHighTemperatureString = String.format("%d\u00b0", celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("highTemperature")))); mWeatherLowTemperatureString = String.format("%d\u00b0", celsiusToLocal(cur.getInt(cur.getColumnIndexOrThrow("lowTemperature")))); mWeatherLocationString = cur.getString( cur.getColumnIndexOrThrow("location")); } else { Log.w(LOG_TAG, "No weather information available (cur=" + cur +")"); mWeatherIconDrawable = null; mWeatherHighTemperatureString = ""; mWeatherLowTemperatureString = ""; mWeatherLocationString = "Weather data unavailable."; // TODO: internationalize } mHandy.sendEmptyMessage(UPDATE_WEATHER_DISPLAY_MSG); } private void refreshWeather() { if (supportsWeather()) scheduleWeatherFetchDelayed(0); updateWeatherDisplay(); // in case we have it cached } private void updateWeatherDisplay() { if (mWeatherCurrentTemperature == null) return; mWeatherCurrentTemperature.setText(mWeatherCurrentTemperatureString); mWeatherHighTemperature.setText(mWeatherHighTemperatureString); mWeatherLowTemperature.setText(mWeatherLowTemperatureString); mWeatherLocation.setText(mWeatherLocationString); mWeatherIcon.setImageDrawable(mWeatherIconDrawable); } // Adapted from KeyguardUpdateMonitor.java private void handleBatteryUpdate(int plugStatus, int batteryLevel) { final boolean pluggedIn = (plugStatus == BATTERY_STATUS_CHARGING || plugStatus == BATTERY_STATUS_FULL); if (pluggedIn != mPluggedIn) { setWakeLock(pluggedIn); } if (pluggedIn != mPluggedIn || batteryLevel != mBatteryLevel) { mBatteryLevel = batteryLevel; mPluggedIn = pluggedIn; refreshBattery(); } } private void refreshBattery() { if (mBatteryDisplay == null) return; if (mPluggedIn /* || mBatteryLevel < LOW_BATTERY_THRESHOLD */) { mBatteryDisplay.setCompoundDrawablesWithIntrinsicBounds( 0, 0, android.R.drawable.ic_lock_idle_charging, 0); mBatteryDisplay.setText( getString(R.string.battery_charging_level, mBatteryLevel)); mBatteryDisplay.setVisibility(View.VISIBLE); } else { mBatteryDisplay.setVisibility(View.INVISIBLE); } } private void refreshDate() { final Date now = new Date(); if (DEBUG) Log.d(LOG_TAG, "refreshing date..." + now); mDate.setText(mDateFormat.format(now)); } private void refreshAlarm() { if (mNextAlarm == null) return; String nextAlarm = Settings.System.getString(getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED); if (!TextUtils.isEmpty(nextAlarm)) { mNextAlarm.setText(nextAlarm); //mNextAlarm.setCompoundDrawablesWithIntrinsicBounds( // android.R.drawable.ic_lock_idle_alarm, 0, 0, 0); mNextAlarm.setVisibility(View.VISIBLE); } else { mNextAlarm.setVisibility(View.INVISIBLE); } } private void refreshAll() { refreshDate(); refreshAlarm(); refreshBattery(); refreshWeather(); } private void doDim(boolean fade) { View tintView = findViewById(R.id.window_tint); if (tintView == null) return; Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); winParams.flags |= (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); // dim the wallpaper somewhat (how much is determined below) winParams.flags |= (WindowManager.LayoutParams.FLAG_DIM_BEHIND); if (mDimmed) { winParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; winParams.dimAmount = 0.67f; // pump up contrast in dim mode // show the window tint tintView.startAnimation(AnimationUtils.loadAnimation(this, fade ? R.anim.dim : R.anim.dim_instant)); } else { winParams.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN); winParams.dimAmount = 0.5f; // lower contrast in normal mode // hide the window tint tintView.startAnimation(AnimationUtils.loadAnimation(this, fade ? R.anim.undim : R.anim.undim_instant)); } win.setAttributes(winParams); } @Override public void onResume() { super.onResume(); if (DEBUG) Log.d(LOG_TAG, "onResume"); // reload the date format in case the user has changed settings // recently final SimpleDateFormat dateFormat = (SimpleDateFormat) java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL); // This is a little clumsy; we want to honor the locale's date format // (rather than simply hardcoding "Weekday, Month Date") but // DateFormat.FULL includes the year (at least, in enUS). So we lop // that bit off if it's there; should have no effect on // locale-specific date strings that look different. mDateFormat = new SimpleDateFormat(dateFormat.toPattern() .replace(", yyyy", "")); // no year IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_DATE_CHANGED); filter.addAction(Intent.ACTION_BATTERY_CHANGED); filter.addAction(ACTION_MIDNIGHT); Calendar today = Calendar.getInstance(); today.add(Calendar.DATE, 1); mMidnightIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_MIDNIGHT), 0); AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); am.setRepeating(AlarmManager.RTC, today.getTimeInMillis(), AlarmManager.INTERVAL_DAY, mMidnightIntent); registerReceiver(mIntentReceiver, filter); doDim(false); restoreScreen(); refreshAll(); // will schedule periodic weather fetch setWakeLock(mPluggedIn); mIdleTimeoutEpoch++; mHandy.sendMessageDelayed( Message.obtain(mHandy, SCREEN_SAVER_TIMEOUT_MSG, mIdleTimeoutEpoch, 0), SCREEN_SAVER_TIMEOUT); final boolean launchedFromDock = getIntent().hasCategory(Intent.CATEGORY_DESK_DOCK); if (supportsWeather() && launchedFromDock && !mInDock) { if (DEBUG) Log.d(LOG_TAG, "Device now docked; forcing weather to refresh right now"); sendBroadcast( new Intent("com.google.android.apps.genie.REFRESH") .putExtra("requestWeather", true)); } mInDock = launchedFromDock; } @Override public void onPause() { if (DEBUG) Log.d(LOG_TAG, "onPause"); // Turn off the screen saver. (But don't un-dim.) restoreScreen(); // Other things we don't want to be doing in the background. unregisterReceiver(mIntentReceiver); AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); am.cancel(mMidnightIntent); unscheduleWeatherFetch(); super.onPause(); } @Override public void onStop() { if (DEBUG) Log.d(LOG_TAG, "onStop"); // Avoid situations where the user launches Alarm Clock and is // surprised to find it in dim mode (because it was last used in dim // mode, but that last use is long in the past). mDimmed = false; super.onStop(); } private void initViews() { // give up any internal focus before we switch layouts final View focused = getCurrentFocus(); if (focused != null) focused.clearFocus(); setContentView(R.layout.desk_clock); mTime = (DigitalClock) findViewById(R.id.time); mDate = (TextView) findViewById(R.id.date); mBatteryDisplay = (TextView) findViewById(R.id.battery); mTime.getRootView().requestFocus(); mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature); mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature); mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature); mWeatherLocation = (TextView) findViewById(R.id.weather_location); mWeatherIcon = (ImageView) findViewById(R.id.weather_icon); mNextAlarm = (TextView) findViewById(R.id.nextAlarm); final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button); alarmButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent(DeskClock.this, AlarmClock.class)); } }); final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button); galleryButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { startActivity(new Intent( Intent.ACTION_VIEW, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI) - .putExtra("slideshow", true)); + .putExtra("slideshow", true) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } catch (android.content.ActivityNotFoundException e) { Log.e(LOG_TAG, "Couldn't launch image browser", e); } } }); final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button); musicButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { - Intent musicAppQuery = getPackageManager().getLaunchIntentForPackage(MUSIC_PACKAGE_ID); + Intent musicAppQuery = getPackageManager() + .getLaunchIntentForPackage(MUSIC_PACKAGE_ID) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (musicAppQuery != null) { startActivity(musicAppQuery); } } catch (android.content.ActivityNotFoundException e) { Log.e(LOG_TAG, "Couldn't launch music browser", e); } } }); final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button); homeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity( new Intent(Intent.ACTION_MAIN) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .addCategory(Intent.CATEGORY_HOME)); } }); final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button); nightmodeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mDimmed = ! mDimmed; doDim(true); } }); nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { saveScreen(); return true; } }); final View weatherView = findViewById(R.id.weather); weatherView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (!supportsWeather()) return; - Intent genieAppQuery = getPackageManager().getLaunchIntentForPackage(GENIE_PACKAGE_ID); + Intent genieAppQuery = getPackageManager() + .getLaunchIntentForPackage(GENIE_PACKAGE_ID) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (genieAppQuery != null) { startActivity(genieAppQuery); } } }); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (!mScreenSaverMode) { initViews(); doDim(false); refreshAll(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_item_alarms) { startActivity(new Intent(DeskClock.this, AlarmClock.class)); return true; } return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.desk_clock_menu, menu); return true; } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); mRNG = new Random(); try { mGenieResources = getPackageManager().getResourcesForApplication(GENIE_PACKAGE_ID); } catch (PackageManager.NameNotFoundException e) { // no weather info available Log.w(LOG_TAG, "Can't find "+GENIE_PACKAGE_ID+". Weather forecast will not be available."); } initViews(); } }
false
true
private void initViews() { // give up any internal focus before we switch layouts final View focused = getCurrentFocus(); if (focused != null) focused.clearFocus(); setContentView(R.layout.desk_clock); mTime = (DigitalClock) findViewById(R.id.time); mDate = (TextView) findViewById(R.id.date); mBatteryDisplay = (TextView) findViewById(R.id.battery); mTime.getRootView().requestFocus(); mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature); mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature); mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature); mWeatherLocation = (TextView) findViewById(R.id.weather_location); mWeatherIcon = (ImageView) findViewById(R.id.weather_icon); mNextAlarm = (TextView) findViewById(R.id.nextAlarm); final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button); alarmButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent(DeskClock.this, AlarmClock.class)); } }); final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button); galleryButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { startActivity(new Intent( Intent.ACTION_VIEW, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI) .putExtra("slideshow", true)); } catch (android.content.ActivityNotFoundException e) { Log.e(LOG_TAG, "Couldn't launch image browser", e); } } }); final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button); musicButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { Intent musicAppQuery = getPackageManager().getLaunchIntentForPackage(MUSIC_PACKAGE_ID); if (musicAppQuery != null) { startActivity(musicAppQuery); } } catch (android.content.ActivityNotFoundException e) { Log.e(LOG_TAG, "Couldn't launch music browser", e); } } }); final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button); homeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity( new Intent(Intent.ACTION_MAIN) .addCategory(Intent.CATEGORY_HOME)); } }); final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button); nightmodeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mDimmed = ! mDimmed; doDim(true); } }); nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { saveScreen(); return true; } }); final View weatherView = findViewById(R.id.weather); weatherView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (!supportsWeather()) return; Intent genieAppQuery = getPackageManager().getLaunchIntentForPackage(GENIE_PACKAGE_ID); if (genieAppQuery != null) { startActivity(genieAppQuery); } } }); }
private void initViews() { // give up any internal focus before we switch layouts final View focused = getCurrentFocus(); if (focused != null) focused.clearFocus(); setContentView(R.layout.desk_clock); mTime = (DigitalClock) findViewById(R.id.time); mDate = (TextView) findViewById(R.id.date); mBatteryDisplay = (TextView) findViewById(R.id.battery); mTime.getRootView().requestFocus(); mWeatherCurrentTemperature = (TextView) findViewById(R.id.weather_temperature); mWeatherHighTemperature = (TextView) findViewById(R.id.weather_high_temperature); mWeatherLowTemperature = (TextView) findViewById(R.id.weather_low_temperature); mWeatherLocation = (TextView) findViewById(R.id.weather_location); mWeatherIcon = (ImageView) findViewById(R.id.weather_icon); mNextAlarm = (TextView) findViewById(R.id.nextAlarm); final ImageButton alarmButton = (ImageButton) findViewById(R.id.alarm_button); alarmButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent(DeskClock.this, AlarmClock.class)); } }); final ImageButton galleryButton = (ImageButton) findViewById(R.id.gallery_button); galleryButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { startActivity(new Intent( Intent.ACTION_VIEW, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI) .putExtra("slideshow", true) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } catch (android.content.ActivityNotFoundException e) { Log.e(LOG_TAG, "Couldn't launch image browser", e); } } }); final ImageButton musicButton = (ImageButton) findViewById(R.id.music_button); musicButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { Intent musicAppQuery = getPackageManager() .getLaunchIntentForPackage(MUSIC_PACKAGE_ID) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (musicAppQuery != null) { startActivity(musicAppQuery); } } catch (android.content.ActivityNotFoundException e) { Log.e(LOG_TAG, "Couldn't launch music browser", e); } } }); final ImageButton homeButton = (ImageButton) findViewById(R.id.home_button); homeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity( new Intent(Intent.ACTION_MAIN) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .addCategory(Intent.CATEGORY_HOME)); } }); final ImageButton nightmodeButton = (ImageButton) findViewById(R.id.nightmode_button); nightmodeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mDimmed = ! mDimmed; doDim(true); } }); nightmodeButton.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { saveScreen(); return true; } }); final View weatherView = findViewById(R.id.weather); weatherView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (!supportsWeather()) return; Intent genieAppQuery = getPackageManager() .getLaunchIntentForPackage(GENIE_PACKAGE_ID) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (genieAppQuery != null) { startActivity(genieAppQuery); } } }); }
diff --git a/src/com/itmill/toolkit/demo/testbench/TestForBasicApplicationLayout.java b/src/com/itmill/toolkit/demo/testbench/TestForBasicApplicationLayout.java index 77f671cb5..19de0d4c8 100644 --- a/src/com/itmill/toolkit/demo/testbench/TestForBasicApplicationLayout.java +++ b/src/com/itmill/toolkit/demo/testbench/TestForBasicApplicationLayout.java @@ -1,115 +1,116 @@ package com.itmill.toolkit.demo.testbench; import java.sql.SQLException; import java.util.Locale; import com.itmill.toolkit.data.util.QueryContainer; import com.itmill.toolkit.demo.util.SampleDatabase; import com.itmill.toolkit.terminal.Sizeable; import com.itmill.toolkit.ui.Button; import com.itmill.toolkit.ui.CustomComponent; import com.itmill.toolkit.ui.DateField; import com.itmill.toolkit.ui.ExpandLayout; import com.itmill.toolkit.ui.Label; import com.itmill.toolkit.ui.OrderedLayout; import com.itmill.toolkit.ui.Panel; import com.itmill.toolkit.ui.SplitPanel; import com.itmill.toolkit.ui.TabSheet; import com.itmill.toolkit.ui.Table; import com.itmill.toolkit.ui.Button.ClickEvent; import com.itmill.toolkit.ui.Button.ClickListener; public class TestForBasicApplicationLayout extends CustomComponent { private Button click; private Button click2; private TabSheet tab; // Database provided with sample data private SampleDatabase sampleDatabase; public TestForBasicApplicationLayout() { click = new Button("Set height -1", new ClickListener() { public void buttonClick(ClickEvent event) { tab.setHeight(-1); } }); click2 = new Button("Set height 100%", new ClickListener() { public void buttonClick(ClickEvent event) { tab.setHeight(100); tab.setHeightUnits(Sizeable.UNITS_PERCENTAGE); } }); SplitPanel sp = new SplitPanel(SplitPanel.ORIENTATION_HORIZONTAL); sp.setSplitPosition(290, Sizeable.UNITS_PIXELS); SplitPanel sp2 = new SplitPanel(SplitPanel.ORIENTATION_VERTICAL); sp2.setSplitPosition(255, Sizeable.UNITS_PIXELS); Panel p = new Panel("Accordion Panel"); p.setSizeFull(); tab = new TabSheet(); tab.setSizeFull(); Panel report = new Panel("Monthly Program Runs", new ExpandLayout()); OrderedLayout controls = new OrderedLayout(); controls.setMargin(true); controls.addComponent(new Label("Report tab")); controls.addComponent(click); controls.addComponent(click2); report.addComponent(controls); DateField cal = new DateField(); cal.setResolution(DateField.RESOLUTION_DAY); cal.setLocale(new Locale("en", "US")); report.addComponent(cal); ((ExpandLayout) report.getLayout()).expand(controls); report.addStyleName(Panel.STYLE_LIGHT); report.setHeight(100); report.setHeightUnits(Sizeable.UNITS_PERCENTAGE); sp2.setFirstComponent(report); Table table = new Table(); // populate Toolkit table component with test SQL table rows try { + sampleDatabase = new SampleDatabase(); QueryContainer qc = new QueryContainer("SELECT * FROM employee", sampleDatabase.getConnection()); table.setContainerDataSource(qc); } catch (SQLException e) { e.printStackTrace(); } // define which columns should be visible on Table component table.setVisibleColumns(new Object[] { "FIRSTNAME", "LASTNAME", "TITLE", "UNIT" }); table.setItemCaptionPropertyId("ID"); table.setPageLength(15); table.setSelectable(true); table.setRowHeaderMode(Table.ROW_HEADER_MODE_INDEX); table.setColumnCollapsingAllowed(true); table.setColumnReorderingAllowed(true); table.setSortDisabled(false); table.setSizeFull(); table.addStyleName("table-inline"); sp2.setSecondComponent(table); tab.addTab(new Label("Tab1"), "Summary", null); tab.addTab(sp2, "Reports", null); tab.addTab(new Label("Tab 3"), "Statistics", null); tab.addTab(new Label("Tab 4"), "Error Tracking", null); tab.setSelectedTab(sp2); sp.setFirstComponent(p); sp.setSecondComponent(tab); setCompositionRoot(sp); } }
true
true
public TestForBasicApplicationLayout() { click = new Button("Set height -1", new ClickListener() { public void buttonClick(ClickEvent event) { tab.setHeight(-1); } }); click2 = new Button("Set height 100%", new ClickListener() { public void buttonClick(ClickEvent event) { tab.setHeight(100); tab.setHeightUnits(Sizeable.UNITS_PERCENTAGE); } }); SplitPanel sp = new SplitPanel(SplitPanel.ORIENTATION_HORIZONTAL); sp.setSplitPosition(290, Sizeable.UNITS_PIXELS); SplitPanel sp2 = new SplitPanel(SplitPanel.ORIENTATION_VERTICAL); sp2.setSplitPosition(255, Sizeable.UNITS_PIXELS); Panel p = new Panel("Accordion Panel"); p.setSizeFull(); tab = new TabSheet(); tab.setSizeFull(); Panel report = new Panel("Monthly Program Runs", new ExpandLayout()); OrderedLayout controls = new OrderedLayout(); controls.setMargin(true); controls.addComponent(new Label("Report tab")); controls.addComponent(click); controls.addComponent(click2); report.addComponent(controls); DateField cal = new DateField(); cal.setResolution(DateField.RESOLUTION_DAY); cal.setLocale(new Locale("en", "US")); report.addComponent(cal); ((ExpandLayout) report.getLayout()).expand(controls); report.addStyleName(Panel.STYLE_LIGHT); report.setHeight(100); report.setHeightUnits(Sizeable.UNITS_PERCENTAGE); sp2.setFirstComponent(report); Table table = new Table(); // populate Toolkit table component with test SQL table rows try { QueryContainer qc = new QueryContainer("SELECT * FROM employee", sampleDatabase.getConnection()); table.setContainerDataSource(qc); } catch (SQLException e) { e.printStackTrace(); } // define which columns should be visible on Table component table.setVisibleColumns(new Object[] { "FIRSTNAME", "LASTNAME", "TITLE", "UNIT" }); table.setItemCaptionPropertyId("ID"); table.setPageLength(15); table.setSelectable(true); table.setRowHeaderMode(Table.ROW_HEADER_MODE_INDEX); table.setColumnCollapsingAllowed(true); table.setColumnReorderingAllowed(true); table.setSortDisabled(false); table.setSizeFull(); table.addStyleName("table-inline"); sp2.setSecondComponent(table); tab.addTab(new Label("Tab1"), "Summary", null); tab.addTab(sp2, "Reports", null); tab.addTab(new Label("Tab 3"), "Statistics", null); tab.addTab(new Label("Tab 4"), "Error Tracking", null); tab.setSelectedTab(sp2); sp.setFirstComponent(p); sp.setSecondComponent(tab); setCompositionRoot(sp); }
public TestForBasicApplicationLayout() { click = new Button("Set height -1", new ClickListener() { public void buttonClick(ClickEvent event) { tab.setHeight(-1); } }); click2 = new Button("Set height 100%", new ClickListener() { public void buttonClick(ClickEvent event) { tab.setHeight(100); tab.setHeightUnits(Sizeable.UNITS_PERCENTAGE); } }); SplitPanel sp = new SplitPanel(SplitPanel.ORIENTATION_HORIZONTAL); sp.setSplitPosition(290, Sizeable.UNITS_PIXELS); SplitPanel sp2 = new SplitPanel(SplitPanel.ORIENTATION_VERTICAL); sp2.setSplitPosition(255, Sizeable.UNITS_PIXELS); Panel p = new Panel("Accordion Panel"); p.setSizeFull(); tab = new TabSheet(); tab.setSizeFull(); Panel report = new Panel("Monthly Program Runs", new ExpandLayout()); OrderedLayout controls = new OrderedLayout(); controls.setMargin(true); controls.addComponent(new Label("Report tab")); controls.addComponent(click); controls.addComponent(click2); report.addComponent(controls); DateField cal = new DateField(); cal.setResolution(DateField.RESOLUTION_DAY); cal.setLocale(new Locale("en", "US")); report.addComponent(cal); ((ExpandLayout) report.getLayout()).expand(controls); report.addStyleName(Panel.STYLE_LIGHT); report.setHeight(100); report.setHeightUnits(Sizeable.UNITS_PERCENTAGE); sp2.setFirstComponent(report); Table table = new Table(); // populate Toolkit table component with test SQL table rows try { sampleDatabase = new SampleDatabase(); QueryContainer qc = new QueryContainer("SELECT * FROM employee", sampleDatabase.getConnection()); table.setContainerDataSource(qc); } catch (SQLException e) { e.printStackTrace(); } // define which columns should be visible on Table component table.setVisibleColumns(new Object[] { "FIRSTNAME", "LASTNAME", "TITLE", "UNIT" }); table.setItemCaptionPropertyId("ID"); table.setPageLength(15); table.setSelectable(true); table.setRowHeaderMode(Table.ROW_HEADER_MODE_INDEX); table.setColumnCollapsingAllowed(true); table.setColumnReorderingAllowed(true); table.setSortDisabled(false); table.setSizeFull(); table.addStyleName("table-inline"); sp2.setSecondComponent(table); tab.addTab(new Label("Tab1"), "Summary", null); tab.addTab(sp2, "Reports", null); tab.addTab(new Label("Tab 3"), "Statistics", null); tab.addTab(new Label("Tab 4"), "Error Tracking", null); tab.setSelectedTab(sp2); sp.setFirstComponent(p); sp.setSecondComponent(tab); setCompositionRoot(sp); }
diff --git a/tregmine/src/info/tregmine/Tregmine.java b/tregmine/src/info/tregmine/Tregmine.java index abc2185..dfad4ac 100644 --- a/tregmine/src/info/tregmine/Tregmine.java +++ b/tregmine/src/info/tregmine/Tregmine.java @@ -1,200 +1,200 @@ package info.tregmine; import info.tregmine.api.TregminePlayer; import info.tregmine.listeners.TregmineBlockListener; import info.tregmine.listeners.TregmineEntityListener; import info.tregmine.listeners.TregminePlayerListener; import info.tregmine.listeners.TregmineWeatherListener; import info.tregmine.stats.BlockStats; //import info.tregmine.world.citadel.CitadelLimit; import java.util.logging.Logger; import org.bukkit.ChatColor; //import org.bukkit.ChatColor; import org.bukkit.WorldCreator; import org.bukkit.World.Environment; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; //import org.bukkit.ChatColor; import org.bukkit.entity.Player; //import org.bukkit.event.Event; //import org.bukkit.event.Event.Priority; //import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import java.util.HashMap; import java.util.Map; /** * @author Ein Andersson - www.tregmine.info * @version 0.8 */ public class Tregmine extends JavaPlugin { public final Logger log = Logger.getLogger("Minecraft"); public final BlockStats blockStats = new BlockStats(this); public Map<String, TregminePlayer> tregminePlayer = new HashMap<String, TregminePlayer>(); public int version = 0; public int amount = 0; @Override public void onEnable() { WorldCreator citadelCreator = new WorldCreator("citadel"); citadelCreator.environment(Environment.NORMAL); citadelCreator.createWorld(); WorldCreator world = new WorldCreator("world"); world.environment(Environment.NORMAL); world.createWorld(); WorldCreator NETHER = new WorldCreator("world_nether"); NETHER.environment(Environment.NETHER); NETHER.createWorld(); getServer().getPluginManager().registerEvents(new info.tregmine.lookup.LookupPlayer(this), this); getServer().getPluginManager().registerEvents(new TregminePlayerListener(this), this); getServer().getPluginManager().registerEvents(new TregmineBlockListener(this), this); getServer().getPluginManager().registerEvents(new TregmineEntityListener(this), this); getServer().getPluginManager().registerEvents(new TregmineWeatherListener(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.invis.InvisPlayer(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.death.DeathEntity(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.death.DeathPlayer(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.chat.Chat(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.sign.Color(), this); } @Override public void onDisable() { //run when plugin is disabled this.getServer().getScheduler().cancelTasks(this); } @Override public void onLoad() { Player[] players = this.getServer().getOnlinePlayers(); for (Player player : players) { String onlineName = player.getName(); TregminePlayer tregPlayer = new TregminePlayer(player, onlineName); tregPlayer.load(); this.tregminePlayer.put(onlineName, tregPlayer); player.sendMessage(ChatColor.AQUA + "Tregmine successfully upgraded to build: " + this.getDescription().getVersion() ); } } public TregminePlayer getPlayer(String name) { return tregminePlayer.get(name); } public TregminePlayer getPlayer(Player player) { return tregminePlayer.get(player.getName()); } public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { String commandName = command.getName().toLowerCase(); Player from = null; TregminePlayer player = null; if(!(sender instanceof Player)) { return false; } else { from = (Player) sender; player = this.getPlayer(from); } if(commandName.equals("who") || commandName.equals("playerlist") || commandName.equals("list")){ info.tregmine.commands.Who.run(this, player, args); return true; } if(commandName.equals("tp")){ info.tregmine.commands.Tp.run(this, player, args); return true; } if(commandName.equals("channel")){ if (args.length != 1) { return false; } from.sendMessage(ChatColor.YELLOW + "You are now talking in channel " + args[0] + "."); from.sendMessage(ChatColor.YELLOW + "Write /channel global to switch to the global chat." ); player.setChatChannel(args[0]); return true; } if(commandName.equals("force") && args.length == 2 ){ player.setChatChannel(args[1]); Player to = getServer().matchPlayer(args[0]).get(0); info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); toPlayer.setChatChannel(args[1]); to.sendMessage(ChatColor.YELLOW + player.getChatChannel() + " forced you into channel " + args[1].toUpperCase() + "."); to.sendMessage(ChatColor.YELLOW + "Write /channel global to switch back to the global chat." ); from.sendMessage(ChatColor.YELLOW + "You are now in a forced chat " + args[1].toUpperCase()+ " with " + to.getDisplayName() + "."); this.log.info(from.getName() + " FORCED CHAT WITH " + to.getDisplayName() + " IN CHANNEL " + args[1].toUpperCase()); return true; } if(commandName.equals("msg") || commandName.equals("m") || commandName.equals("tell")) { Player to = getServer().getPlayer(args[0]); if (to != null) { info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); StringBuffer buf = new StringBuffer(); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if (!toPlayer.getMetaBoolean("invis")) { from.sendMessage(ChatColor.GREEN + "(to) " + toPlayer.getChatName() + ChatColor.GREEN + ": " + buffMsg); } to.sendMessage(ChatColor.GREEN + "(msg) " + player.getChatName() + ChatColor.GREEN + ": " + buffMsg); log.info(from.getName() + " => " + to.getName() + buffMsg); return true; } } if(commandName.equals("me") && args.length > 0 ){ StringBuffer buf = new StringBuffer(); Player[] players = getServer().getOnlinePlayers(); for (int i = 0; i < args.length; ++i) { buf.append(" " + args[i]); } for (Player tp : players) { TregminePlayer to = this.getPlayer(tp); if (player.getChatChannel().equals(to.getChatChannel())) { - player.sendMessage("* " + player.getChatName() + ChatColor.WHITE + buf.toString() ); + to.sendMessage("* " + player.getChatName() + ChatColor.WHITE + buf.toString() ); } } return true; } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { String commandName = command.getName().toLowerCase(); Player from = null; TregminePlayer player = null; if(!(sender instanceof Player)) { return false; } else { from = (Player) sender; player = this.getPlayer(from); } if(commandName.equals("who") || commandName.equals("playerlist") || commandName.equals("list")){ info.tregmine.commands.Who.run(this, player, args); return true; } if(commandName.equals("tp")){ info.tregmine.commands.Tp.run(this, player, args); return true; } if(commandName.equals("channel")){ if (args.length != 1) { return false; } from.sendMessage(ChatColor.YELLOW + "You are now talking in channel " + args[0] + "."); from.sendMessage(ChatColor.YELLOW + "Write /channel global to switch to the global chat." ); player.setChatChannel(args[0]); return true; } if(commandName.equals("force") && args.length == 2 ){ player.setChatChannel(args[1]); Player to = getServer().matchPlayer(args[0]).get(0); info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); toPlayer.setChatChannel(args[1]); to.sendMessage(ChatColor.YELLOW + player.getChatChannel() + " forced you into channel " + args[1].toUpperCase() + "."); to.sendMessage(ChatColor.YELLOW + "Write /channel global to switch back to the global chat." ); from.sendMessage(ChatColor.YELLOW + "You are now in a forced chat " + args[1].toUpperCase()+ " with " + to.getDisplayName() + "."); this.log.info(from.getName() + " FORCED CHAT WITH " + to.getDisplayName() + " IN CHANNEL " + args[1].toUpperCase()); return true; } if(commandName.equals("msg") || commandName.equals("m") || commandName.equals("tell")) { Player to = getServer().getPlayer(args[0]); if (to != null) { info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); StringBuffer buf = new StringBuffer(); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if (!toPlayer.getMetaBoolean("invis")) { from.sendMessage(ChatColor.GREEN + "(to) " + toPlayer.getChatName() + ChatColor.GREEN + ": " + buffMsg); } to.sendMessage(ChatColor.GREEN + "(msg) " + player.getChatName() + ChatColor.GREEN + ": " + buffMsg); log.info(from.getName() + " => " + to.getName() + buffMsg); return true; } } if(commandName.equals("me") && args.length > 0 ){ StringBuffer buf = new StringBuffer(); Player[] players = getServer().getOnlinePlayers(); for (int i = 0; i < args.length; ++i) { buf.append(" " + args[i]); } for (Player tp : players) { TregminePlayer to = this.getPlayer(tp); if (player.getChatChannel().equals(to.getChatChannel())) { player.sendMessage("* " + player.getChatName() + ChatColor.WHITE + buf.toString() ); } } return true; } return false; }
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { String commandName = command.getName().toLowerCase(); Player from = null; TregminePlayer player = null; if(!(sender instanceof Player)) { return false; } else { from = (Player) sender; player = this.getPlayer(from); } if(commandName.equals("who") || commandName.equals("playerlist") || commandName.equals("list")){ info.tregmine.commands.Who.run(this, player, args); return true; } if(commandName.equals("tp")){ info.tregmine.commands.Tp.run(this, player, args); return true; } if(commandName.equals("channel")){ if (args.length != 1) { return false; } from.sendMessage(ChatColor.YELLOW + "You are now talking in channel " + args[0] + "."); from.sendMessage(ChatColor.YELLOW + "Write /channel global to switch to the global chat." ); player.setChatChannel(args[0]); return true; } if(commandName.equals("force") && args.length == 2 ){ player.setChatChannel(args[1]); Player to = getServer().matchPlayer(args[0]).get(0); info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); toPlayer.setChatChannel(args[1]); to.sendMessage(ChatColor.YELLOW + player.getChatChannel() + " forced you into channel " + args[1].toUpperCase() + "."); to.sendMessage(ChatColor.YELLOW + "Write /channel global to switch back to the global chat." ); from.sendMessage(ChatColor.YELLOW + "You are now in a forced chat " + args[1].toUpperCase()+ " with " + to.getDisplayName() + "."); this.log.info(from.getName() + " FORCED CHAT WITH " + to.getDisplayName() + " IN CHANNEL " + args[1].toUpperCase()); return true; } if(commandName.equals("msg") || commandName.equals("m") || commandName.equals("tell")) { Player to = getServer().getPlayer(args[0]); if (to != null) { info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); StringBuffer buf = new StringBuffer(); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if (!toPlayer.getMetaBoolean("invis")) { from.sendMessage(ChatColor.GREEN + "(to) " + toPlayer.getChatName() + ChatColor.GREEN + ": " + buffMsg); } to.sendMessage(ChatColor.GREEN + "(msg) " + player.getChatName() + ChatColor.GREEN + ": " + buffMsg); log.info(from.getName() + " => " + to.getName() + buffMsg); return true; } } if(commandName.equals("me") && args.length > 0 ){ StringBuffer buf = new StringBuffer(); Player[] players = getServer().getOnlinePlayers(); for (int i = 0; i < args.length; ++i) { buf.append(" " + args[i]); } for (Player tp : players) { TregminePlayer to = this.getPlayer(tp); if (player.getChatChannel().equals(to.getChatChannel())) { to.sendMessage("* " + player.getChatName() + ChatColor.WHITE + buf.toString() ); } } return true; } return false; }
diff --git a/src/zemberek3/lexicon/TurkishSuffixes.java b/src/zemberek3/lexicon/TurkishSuffixes.java index 3142a31..622be43 100644 --- a/src/zemberek3/lexicon/TurkishSuffixes.java +++ b/src/zemberek3/lexicon/TurkishSuffixes.java @@ -1,888 +1,888 @@ package zemberek3.lexicon; import zemberek3.lexicon.graph.DynamicSuffixProvider; import zemberek3.lexicon.graph.SuffixData; import zemberek3.lexicon.graph.TerminationType; public class TurkishSuffixes extends DynamicSuffixProvider { // ------------ case suffixes --------------------------- public static Suffix Dat = new Suffix("Dat"); public static SuffixFormSet Dat_yA = new SuffixFormSet(Dat, "+yA"); public static SuffixFormSet Dat_nA = new SuffixFormSet(Dat, "nA"); public static Suffix Loc = new Suffix("Loc"); public static SuffixFormSet Loc_dA = new SuffixFormSet(Loc, ">dA"); public static SuffixFormSet Loc_ndA = new SuffixFormSet(Loc, "ndA"); public static Suffix Abl = new Suffix("Abl"); public static SuffixFormSet Abl_dAn = new SuffixFormSet(Abl, ">dAn"); public static SuffixFormSet Abl_ndAn = new SuffixFormSet(Abl, "ndAn"); public static Suffix Gen = new Suffix("Gen"); public static SuffixFormSet Gen_nIn = new SuffixFormSet(Gen, "+nIn"); public static Suffix Acc = new Suffix("Acc"); public static SuffixFormSet Acc_yI = new SuffixFormSet(Acc, "+yI"); public static SuffixFormSet Acc_nI = new SuffixFormSet(Acc, "nI"); public static Suffix Inst = new Suffix("Inst"); public static SuffixFormSet Inst_ylA = new SuffixFormSet(Inst, "+ylA"); public static Suffix Nom = new Suffix("Nom"); public static SuffixFormSet Nom_EMPTY = getTemplate("Nom_EMPTY", Nom); // ----------------- possesive ---------------------------- public static Suffix Pnon = new Suffix("Pnon"); public static SuffixFormSet Pnon_EMPTY = getTemplate("Pnon_EMPTY", Pnon); public static Suffix P1sg = new Suffix("P1sg"); public static SuffixFormSet P1sg_Im = new SuffixFormSet(P1sg, "Im"); public static Suffix P2sg = new Suffix("P2sg"); public static SuffixFormSet P2sg_In = new SuffixFormSet(P2sg, "In"); public static Suffix P3sg = new Suffix("P3sg"); public static SuffixFormSet P3sg_sI = new SuffixFormSet(P3sg, "+sI"); public static Suffix P1pl = new Suffix("P1pl"); public static SuffixFormSet P1pl_ImIz = new SuffixFormSet(P1pl, "ImIz"); public static Suffix P2pl = new Suffix("P2pl"); public static SuffixFormSet P2pl_InIz = new SuffixFormSet(P2pl, "InIz"); public static Suffix P3pl = new Suffix("P3pl"); public static SuffixFormSet P3pl_lArI = new SuffixFormSet(P3pl, "lArI"); // -------------- Number-Person agreement -------------------- public static Suffix A1sg = new Suffix("A1sg"); public static SuffixFormSet A1sg_yIm = new SuffixFormSet(A1sg, "+yIm"); // gel-e-yim public static SuffixFormSet A1sg_m = new SuffixFormSet(A1sg, "m"); // gel-se-m public static SuffixFormSet A1sg_EMPTY = new SuffixFormSet("A1sg_EMPTY", A1sg, ""); // ben public static Suffix A2sg = new Suffix("A2sg"); public static SuffixFormSet A2sg_sIn = new SuffixFormSet(A2sg, "sIn"); // gel-ecek-sin public static SuffixFormSet A2sg_n = new SuffixFormSet(A2sg, "n"); // gel-di-n public static SuffixFormSet A2sg_EMPTY = new SuffixFormSet("A2sg_EMPTY", A2sg, ""); // gel, sen,.. public static Suffix A2sg2 = new Suffix("A2sg2"); public static SuffixFormSet A2sg2_sAnA = new SuffixFormSet(A2sg2, "sAnA"); //gel-sene public static Suffix A2sg3 = new Suffix("A2sg3"); public static SuffixFormSet A2sg3_yInIz = new SuffixFormSet(A2sg3, "+yInIz"); //gel-iniz public static Suffix A3sg = new Suffix("A3sg"); public static SuffixFormSet A3sg_EMPTY = getTemplate("A3sg_EMPTY", A3sg); // gel-di-, o- public static SuffixFormSet A3sg_sIn = new SuffixFormSet(A3sg, "sIn"); // gel-sin public static Suffix A1pl = new Suffix("A1pl"); public static SuffixFormSet A1pl_yIz = new SuffixFormSet(A1pl, "+yIz"); // geliyor-uz public static SuffixFormSet A1pl_k = new SuffixFormSet(A1pl, "k"); // gel-di-k public static SuffixFormSet A1pl_lIm = new SuffixFormSet(A1pl, "lIm"); // gel-e-lim public static SuffixFormSet A1pl_EMPTY = new SuffixFormSet("A1pl_EMPTY", A1pl, ""); // biz public static Suffix A2pl = new Suffix("A2pl"); public static SuffixFormSet A2pl_sInIz = new SuffixFormSet(A2pl, "sInIz"); // gel-ecek-siniz public static SuffixFormSet A2pl_nIz = new SuffixFormSet(A2pl, "nIz"); // gel-di-niz public static SuffixFormSet A2pl_yIn = new SuffixFormSet(A2pl, "+yIn"); // gel-me-yin public static SuffixFormSet A2pl_EMPTY = new SuffixFormSet("A2pl_EMPTY", A2pl, ""); // gel-e-lim public static Suffix A2pl2 = new Suffix("A2pl2"); public static SuffixFormSet A2pl2_sAnIzA = new SuffixFormSet(A2pl2, "sAnIzA"); // gel-senize public static Suffix A3pl = new Suffix("A3pl"); public static SuffixFormSet A3pl_lAr = new SuffixFormSet(A3pl, "lAr"); // gel-ecek-ler public static SuffixFormSet A3pl_Comp_lAr = new SuffixFormSet("A3pl_Comp_lAr", A3pl, "lAr", TerminationType.NON_TERMINAL); //zeytinyağlarımız public static SuffixFormSet A3pl_sInlAr = new SuffixFormSet(A3pl, "sInlAr"); // gel-sinler // ------------ derivatioonal ---------------------- public static Suffix Dim = new Suffix("Dim"); public static SuffixFormSet Dim_cIk = new SuffixFormSet(Dim, ">cI~k"); public static Suffix Dim2 = new Suffix("Dim2"); public static SuffixFormSet Dim2_cAgIz = new SuffixFormSet(Dim2, "cAğIz"); public static Suffix With = new Suffix("With"); public static SuffixFormSet With_lI = new SuffixFormSet(With, "lI"); public static Suffix Without = new Suffix("Without"); public static SuffixFormSet Without_sIz = new SuffixFormSet(Without, "sIz"); public static Suffix Rel = new Suffix("Rel"); public static SuffixFormSet Rel_ki = new SuffixFormSet(Rel, "ki"); // masa-da-ki public static SuffixFormSet Rel_kI = new SuffixFormSet(Rel, "kI"); // dünkü public static Suffix Agt = new Suffix("Agt"); public static SuffixFormSet Agt_cI = new SuffixFormSet(Agt, ">cI"); // araba-cı. Converts to another Noun. public static SuffixFormSet Agt_yIcI = new SuffixFormSet(Agt, "+yIcI"); // otur-ucu. converts to both Noun and Adj public static Suffix Ness = new Suffix("Ness"); public static SuffixFormSet Ness_lIk = new SuffixFormSet(Ness, "lI~k"); public static Suffix Become = new Suffix("Become"); public static SuffixFormSet Become_lAs = new SuffixFormSet(Become, "lAş"); public static Suffix Resemb = new Suffix("Resemb"); public static SuffixFormSet Resemb_ImsI = new SuffixFormSet(Resemb, "ImsI"); // udunumsu public static SuffixFormSet Resemb_msI = new SuffixFormSet(Resemb, "+msI"); // odunsu public static Suffix Related = new Suffix("Related"); public static SuffixFormSet Related_sAl = new SuffixFormSet(Related, "sAl"); // ---------------------------- verbal tense -------------------------------- public static Suffix Aor = new Suffix("Aor"); public static SuffixFormSet Aor_Ir = new SuffixFormSet(Aor, "+Ir"); //gel-ir public static SuffixFormSet Aor_Ar = new SuffixFormSet(Aor, "+Ar"); //ser-er public static SuffixFormSet Aor_z = new SuffixFormSet(Aor, "z"); // gel-me-z public static SuffixFormSet Aor_EMPTY = new SuffixFormSet("Aor_EMPTY", Aor, "", TerminationType.NON_TERMINAL); // gel-me--yiz public static Suffix Prog = new Suffix("Prog"); public static SuffixFormSet Prog_Iyor = new SuffixFormSet(Prog, "Iyor"); public static Suffix Prog2 = new Suffix("Prog2"); public static SuffixFormSet Prog2_mAktA = new SuffixFormSet(Prog2, "mAktA"); public static Suffix Fut = new Suffix("Fut"); public static SuffixFormSet Fut_yAcAk = new SuffixFormSet(Fut, "+yAcA~k"); public static Suffix Past = new Suffix("Past"); public static SuffixFormSet Past_dI = new SuffixFormSet(Past, ">dI"); public static Suffix Evid = new Suffix("Evid"); public static SuffixFormSet Evid_mIs = new SuffixFormSet(Evid, "mIş"); // --------------------------------------------------- public static Suffix PastPart = new Suffix("PastPart"); public static SuffixFormSet PastPart_dIk = new SuffixFormSet(PastPart, ">dI~k"); public static Suffix AorPart = new Suffix("AorPart"); // convert to an Adjective public static SuffixFormSet AorPart_Ir = new SuffixFormSet(AorPart, "+Ir"); //gel-ir public static SuffixFormSet AorPart_Ar = new SuffixFormSet(AorPart, "+Ar"); //ser-er public static SuffixFormSet AorPart_z = new SuffixFormSet(AorPart, "z"); // gel-me-z public static Suffix FutPart = new Suffix("FutPart"); public static SuffixFormSet FutPart_yAcAk = new SuffixFormSet(FutPart, "+yAcA~k"); public static Suffix EvidPart = new Suffix("EvidPart"); public static SuffixFormSet EvidPart_mIs = new SuffixFormSet(EvidPart, "mIş"); public static Suffix PresPart = new Suffix("PresPart"); public static SuffixFormSet PresPart_yAn = new SuffixFormSet(PresPart, "+yAn"); public static Suffix Pos = new Suffix("Pos"); public static SuffixFormSet Pos_EMPTY = getTemplate("Pos_EMPTY", Pos); // gel-m-iyor public static Suffix Neg = new Suffix("Neg"); public static SuffixFormSet Neg_mA = new SuffixFormSet(Neg, "mA"); //gel-me public static SuffixFormSet Neg_m = new SuffixFormSet(Neg, "m", TerminationType.NON_TERMINAL); // gel-m-iyor public static Suffix Cond = new Suffix("Cond"); public static SuffixFormSet Cond_sA = new SuffixFormSet(Cond, "sA"); public static Suffix Necess = new Suffix("Necess"); public static SuffixFormSet Necess_mAlI = new SuffixFormSet(Necess, "mAlI"); public static Suffix Opt = new Suffix("Opt"); public static SuffixFormSet Opt_yA = new SuffixFormSet(Opt, "+yA"); public static Suffix Pass = new Suffix("Pass"); public static SuffixFormSet Pass_In = new SuffixFormSet(Pass, "+In"); public static SuffixFormSet Pass_nIl = new SuffixFormSet(Pass, "+nIl"); public static Suffix Caus = new Suffix("Caus"); public static SuffixFormSet Caus_t = new SuffixFormSet(Caus, "t"); public static SuffixFormSet Caus_tIr = new SuffixFormSet(Caus, ">dIr"); public static Suffix Imp = new Suffix("Imp"); public static SuffixFormSet Imp_EMPTY = new SuffixFormSet(Imp, ""); public static SuffixFormSet Imp_EMPTY_C = new SuffixFormSet(Imp, ""); public static SuffixFormSet Imp_EMPTY_V = new SuffixFormSet(Imp, ""); public static Suffix Des = new Suffix("Des"); public static SuffixFormSet Des_sA = new SuffixFormSet(Des, "sA"); public static Suffix Recip = new Suffix("Recip"); public static SuffixFormSet Recip_Is = new SuffixFormSet(Recip, "+Iş"); public static SuffixFormSet Recip_yIs = new SuffixFormSet(Recip, "+yIş"); public static Suffix Reflex = new Suffix("Reflex"); public static SuffixFormSet Reflex_In = new SuffixFormSet(Reflex, "+In"); public static Suffix Abil = new Suffix("Abil"); public static SuffixFormSet Abil_yAbil = new SuffixFormSet(Abil, "+yAbil"); public static SuffixFormSet Abil_yA = new SuffixFormSet(Abil, "+yA", TerminationType.NON_TERMINAL); public static Suffix Cop = new Suffix("Cop"); public static SuffixFormSet Cop_dIr = new SuffixFormSet(Cop, ">dIr"); public static Suffix PastCop = new Suffix("PastCop"); public static SuffixFormSet PastCop_ydI = new SuffixFormSet(PastCop, "+y>dI"); public static Suffix EvidCop = new Suffix("EvidCop"); public static SuffixFormSet EvidCop_ymIs = new SuffixFormSet(EvidCop, "+ymIş"); public static Suffix CondCop = new Suffix("CondCop"); public static SuffixFormSet CondCop_ysA = new SuffixFormSet(CondCop, "+ysA"); public static Suffix While = new Suffix("While"); public static SuffixFormSet While_ken = new SuffixFormSet(While, "+yken"); public static Suffix Equ = new Suffix("Equ"); public static SuffixFormSet Equ_cA = new SuffixFormSet(Equ, ">cA"); public static SuffixFormSet Equ_ncA = new SuffixFormSet(Equ, "ncA"); public static Suffix NotState = new Suffix("NotState"); public static SuffixFormSet NotState_mAzlIk = new SuffixFormSet(NotState, "mAzlI~k"); public static Suffix ActOf = new Suffix("ActOf"); public static SuffixFormSet ActOf_mAcA = new SuffixFormSet(ActOf, "mAcA"); public static Suffix AsIf = new Suffix("AsIf"); public static SuffixFormSet AsIf_cAsInA = new SuffixFormSet(AsIf, ">cAsInA"); // Converts to an Adverb. public static Suffix AsLongAs = new Suffix("AsLongAs"); public static SuffixFormSet AsLongAs_dIkcA = new SuffixFormSet(AsLongAs, ">dIkçA"); public static Suffix When = new Suffix("When"); public static SuffixFormSet When_yIncA = new SuffixFormSet(When, "+yIncA"); // It also may have "worthy of doing" meaning after passive. Converts to an Adjective. public static Suffix FeelLike = new Suffix("FeelLike"); public static SuffixFormSet FeelLike_yAsI = new SuffixFormSet(FeelLike, "+yAsI"); // Converts to an Adverb. public static Suffix SinceDoing = new Suffix("SinceDoing"); public static SuffixFormSet SinceDoing_yAlI = new SuffixFormSet(SinceDoing, "+yAlI"); // Converts to an Adverb. public static Suffix ByDoing = new Suffix("ByDoing"); public static SuffixFormSet ByDoing_yArAk = new SuffixFormSet(ByDoing, "+yArAk"); // Converts to an Adverb. public static Suffix WithoutDoing = new Suffix("WithoutDoing"); public static SuffixFormSet WithoutDoing_mAdAn = new SuffixFormSet(WithoutDoing, "mAdAn"); // Converts to an Adverb. public static Suffix UntilDoing = new Suffix("UntilDoing"); public static SuffixFormSet UntilDoing_yAsIyA = new SuffixFormSet(UntilDoing, "+yAsIyA"); public static Suffix WithoutDoing2 = new Suffix("WithoutDoing2"); public static SuffixFormSet WithoutDoing2_mAksIzIn = new SuffixFormSet(WithoutDoing2, "mAksIzIn"); // Converts to an Adverb. public static Suffix AfterDoing = new Suffix("AfterDoing"); public static SuffixFormSet AfterDoing_yIp = new SuffixFormSet(AfterDoing, "+yIp"); public static Suffix UnableToDo = new Suffix("UnableToDo"); public static SuffixFormSet UnableToDo_yAmAdAn = new SuffixFormSet(UnableToDo, "+yAmAdAn"); public static Suffix InsteadOfDoing = new Suffix("InsteadOfDoing"); public static SuffixFormSet InsteadOfDoing_mAktAnsA = new SuffixFormSet(InsteadOfDoing, "mAktAnsA"); // Converts to an Adverb. public static Suffix KeepDoing = new Suffix("KeepDoing"); public static SuffixFormSet KeepDoing_yAgor = new SuffixFormSet(KeepDoing, "+yAgör"); public static Suffix KeepDoing2 = new Suffix("KeepDoing2"); public static SuffixFormSet KeepDoing2_yAdur = new SuffixFormSet(KeepDoing2, "+yAdur"); public static Suffix EverSince = new Suffix("EverSince"); public static SuffixFormSet EverSince_yAgel = new SuffixFormSet(EverSince, "+yAgel"); public static Suffix Almost = new Suffix("Almost"); public static SuffixFormSet Almost_yAyAz = new SuffixFormSet(Almost, "+yAyaz"); public static Suffix Hastily = new Suffix("Hastily"); public static SuffixFormSet Hastily_yIver = new SuffixFormSet(Hastily, "+yIver"); public static Suffix Stay = new Suffix("Stay"); public static SuffixFormSet Stay_yAkal = new SuffixFormSet(Stay, "+yAkal"); public static Suffix Inf1 = new Suffix("Inf1"); public static SuffixFormSet Inf1_mAk = new SuffixFormSet(Inf1, "mAk"); public static Suffix Inf2 = new Suffix("Inf2"); public static SuffixFormSet Inf2_mA = new SuffixFormSet(Inf2, "mA"); public static Suffix Inf3 = new Suffix("Inf3"); public static SuffixFormSet Inf3_yIs = new SuffixFormSet(Inf3, "+yIş"); public static Suffix NounDeriv = new Suffix("NounDeriv"); public static SuffixFormSet NounDeriv_nIm = new SuffixFormSet(NounDeriv, "+nIm"); public static Suffix Ly = new Suffix("Ly"); public static SuffixFormSet Ly_cA = new SuffixFormSet(Ly, ">cA"); public static Suffix Quite = new Suffix("Quite"); public static SuffixFormSet Quite_cA = new SuffixFormSet(Quite, ">cA"); public static Suffix Ordinal = new Suffix("Ordinal"); public static SuffixFormSet Ordinal_IncI = new SuffixFormSet(Ordinal, "+IncI"); public static Suffix Grouping = new Suffix("Grouping"); public static SuffixFormSet Grouping_sAr = new SuffixFormSet(Grouping, "+şAr"); public static Suffix NounRoot = new Suffix("Noun"); public static SuffixFormSet Noun_Main = new SuffixFormSet("Noun_Main", NounRoot, ""); public static SuffixFormSet Noun_Default = getNull("Noun_Default", NounRoot); public static SuffixFormSet Noun_Comp_P3sg = getNull("Noun_Comp_P3sg", NounRoot); public static SuffixFormSet Noun_Comp_P3sg_Root = getNull("Noun_Comp_P3sg_Root", NounRoot); public static Suffix AdjRoot = new Suffix("Adj"); public static SuffixFormSet Adj_Main = getTemplate("Adj_Main", AdjRoot); public static SuffixFormSet Adj_Main_Rel = getNull("Adj_Main", AdjRoot); public static SuffixFormSet Adj_Default = getNull("Adj_Default", AdjRoot); public static Suffix AdvRoot = new Suffix("AdvRoot"); public static SuffixFormSet Adv_Main = getTemplate("Adv_Main", AdvRoot); public static SuffixFormSet Adv_Default = getTemplate("Adv_Default", AdvRoot); public static Suffix InterjRoot = new Suffix("Interj"); public static SuffixFormSet Interj_Main = getTemplate("Interj_Main", InterjRoot); public static Suffix ConjRoot = new Suffix("Conj"); public static SuffixFormSet Conj_Main = getTemplate("Conj_Main", ConjRoot); public static Suffix NumeralRoot = new Suffix("Numeral"); public static SuffixFormSet Numeral_Main = getTemplate("Numeral_Main", NumeralRoot); public static Suffix DetRoot = new Suffix("Det"); public static SuffixFormSet Det_Main = getTemplate("Det_Main", DetRoot); public static Suffix ProperNounRoot = new Suffix("ProperNounRoot"); public static SuffixFormSet ProperNoun_Main = getTemplate("ProperNoun_Main", ProperNounRoot); public static Suffix VerbRoot = new Suffix("Verb"); public static SuffixFormSet Verb_Main = getTemplate("Verb_Main", VerbRoot); public static SuffixFormSet Verb_Zero = getTemplate("Verb_Zero", VerbRoot); // Zero morphem derivation. public static SuffixFormSet Verb_Default = getNull("Verb_Default", VerbRoot); public static SuffixFormSet Verb_Prog_Drop = new SuffixFormSet("Verb_Prog_Drop", VerbRoot, ""); public static Suffix PersPronRoot = new Suffix("PersPron"); public static SuffixFormSet PersPron_Main = getTemplate("PersPron_Main", PersPronRoot); public static SuffixFormSet PersPron_BenSen = getTemplate("PersPron_BenSen", PersPronRoot); public static SuffixFormSet PersPron_BanSan = getTemplate("PersPron_BanSan", PersPronRoot); public static Suffix QuesRoot = new Suffix("Ques"); public static SuffixFormSet Ques_mI = getTemplate("Ques_mI", QuesRoot); public static Suffix ParticleRoot = new Suffix("Particle"); public static SuffixFormSet Particle_Main = getTemplate("Particle_Main", ParticleRoot); // TODO: add time root. (with Rel_ki + Noun) public static final SuffixFormSet[] CASE_FORMS = {Nom_EMPTY, Dat_yA, Loc_dA, Abl_dAn, Gen_nIn, Acc_yI, Inst_ylA, Equ_cA}; public static final SuffixFormSet[] POSSESSIVE_FORMS = {Pnon_EMPTY, P1sg_Im, P2sg_In, P3sg_sI, P1pl_ImIz, P2pl_InIz, P3pl_lArI}; public static final SuffixFormSet[] PERSON_FORMS_N = {A1sg_yIm, A2sg_sIn, A3sg_EMPTY, A1pl_yIz, A2pl_sInIz, A3pl_lAr}; public static final SuffixFormSet[] PERSON_FORMS_COP = {A1sg_m, A2sg_n, A3sg_EMPTY, A1pl_k, A2pl_nIz, A3pl_lAr}; public static final SuffixFormSet[] COPULAR_FORMS = {Cop_dIr, PastCop_ydI, EvidCop_ymIs, CondCop_ysA, While_ken}; public TurkishSuffixes() { // noun template. it has all possible suffix forms that a noun can follow Noun_Main.directSuccessors.add(A3pl_lAr, A3pl_Comp_lAr, A3sg_EMPTY); Noun_Main.successors.add(POSSESSIVE_FORMS, CASE_FORMS) .add(Dat_nA, Loc_ndA, Abl_ndAn, Acc_nI, Equ_ncA) .add(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI, Ness_lIk, Related_sAl) .add(Become_lAs); // default noun suffix form. we remove some suffixes so that words like araba-na (dative) Noun_Default.directSuccessors.add(A3pl_lAr, A3sg_EMPTY); Noun_Default.successors.add(Noun_Main.successors) .remove(Dat_nA, Loc_ndA, Abl_ndAn, Acc_nI); // P3sg compound suffixes. (full form. such as zeytinyağı-na) Noun_Comp_P3sg.directSuccessors.add(A3sg_EMPTY); Noun_Comp_P3sg.successors.add(POSSESSIVE_FORMS) .add(Pnon_EMPTY, Nom_EMPTY) .add(Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA) .add(A1sg_yIm, A1pl_yIz, A2sg_sIn, A2pl_sInIz); // P3sg compound suffixes. (root form. such as zeytinyağ-lar-ı) Noun_Comp_P3sg_Root.directSuccessors.add(A3pl_Comp_lAr, A3sg_EMPTY); // A3pl_Comp_lAr is used, because zeytinyağ-lar is not allowed. Noun_Comp_P3sg_Root.successors.add(Pnon_EMPTY, Nom_EMPTY, With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI, Ness_lIk, Related_sAl, Dim_cIk) .add(P3pl_lArI); // Proper noun default //TODO: should be a template ProperNoun_Main.directSuccessors.add(A3pl_lAr, A3sg_EMPTY); ProperNoun_Main.successors.add(CASE_FORMS, POSSESSIVE_FORMS) .add(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, A3sg_EMPTY, Agt_cI, Ness_lIk); A3pl_lAr.directSuccessors.add(POSSESSIVE_FORMS).remove(P3pl_lArI); A3pl_lAr.successors.add(CASE_FORMS) .add(A1pl_yIz, A2pl_sInIz); //TODO: check below. A3pl_Comp_lAr.directSuccessors.add(A3pl_lAr.directSuccessors); A3pl_Comp_lAr.successors.add(CASE_FORMS) .add(A1pl_yIz, A2pl_sInIz); A3sg_EMPTY.directSuccessors.add(POSSESSIVE_FORMS); A3sg_EMPTY.successors.add(Noun_Main.successors).remove(POSSESSIVE_FORMS); Nom_EMPTY.directSuccessors.add(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI) .add(Ness_lIk, Related_sAl, Become_lAs, Equ_cA); Dim_cIk.directSuccessors.add(Noun_Main); Dim_cIk.successors.add(Noun_Main.allSuccessors().remove(Dim_cIk, Dim2_cAgIz)); Dim2_cAgIz.directSuccessors.add(Noun_Main); Dim2_cAgIz.successors.add(Noun_Main.allSuccessors().remove(Dim_cIk, Dim2_cAgIz)); Pnon_EMPTY.directSuccessors.add(CASE_FORMS) .add(Dat_nA, Loc_ndA, Abl_ndAn, Acc_nI); Pnon_EMPTY.successors.add(Nom_EMPTY.directSuccessors); P1sg_Im.directSuccessors.add(CASE_FORMS); P2sg_In.directSuccessors.add(CASE_FORMS); P3sg_sI.directSuccessors.add(Nom_EMPTY, Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA, Equ_ncA); P1pl_ImIz.directSuccessors.add(CASE_FORMS); P2pl_InIz.directSuccessors.add(CASE_FORMS); P3pl_lArI.directSuccessors.add(CASE_FORMS); With_lI.directSuccessors.add(Adj_Main); With_lI.successors.add(Adj_Main.directSuccessors); Without_sIz.directSuccessors.add(Adj_Main); Without_sIz.successors.add(Adj_Main.directSuccessors); Loc_dA.directSuccessors.add(Rel_ki); Rel_ki.directSuccessors.add(Adj_Main_Rel); Resemb_msI.directSuccessors.add(Adj_Main); Resemb_msI.successors.add(Adj_Main.allSuccessors()); Resemb_ImsI.directSuccessors.add(Adj_Main); Resemb_ImsI.successors.add(Adj_Main.allSuccessors()); //---------------------------- Adjective ----------------------------------------------------------------------- Adj_Main.directSuccessors.add(Ly_cA, Become_lAs, Quite_cA, Resemb_ImsI, Resemb_msI); Adj_Main.successors.add(Noun_Main.allSuccessors().remove(Related_sAl)); Adj_Default.directSuccessors.add(Adj_Main.directSuccessors); Adj_Default.successors.add(Adj_Main.getSuccessors()); Adj_Main_Rel.directSuccessors.add(Adj_Main.directSuccessors); Adj_Main_Rel.successors.add(Adj_Main.getSuccessors()); Become_lAs.directSuccessors.add(Verb_Main); Become_lAs.successors.add(Verb_Main.allSuccessors()); Quite_cA.directSuccessors.add(Adj_Main); Ly_cA.directSuccessors.add(Adv_Main); //---------------------------- Verb ---------------------------------------------------------------------------- Verb_Main.directSuccessors.add(Neg_mA, Neg_m, Pos_EMPTY, Caus_t, Caus_tIr, Pass_In, Pass_nIl); Verb_Main.successors.add(Prog_Iyor, Prog2_mAktA, Fut_yAcAk, Past_dI, Evid_mIs, Aor_Ir, AorPart_Ir) .add(Abil_yAbil, Abil_yA, Caus_tIr, Opt_yA, Imp_EMPTY, Agt_yIcI, Des_sA) .add(NotState_mAzlIk, ActOf_mAcA, PastPart_dIk, EvidPart_mIs) .add(FutPart_yAcAk, PresPart_yAn, AsLongAs_dIkcA) .add(Inf1_mAk, Inf2_mA, Inf3_yIs) .add(When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing_mAdAn, WithoutDoing2_mAksIzIn) .add(AfterDoing_yIp, When_yIncA, UnableToDo_yAmAdAn, InsteadOfDoing_mAktAnsA) .add(KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Almost_yAyAz, Hastily_yIver, Stay_yAkal, Recip_Is) .add(NounDeriv_nIm, UntilDoing_yAsIyA); - Verb_Default.directSuccessors.add(Verb_Main.directSuccessors).remove(Pass_nIl); + Verb_Default.directSuccessors.add(Verb_Main.directSuccessors); Verb_Default.successors.add(Verb_Main.successors); Pos_EMPTY.directSuccessors.add(Imp_EMPTY); Pos_EMPTY.successors.add(Verb_Default.successors).remove(Neg_m, Neg_mA); Neg_mA.directSuccessors.add(Aor_z, AorPart_z, Aor_EMPTY, Prog2_mAktA, Imp_EMPTY, Opt_yA, Des_sA, Fut_yAcAk, Past_dI, Evid_mIs, Cond_sA, Abil_yAbil, Necess_mAlI, NotState_mAzlIk, ActOf_mAcA, PastPart_dIk, FutPart_yAcAk, EvidPart_mIs, Agt_yIcI) .add(AsLongAs_dIkcA, PresPart_yAn) .add(Inf1_mAk, Inf2_mA, Inf3_yIs) .add(When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing2_mAksIzIn) .add(AfterDoing_yIp, When_yIncA, InsteadOfDoing_mAktAnsA) .add(KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Hastily_yIver); Imp_EMPTY.directSuccessors.add(A2sg_EMPTY, A2sg2_sAnA, A2sg3_yInIz, A2pl2_sAnIzA, A2pl_yIn, A3sg_sIn, A3pl_sInlAr); Caus_t.directSuccessors.add(Verb_Main); Caus_t.successors.add(Verb_Main.allSuccessors()).add(Pass_nIl).remove(Caus_t); Caus_tIr.directSuccessors.add(Verb_Main); Caus_tIr.successors.add(Verb_Main.allSuccessors()).add(Pass_nIl).remove(Caus_tIr); Pass_nIl.directSuccessors.add(Verb_Main); Pass_nIl.directSuccessors.add(Verb_Main.allSuccessors()).remove(Caus_t, Caus_tIr, Pass_nIl, Pass_In); registerForms( Noun_Default, Nom_EMPTY, Verb_Default, Pnon_EMPTY, Dat_yA, Dat_nA, Loc_dA, Loc_ndA, Abl_dAn, Abl_ndAn, Gen_nIn, Acc_yI, Acc_nI, Inst_ylA, P1sg_Im, P2sg_In, P3sg_sI, P1pl_ImIz, P2pl_InIz, P3pl_lArI, Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Rel_ki, Rel_kI, A1sg_yIm, A1sg_m, A1sg_EMPTY, A2sg_sIn, A2sg_n, A2sg_EMPTY, A2sg2_sAnA, A2sg3_yInIz, A3sg_EMPTY, A3sg_sIn, A1pl_yIz, A1pl_k, A1pl_lIm, A1pl_EMPTY, A2pl_sInIz, A2pl_nIz, A2pl_yIn, A2pl_EMPTY, A2pl2_sAnIzA, A3pl_lAr, A3pl_sInlAr, Agt_cI, Agt_yIcI, Ness_lIk, Become_lAs, Resemb_ImsI, Resemb_msI, Related_sAl, Aor_Ir, Aor_Ar, Aor_z, Des_sA, Aor_EMPTY, AorPart_Ir, AorPart_Ar, AorPart_z, Prog_Iyor, Prog2_mAktA, Fut_yAcAk, FutPart_yAcAk, Past_dI, PastPart_dIk, Evid_mIs, EvidPart_mIs, PresPart_yAn, Neg_mA, Neg_m, Cond_sA, Necess_mAlI, Opt_yA, Pass_In, Pass_nIl, Caus_t, Caus_tIr, Imp_EMPTY, Imp_EMPTY_V, Imp_EMPTY_C, Recip_Is, Recip_yIs, Reflex_In, Abil_yAbil, Abil_yA, Cop_dIr, PastCop_ydI, EvidCop_ymIs, CondCop_ysA, While_ken, NotState_mAzlIk, ActOf_mAcA, AsIf_cAsInA, AsLongAs_dIkcA, When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing_mAdAn, WithoutDoing2_mAksIzIn, AfterDoing_yIp, UnableToDo_yAmAdAn, InsteadOfDoing_mAktAnsA, KeepDoing_yAgor, KeepDoing2_yAdur, EverSince_yAgel, Almost_yAyAz, Hastily_yIver, Stay_yAkal, Inf1_mAk, Inf2_mA, Inf3_yIs, Ly_cA, Quite_cA, Equ_cA, Equ_ncA, UntilDoing_yAsIyA, Noun_Main, Noun_Comp_P3sg, Noun_Comp_P3sg_Root, A3pl_Comp_lAr, Adj_Main, Adv_Main, Adj_Main_Rel, Interj_Main, Verb_Main, Verb_Prog_Drop, PersPron_Main, PersPron_BenSen, PersPron_BanSan, Numeral_Main, Ordinal_IncI, Grouping_sAr, Ques_mI, Particle_Main, NounDeriv_nIm); /* Noun_Main.add(CASE_FORMS, POSSESSIVE_FORMS, COPULAR_FORMS, PERSON_FORMS_N) .add(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI, Ness_lIk, Related_sAl, Become_lAs, Equ_cA); Noun_Exp_V.add(Dat_yA, Acc_yI, Gen_nIn, P1sg_Im, P2sg_In, P3sg_sI, P1pl_ImIz, P2pl_InIz, A1sg_yIm, A1pl_yIz, Resemb_ImsI); Noun_Exp_C.add(Noun_Main.getSuccSetCopy()).remove(Noun_Exp_V.getSuccSetCopy()); Noun_Comp_P3sg.add(COPULAR_FORMS, POSSESSIVE_FORMS) .add(Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA) .add(A1sg_yIm, A1pl_yIz, A2sg_sIn, A2pl_sInIz); Noun_Comp_P3sg_Root.add(With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI, Ness_lIk, Related_sAl, P1sg_Im, P2sg_In, P1pl_ImIz, P2pl_InIz, P3pl_lArI, A3pl_Comp_lAr); ProperNoun_Main .add(CASE_FORMS, POSSESSIVE_FORMS, COPULAR_FORMS, PERSON_FORMS_N) .add(Pl_lAr, Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, A3sg_EMPTY, Agt_cI, Ness_lIk); Verb_Main.add(Prog_Iyor, Prog2_mAktA, Fut_yAcAk, Past_dI, Evid_mIs, Aor_Ir, AorPart_Ir) .add(Neg_mA, Neg_m, Abil_yAbil, Abil_yA, Caus_tIr, Opt_yA, Imp_EMPTY, Agt_yIcI, Des_sA) .add(Pass_nIl, NotState_mAzlIk, ActOf_mAcA, PastPart_dIk, EvidPart_mIs) .add(FutPart_yAcAk, PresPart_yAn, AsLongAs_dIkcA) .add(Inf1_mAk, Inf2_mA, Inf3_yIs) .add(When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing_mAdAn, WithoutDoing2_mAksIzIn) .add(AfterDoing_yIp, When_yIncA, UnableToDo_yAmAdAn, InsteadOfDoing_mAktAnsA) .add(KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Almost_yAyAz, Hastily_yIver, Stay_yAkal, Recip_Is) .add(NounDeriv_nIm, UntilDoing_yAsIyA); Verb_Exp_V.add(Opt_yA, Fut_yAcAk, Aor_Ar, AorPart_Ar, Prog_Iyor, PresPart_yAn, Pass_nIl, KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Almost_yAyAz, Hastily_yIver, Stay_yAkal, When_yIncA, UnableToDo_yAmAdAn, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, Inf3_yIs, Abil_yA, Abil_yAbil, AfterDoing_yIp, Agt_yIcI, FutPart_yAcAk, Imp_EMPTY_V).remove(Imp_EMPTY); Verb_Exp_C.add(Verb_Main.getSuccSetCopy()) .remove(Verb_Exp_V.getSuccSetCopy()).remove(Aor_Ir, AorPart_Ir, Imp_EMPTY) .add(Imp_EMPTY_V); Verb_Prog_Drop.add(Prog_Iyor); Adv_Main.add(COPULAR_FORMS); PersPron_Main.add(CASE_FORMS).add(PastCop_ydI, EvidCop_ymIs, CondCop_ysA, While_ken); PersPron_BenSen.add(PersPron_Main.getSuccSetCopy()).remove(Dat_yA); PersPron_BanSan.add(Dat_yA); Ques_mI.add(PERSON_FORMS_N).add(Cop_dIr, EvidCop_ymIs, PastCop_ydI); Adj_Main.add(Noun_Main.getSuccSetCopy()).add(Ly_cA, Become_lAs, Quite_cA).remove(Related_sAl); Adj_Exp_C.add(Noun_Exp_C.getSuccSetCopy()).add(Ly_cA, Become_lAs, Quite_cA); Adj_Exp_V.add(Noun_Exp_V.getSuccSetCopy()); Become_lAs.add(Verb_Main.getSuccSetCopy()); Quite_cA.add(Noun_Main.getSuccSetCopy()).remove(Related_sAl); Numeral_Main.add(COPULAR_FORMS, CASE_FORMS, POSSESSIVE_FORMS, PERSON_FORMS_N) .add(Ordinal_IncI, Grouping_sAr, With_lI, Without_sIz, Ness_lIk, Pl_lAr); Ordinal_IncI.add(Numeral_Main.getSuccSetCopy()).remove(Ordinal_IncI, Grouping_sAr); Grouping_sAr.add(With_lI, Ness_lIk, Abl_dAn).add(COPULAR_FORMS); Pl_lAr.add(CASE_FORMS, COPULAR_FORMS) .add(P1sg_Im, P2sg_In, P1pl_ImIz, P2pl_InIz, A1pl_yIz, A2pl_sInIz, Equ_cA); P1sg_Im.add(CASE_FORMS, COPULAR_FORMS).add(A2sg_sIn, A1pl_yIz, A2pl_sInIz, A3sg_EMPTY, Equ_cA); P2sg_In.add(CASE_FORMS, COPULAR_FORMS).add(A1sg_yIm, A1pl_yIz, A3sg_EMPTY, Equ_cA); P3sg_sI.add(COPULAR_FORMS) .add(Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA) .add(A1sg_yIm, A1pl_yIz, A2sg_sIn, A2pl_sInIz, A3sg_EMPTY, Equ_ncA); P1pl_ImIz.add(CASE_FORMS, COPULAR_FORMS).add(A1sg_yIm, A2sg_sIn, A3sg_EMPTY, Equ_cA, A2pl_sInIz); P2pl_InIz.add(CASE_FORMS, COPULAR_FORMS).add(A1sg_yIm, A2sg_sIn, A1pl_yIz, A2pl_sInIz, A3sg_EMPTY, Equ_cA); P3pl_lArI.add(P3sg_sI.getSuccSetCopy()).add(A1sg_yIm, A2sg_sIn, A3sg_EMPTY, A1pl_yIz, A2pl_sInIz, Equ_ncA); Rel_ki.add(COPULAR_FORMS, PERSON_FORMS_N).add(Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA, Pl_lAr); Rel_kI.add(Rel_ki.getSuccSetCopy()); Dat_yA.add(COPULAR_FORMS); Dat_nA.add(COPULAR_FORMS); Loc_dA.add(COPULAR_FORMS, PERSON_FORMS_N).add(Rel_ki); Loc_ndA.add(COPULAR_FORMS, PERSON_FORMS_N).add(Rel_ki); Inst_ylA.add(COPULAR_FORMS, PERSON_FORMS_N, POSSESSIVE_FORMS); Abl_dAn.add(COPULAR_FORMS, PERSON_FORMS_N); Abl_ndAn.add(COPULAR_FORMS, PERSON_FORMS_N); Gen_nIn.add(COPULAR_FORMS, PERSON_FORMS_N).add(Rel_ki); A1sg_yIm.add(Cop_dIr); A2sg_sIn.add(Cop_dIr); A3sg_EMPTY.add(Cop_dIr); A1pl_yIz.add(Cop_dIr); A2pl_sInIz.add(Cop_dIr); A3pl_lAr.add(Pl_lAr.getSuccSetCopy()); A3pl_Comp_lAr.add(Pl_lAr.getSuccSetCopy()); Dim_cIk.add(Loc_dA, Abl_dAn, Inst_ylA, P3pl_lArI, A2sg_sIn, A2pl_sInIz, A3pl_lAr, Pl_lAr, Inst_ylA).add(COPULAR_FORMS); Dim2_cAgIz.add(CASE_FORMS, COPULAR_FORMS, POSSESSIVE_FORMS, PERSON_FORMS_N).add(Pl_lAr); With_lI.add(CASE_FORMS, COPULAR_FORMS, POSSESSIVE_FORMS, PERSON_FORMS_N).add(Pl_lAr, Ness_lIk, Become_lAs, Ly_cA); Without_sIz.add(CASE_FORMS, COPULAR_FORMS, POSSESSIVE_FORMS, PERSON_FORMS_N).add(Pl_lAr, Ness_lIk, Become_lAs, Ly_cA); Resemb_msI.add(CASE_FORMS, PERSON_FORMS_N, COPULAR_FORMS, POSSESSIVE_FORMS) .add(Pl_lAr, Ness_lIk, With_lI, Without_sIz, Become_lAs); Resemb_ImsI.add(Resemb_ImsI.getSuccSetCopy()); Ness_lIk.add(CASE_FORMS, POSSESSIVE_FORMS, COPULAR_FORMS, CASE_FORMS).add(Pl_lAr, Agt_cI, With_lI, Without_sIz, Equ_cA); Related_sAl.add(Adj_Main.getSuccSetCopy()).remove(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Related_sAl, Resemb_msI, Resemb_msI); PastCop_ydI.add(PERSON_FORMS_COP); EvidCop_ymIs.add(A1sg_yIm, A2sg_sIn, A3sg_EMPTY, A1pl_yIz, A2pl_sInIz, A3pl_lAr, AsIf_cAsInA); CondCop_ysA.add(PERSON_FORMS_COP); Cop_dIr.add(A3pl_lAr); Neg_mA.add(Aor_z, AorPart_z, Aor_EMPTY, Prog2_mAktA, Imp_EMPTY, Opt_yA, Des_sA, Fut_yAcAk, Past_dI, Evid_mIs, Cond_sA, Abil_yAbil, Necess_mAlI, NotState_mAzlIk, ActOf_mAcA, PastPart_dIk, FutPart_yAcAk, EvidPart_mIs, Agt_yIcI) .add(AsLongAs_dIkcA, PresPart_yAn) .add(Inf1_mAk, Inf2_mA, Inf3_yIs) .add(When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing2_mAksIzIn) .add(AfterDoing_yIp, When_yIncA, InsteadOfDoing_mAktAnsA) .add(KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Hastily_yIver); Neg_m.add(Prog_Iyor); Aor_Ar.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA); Aor_Ir.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA); Aor_z.add(COPULAR_FORMS).add(A3sg_sIn, Cond_sA); Aor_EMPTY.add(A1sg_m, A1pl_yIz); Set<SuffixFormSet> noParticipleSuff = Sets.newHashSet(Become_lAs, Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Related_sAl, Resemb_msI, Resemb_msI); AorPart_Ar.add(Adj_Main.getSuccSetCopy()).remove(noParticipleSuff).add(AsIf_cAsInA); AorPart_Ir.add(AorPart_Ar.getSuccSetCopy()); AorPart_z.add(AorPart_Ar.getSuccSetCopy()); FutPart_yAcAk.add(Adj_Exp_C.getSuccSetCopy()); NotState_mAzlIk.add(Adj_Exp_C.getSuccSetCopy()); PresPart_yAn.add(AorPart_Ar.getSuccSetCopy()); EvidPart_mIs.add(AorPart_Ar.getSuccSetCopy()); PastPart_dIk.add(Adj_Exp_C.getSuccSetCopy()).remove(AsIf_cAsInA).remove(noParticipleSuff); Prog_Iyor.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA); Prog2_mAktA.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA); Fut_yAcAk.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA, AsIf_cAsInA); Past_dI.add(A1sg_m, A2sg_n, A3sg_EMPTY, A1pl_k, A2pl_nIz, A3pl_lAr, CondCop_ysA, PastCop_ydI); Evid_mIs.add(PERSON_FORMS_N).add(CondCop_ysA, PastCop_ydI, EvidCop_ymIs, While_ken, Cop_dIr); Cond_sA.add(A1sg_m, A2sg_n, A3sg_EMPTY, A1pl_k, A2pl_nIz, A3pl_lAr, PastCop_ydI, EvidCop_ymIs); Imp_EMPTY.add(A2sg_EMPTY, A2sg2_sAnA, A2sg3_yInIz, A2pl2_sAnIzA, A2pl_yIn, A3sg_sIn, A3pl_sInlAr); Imp_EMPTY_C.add(A2sg_EMPTY, A2sg2_sAnA, A2pl2_sAnIzA, A3sg_sIn, A3pl_sInlAr); Imp_EMPTY_V.add(A2sg3_yInIz, A2pl_yIn); Agt_cI.add(CASE_FORMS, PERSON_FORMS_N, POSSESSIVE_FORMS, COPULAR_FORMS).add(Pl_lAr, Become_lAs, With_lI, Without_sIz, Ness_lIk); Agt_yIcI.add(Agt_cI.getSuccSetCopy()); Abil_yAbil.add(Verb_Main.getSuccSetCopy()).remove(Abil_yAbil, Abil_yA, Neg_mA, Pass_nIl).add(Cond_sA, Pass_In); Abil_yA.add(Neg_mA, Neg_m); Opt_yA.add(A1sg_yIm, A2sg_sIn, A3sg_EMPTY, A1pl_lIm, A2pl_sInIz, A3pl_lAr); Des_sA.add(COPULAR_FORMS).add(A1sg_m, A2sg_n, A3sg_EMPTY, A1pl_k, A2pl_nIz, A3pl_lAr, PastCop_ydI, EvidCop_ymIs); Caus_t.add(Verb_Main.getSuccSetCopy()).add(Pass_nIl); Caus_tIr.add(Verb_Main.getSuccSetCopy()).remove(Caus_tIr).add(Caus_t, Pass_nIl); Pass_nIl.add(Verb_Main.getSuccSetCopy()).remove(Pass_In, Pass_nIl, Caus_tIr).add(Caus_t); Pass_In.add(Verb_Main.getSuccSetCopy()).remove(Pass_In); Reflex_In.add(Verb_Main.getSuccSetCopy()); Recip_Is.add(Verb_Main.getSuccSetCopy()).remove(Recip_Is); Recip_yIs.add(Verb_Main.getSuccSetCopy()).remove(Recip_Is); Inf1_mAk.add(COPULAR_FORMS).add(Abl_dAn, Loc_dA, Inst_ylA); Inf2_mA.add(Noun_Main.getSuccessors()); Inf3_yIs.add(Noun_Main.getSuccessors()); NounDeriv_nIm.add(Noun_Main.getSuccSetCopy()); When_yIncA.add(Dat_yA); While_ken.add(Rel_ki).add(PastCop_ydI, EvidCop_ymIs, CondCop_ysA); FeelLike_yAsI.add(POSSESSIVE_FORMS).add(COPULAR_FORMS); KeepDoing_yAgor.add(Neg_mA.getSuccSetCopy()).remove(Aor_z).add(Neg_mA, Neg_m, Aor_Ir, Prog_Iyor); KeepDoing2_yAdur.add(KeepDoing_yAgor.getSuccSetCopy()); EverSince_yAgel.add(KeepDoing_yAgor.getSuccSetCopy()); Almost_yAyAz.add(KeepDoing_yAgor.getSuccSetCopy()); Hastily_yIver.add(KeepDoing_yAgor.getSuccSetCopy()); Stay_yAkal.add(KeepDoing_yAgor.getSuccSetCopy()); Necess_mAlI.add(COPULAR_FORMS, PERSON_FORMS_N); */ } @Override public SuffixFormSet getRootSet(DictionaryItem item, SuffixData successorConstraint) { if (successorConstraint.isEmpty()) { switch (item.primaryPos) { case Noun: return Noun_Default; case Adjective: return Adj_Default; case Verb: return Verb_Default; case Adverb: return Adv_Default; default: return Noun_Default; } } else { switch (item.primaryPos) { case Noun: SuffixFormSet copyOfTemplate = Noun_Main.copy(idMaker.getNew(Noun_Main.id)); return getRootFormSet(successorConstraint, copyOfTemplate); case Adjective: copyOfTemplate = Adj_Main.copy(idMaker.getNew(Adj_Main.id)); return getRootFormSet(successorConstraint, copyOfTemplate); case Verb: copyOfTemplate = Verb_Main.copy(idMaker.getNew(Verb_Main.id)); return getRootFormSet(successorConstraint, copyOfTemplate); default: copyOfTemplate = Noun_Main.copy(idMaker.getNew(Noun_Main.id)); return getRootFormSet(successorConstraint, copyOfTemplate); } } } private SuffixFormSet getRootFormSet(SuffixData successorConstraint, SuffixFormSet copyOfTemplate) { copyOfTemplate.directSuccessors.retain(successorConstraint); copyOfTemplate.successors.retain(successorConstraint); if (formSetLookup.containsKey(copyOfTemplate)) { copyOfTemplate = formSetLookup.get(copyOfTemplate); } else { registerForm(copyOfTemplate); } return copyOfTemplate; } @Override public SuffixData[] defineSuccessorSuffixes(DictionaryItem item) { SuffixData original = new SuffixData(); SuffixData modified = new SuffixData(); PrimaryPos primaryPos = item.primaryPos; switch (primaryPos) { case Noun: getForNoun(item, original, modified); break; case Verb: getForVerb(item, original, modified); break; default: getForNoun(item, original, modified); } return new SuffixData[]{original, modified}; } private void getForNoun(DictionaryItem item, SuffixData original, SuffixData modified) { for (RootAttr attribute : item.attrs.getAsList(RootAttr.class)) { switch (attribute) { case CompoundP3sg: original.add(Noun_Comp_P3sg.allSuccessors()); modified.clear().add(Noun_Comp_P3sg_Root.allSuccessors()); break; default: break; } } } private void getForVerb(DictionaryItem item, SuffixData original, SuffixData modified) { for (RootAttr attribute : item.attrs.getAsList(RootAttr.class)) { switch (attribute) { case Aorist_A: original.add(Aor_Ar, AorPart_Ar); original.remove(Aor_Ir, AorPart_Ir); modified.add(Aor_Ar, AorPart_Ar); modified.remove(Aor_Ir, AorPart_Ir); break; case Aorist_I: original.add(Aor_Ir, AorPart_Ir); original.remove(Aor_Ar, AorPart_Ar); modified.add(Aor_Ir, AorPart_Ir); modified.remove(Aor_Ar, AorPart_Ar); break; case Passive_In: original.add(Pass_In); original.remove(Pass_nIl); break; case LastVowelDrop: original.remove(Pass_nIl); modified.clear().add(Pass_nIl); break; /* case VoicingOpt: modified.remove(Verb_Exp_C.getSuccessors()); break;*/ case ProgressiveVowelDrop: original.add(Prog_Iyor); modified.clear().add(Prog_Iyor); break; case NonTransitive: original.remove(Caus_t, Caus_tIr); modified.remove(Caus_t, Caus_tIr); break; case Reflexive: original.add(Reflex_In); modified.add(Reflex_In); break; case Reciprocal: original.add(Recip_Is); modified.add(Recip_Is); break; case Causative_t: original.remove(Caus_tIr); original.add(Caus_t); modified.remove(Caus_tIr); modified.add(Caus_t); break; default: break; } } } }
true
true
public TurkishSuffixes() { // noun template. it has all possible suffix forms that a noun can follow Noun_Main.directSuccessors.add(A3pl_lAr, A3pl_Comp_lAr, A3sg_EMPTY); Noun_Main.successors.add(POSSESSIVE_FORMS, CASE_FORMS) .add(Dat_nA, Loc_ndA, Abl_ndAn, Acc_nI, Equ_ncA) .add(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI, Ness_lIk, Related_sAl) .add(Become_lAs); // default noun suffix form. we remove some suffixes so that words like araba-na (dative) Noun_Default.directSuccessors.add(A3pl_lAr, A3sg_EMPTY); Noun_Default.successors.add(Noun_Main.successors) .remove(Dat_nA, Loc_ndA, Abl_ndAn, Acc_nI); // P3sg compound suffixes. (full form. such as zeytinyağı-na) Noun_Comp_P3sg.directSuccessors.add(A3sg_EMPTY); Noun_Comp_P3sg.successors.add(POSSESSIVE_FORMS) .add(Pnon_EMPTY, Nom_EMPTY) .add(Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA) .add(A1sg_yIm, A1pl_yIz, A2sg_sIn, A2pl_sInIz); // P3sg compound suffixes. (root form. such as zeytinyağ-lar-ı) Noun_Comp_P3sg_Root.directSuccessors.add(A3pl_Comp_lAr, A3sg_EMPTY); // A3pl_Comp_lAr is used, because zeytinyağ-lar is not allowed. Noun_Comp_P3sg_Root.successors.add(Pnon_EMPTY, Nom_EMPTY, With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI, Ness_lIk, Related_sAl, Dim_cIk) .add(P3pl_lArI); // Proper noun default //TODO: should be a template ProperNoun_Main.directSuccessors.add(A3pl_lAr, A3sg_EMPTY); ProperNoun_Main.successors.add(CASE_FORMS, POSSESSIVE_FORMS) .add(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, A3sg_EMPTY, Agt_cI, Ness_lIk); A3pl_lAr.directSuccessors.add(POSSESSIVE_FORMS).remove(P3pl_lArI); A3pl_lAr.successors.add(CASE_FORMS) .add(A1pl_yIz, A2pl_sInIz); //TODO: check below. A3pl_Comp_lAr.directSuccessors.add(A3pl_lAr.directSuccessors); A3pl_Comp_lAr.successors.add(CASE_FORMS) .add(A1pl_yIz, A2pl_sInIz); A3sg_EMPTY.directSuccessors.add(POSSESSIVE_FORMS); A3sg_EMPTY.successors.add(Noun_Main.successors).remove(POSSESSIVE_FORMS); Nom_EMPTY.directSuccessors.add(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI) .add(Ness_lIk, Related_sAl, Become_lAs, Equ_cA); Dim_cIk.directSuccessors.add(Noun_Main); Dim_cIk.successors.add(Noun_Main.allSuccessors().remove(Dim_cIk, Dim2_cAgIz)); Dim2_cAgIz.directSuccessors.add(Noun_Main); Dim2_cAgIz.successors.add(Noun_Main.allSuccessors().remove(Dim_cIk, Dim2_cAgIz)); Pnon_EMPTY.directSuccessors.add(CASE_FORMS) .add(Dat_nA, Loc_ndA, Abl_ndAn, Acc_nI); Pnon_EMPTY.successors.add(Nom_EMPTY.directSuccessors); P1sg_Im.directSuccessors.add(CASE_FORMS); P2sg_In.directSuccessors.add(CASE_FORMS); P3sg_sI.directSuccessors.add(Nom_EMPTY, Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA, Equ_ncA); P1pl_ImIz.directSuccessors.add(CASE_FORMS); P2pl_InIz.directSuccessors.add(CASE_FORMS); P3pl_lArI.directSuccessors.add(CASE_FORMS); With_lI.directSuccessors.add(Adj_Main); With_lI.successors.add(Adj_Main.directSuccessors); Without_sIz.directSuccessors.add(Adj_Main); Without_sIz.successors.add(Adj_Main.directSuccessors); Loc_dA.directSuccessors.add(Rel_ki); Rel_ki.directSuccessors.add(Adj_Main_Rel); Resemb_msI.directSuccessors.add(Adj_Main); Resemb_msI.successors.add(Adj_Main.allSuccessors()); Resemb_ImsI.directSuccessors.add(Adj_Main); Resemb_ImsI.successors.add(Adj_Main.allSuccessors()); //---------------------------- Adjective ----------------------------------------------------------------------- Adj_Main.directSuccessors.add(Ly_cA, Become_lAs, Quite_cA, Resemb_ImsI, Resemb_msI); Adj_Main.successors.add(Noun_Main.allSuccessors().remove(Related_sAl)); Adj_Default.directSuccessors.add(Adj_Main.directSuccessors); Adj_Default.successors.add(Adj_Main.getSuccessors()); Adj_Main_Rel.directSuccessors.add(Adj_Main.directSuccessors); Adj_Main_Rel.successors.add(Adj_Main.getSuccessors()); Become_lAs.directSuccessors.add(Verb_Main); Become_lAs.successors.add(Verb_Main.allSuccessors()); Quite_cA.directSuccessors.add(Adj_Main); Ly_cA.directSuccessors.add(Adv_Main); //---------------------------- Verb ---------------------------------------------------------------------------- Verb_Main.directSuccessors.add(Neg_mA, Neg_m, Pos_EMPTY, Caus_t, Caus_tIr, Pass_In, Pass_nIl); Verb_Main.successors.add(Prog_Iyor, Prog2_mAktA, Fut_yAcAk, Past_dI, Evid_mIs, Aor_Ir, AorPart_Ir) .add(Abil_yAbil, Abil_yA, Caus_tIr, Opt_yA, Imp_EMPTY, Agt_yIcI, Des_sA) .add(NotState_mAzlIk, ActOf_mAcA, PastPart_dIk, EvidPart_mIs) .add(FutPart_yAcAk, PresPart_yAn, AsLongAs_dIkcA) .add(Inf1_mAk, Inf2_mA, Inf3_yIs) .add(When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing_mAdAn, WithoutDoing2_mAksIzIn) .add(AfterDoing_yIp, When_yIncA, UnableToDo_yAmAdAn, InsteadOfDoing_mAktAnsA) .add(KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Almost_yAyAz, Hastily_yIver, Stay_yAkal, Recip_Is) .add(NounDeriv_nIm, UntilDoing_yAsIyA); Verb_Default.directSuccessors.add(Verb_Main.directSuccessors).remove(Pass_nIl); Verb_Default.successors.add(Verb_Main.successors); Pos_EMPTY.directSuccessors.add(Imp_EMPTY); Pos_EMPTY.successors.add(Verb_Default.successors).remove(Neg_m, Neg_mA); Neg_mA.directSuccessors.add(Aor_z, AorPart_z, Aor_EMPTY, Prog2_mAktA, Imp_EMPTY, Opt_yA, Des_sA, Fut_yAcAk, Past_dI, Evid_mIs, Cond_sA, Abil_yAbil, Necess_mAlI, NotState_mAzlIk, ActOf_mAcA, PastPart_dIk, FutPart_yAcAk, EvidPart_mIs, Agt_yIcI) .add(AsLongAs_dIkcA, PresPart_yAn) .add(Inf1_mAk, Inf2_mA, Inf3_yIs) .add(When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing2_mAksIzIn) .add(AfterDoing_yIp, When_yIncA, InsteadOfDoing_mAktAnsA) .add(KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Hastily_yIver); Imp_EMPTY.directSuccessors.add(A2sg_EMPTY, A2sg2_sAnA, A2sg3_yInIz, A2pl2_sAnIzA, A2pl_yIn, A3sg_sIn, A3pl_sInlAr); Caus_t.directSuccessors.add(Verb_Main); Caus_t.successors.add(Verb_Main.allSuccessors()).add(Pass_nIl).remove(Caus_t); Caus_tIr.directSuccessors.add(Verb_Main); Caus_tIr.successors.add(Verb_Main.allSuccessors()).add(Pass_nIl).remove(Caus_tIr); Pass_nIl.directSuccessors.add(Verb_Main); Pass_nIl.directSuccessors.add(Verb_Main.allSuccessors()).remove(Caus_t, Caus_tIr, Pass_nIl, Pass_In); registerForms( Noun_Default, Nom_EMPTY, Verb_Default, Pnon_EMPTY, Dat_yA, Dat_nA, Loc_dA, Loc_ndA, Abl_dAn, Abl_ndAn, Gen_nIn, Acc_yI, Acc_nI, Inst_ylA, P1sg_Im, P2sg_In, P3sg_sI, P1pl_ImIz, P2pl_InIz, P3pl_lArI, Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Rel_ki, Rel_kI, A1sg_yIm, A1sg_m, A1sg_EMPTY, A2sg_sIn, A2sg_n, A2sg_EMPTY, A2sg2_sAnA, A2sg3_yInIz, A3sg_EMPTY, A3sg_sIn, A1pl_yIz, A1pl_k, A1pl_lIm, A1pl_EMPTY, A2pl_sInIz, A2pl_nIz, A2pl_yIn, A2pl_EMPTY, A2pl2_sAnIzA, A3pl_lAr, A3pl_sInlAr, Agt_cI, Agt_yIcI, Ness_lIk, Become_lAs, Resemb_ImsI, Resemb_msI, Related_sAl, Aor_Ir, Aor_Ar, Aor_z, Des_sA, Aor_EMPTY, AorPart_Ir, AorPart_Ar, AorPart_z, Prog_Iyor, Prog2_mAktA, Fut_yAcAk, FutPart_yAcAk, Past_dI, PastPart_dIk, Evid_mIs, EvidPart_mIs, PresPart_yAn, Neg_mA, Neg_m, Cond_sA, Necess_mAlI, Opt_yA, Pass_In, Pass_nIl, Caus_t, Caus_tIr, Imp_EMPTY, Imp_EMPTY_V, Imp_EMPTY_C, Recip_Is, Recip_yIs, Reflex_In, Abil_yAbil, Abil_yA, Cop_dIr, PastCop_ydI, EvidCop_ymIs, CondCop_ysA, While_ken, NotState_mAzlIk, ActOf_mAcA, AsIf_cAsInA, AsLongAs_dIkcA, When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing_mAdAn, WithoutDoing2_mAksIzIn, AfterDoing_yIp, UnableToDo_yAmAdAn, InsteadOfDoing_mAktAnsA, KeepDoing_yAgor, KeepDoing2_yAdur, EverSince_yAgel, Almost_yAyAz, Hastily_yIver, Stay_yAkal, Inf1_mAk, Inf2_mA, Inf3_yIs, Ly_cA, Quite_cA, Equ_cA, Equ_ncA, UntilDoing_yAsIyA, Noun_Main, Noun_Comp_P3sg, Noun_Comp_P3sg_Root, A3pl_Comp_lAr, Adj_Main, Adv_Main, Adj_Main_Rel, Interj_Main, Verb_Main, Verb_Prog_Drop, PersPron_Main, PersPron_BenSen, PersPron_BanSan, Numeral_Main, Ordinal_IncI, Grouping_sAr, Ques_mI, Particle_Main, NounDeriv_nIm); /* Noun_Main.add(CASE_FORMS, POSSESSIVE_FORMS, COPULAR_FORMS, PERSON_FORMS_N) .add(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI, Ness_lIk, Related_sAl, Become_lAs, Equ_cA); Noun_Exp_V.add(Dat_yA, Acc_yI, Gen_nIn, P1sg_Im, P2sg_In, P3sg_sI, P1pl_ImIz, P2pl_InIz, A1sg_yIm, A1pl_yIz, Resemb_ImsI); Noun_Exp_C.add(Noun_Main.getSuccSetCopy()).remove(Noun_Exp_V.getSuccSetCopy()); Noun_Comp_P3sg.add(COPULAR_FORMS, POSSESSIVE_FORMS) .add(Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA) .add(A1sg_yIm, A1pl_yIz, A2sg_sIn, A2pl_sInIz); Noun_Comp_P3sg_Root.add(With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI, Ness_lIk, Related_sAl, P1sg_Im, P2sg_In, P1pl_ImIz, P2pl_InIz, P3pl_lArI, A3pl_Comp_lAr); ProperNoun_Main .add(CASE_FORMS, POSSESSIVE_FORMS, COPULAR_FORMS, PERSON_FORMS_N) .add(Pl_lAr, Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, A3sg_EMPTY, Agt_cI, Ness_lIk); Verb_Main.add(Prog_Iyor, Prog2_mAktA, Fut_yAcAk, Past_dI, Evid_mIs, Aor_Ir, AorPart_Ir) .add(Neg_mA, Neg_m, Abil_yAbil, Abil_yA, Caus_tIr, Opt_yA, Imp_EMPTY, Agt_yIcI, Des_sA) .add(Pass_nIl, NotState_mAzlIk, ActOf_mAcA, PastPart_dIk, EvidPart_mIs) .add(FutPart_yAcAk, PresPart_yAn, AsLongAs_dIkcA) .add(Inf1_mAk, Inf2_mA, Inf3_yIs) .add(When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing_mAdAn, WithoutDoing2_mAksIzIn) .add(AfterDoing_yIp, When_yIncA, UnableToDo_yAmAdAn, InsteadOfDoing_mAktAnsA) .add(KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Almost_yAyAz, Hastily_yIver, Stay_yAkal, Recip_Is) .add(NounDeriv_nIm, UntilDoing_yAsIyA); Verb_Exp_V.add(Opt_yA, Fut_yAcAk, Aor_Ar, AorPart_Ar, Prog_Iyor, PresPart_yAn, Pass_nIl, KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Almost_yAyAz, Hastily_yIver, Stay_yAkal, When_yIncA, UnableToDo_yAmAdAn, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, Inf3_yIs, Abil_yA, Abil_yAbil, AfterDoing_yIp, Agt_yIcI, FutPart_yAcAk, Imp_EMPTY_V).remove(Imp_EMPTY); Verb_Exp_C.add(Verb_Main.getSuccSetCopy()) .remove(Verb_Exp_V.getSuccSetCopy()).remove(Aor_Ir, AorPart_Ir, Imp_EMPTY) .add(Imp_EMPTY_V); Verb_Prog_Drop.add(Prog_Iyor); Adv_Main.add(COPULAR_FORMS); PersPron_Main.add(CASE_FORMS).add(PastCop_ydI, EvidCop_ymIs, CondCop_ysA, While_ken); PersPron_BenSen.add(PersPron_Main.getSuccSetCopy()).remove(Dat_yA); PersPron_BanSan.add(Dat_yA); Ques_mI.add(PERSON_FORMS_N).add(Cop_dIr, EvidCop_ymIs, PastCop_ydI); Adj_Main.add(Noun_Main.getSuccSetCopy()).add(Ly_cA, Become_lAs, Quite_cA).remove(Related_sAl); Adj_Exp_C.add(Noun_Exp_C.getSuccSetCopy()).add(Ly_cA, Become_lAs, Quite_cA); Adj_Exp_V.add(Noun_Exp_V.getSuccSetCopy()); Become_lAs.add(Verb_Main.getSuccSetCopy()); Quite_cA.add(Noun_Main.getSuccSetCopy()).remove(Related_sAl); Numeral_Main.add(COPULAR_FORMS, CASE_FORMS, POSSESSIVE_FORMS, PERSON_FORMS_N) .add(Ordinal_IncI, Grouping_sAr, With_lI, Without_sIz, Ness_lIk, Pl_lAr); Ordinal_IncI.add(Numeral_Main.getSuccSetCopy()).remove(Ordinal_IncI, Grouping_sAr); Grouping_sAr.add(With_lI, Ness_lIk, Abl_dAn).add(COPULAR_FORMS); Pl_lAr.add(CASE_FORMS, COPULAR_FORMS) .add(P1sg_Im, P2sg_In, P1pl_ImIz, P2pl_InIz, A1pl_yIz, A2pl_sInIz, Equ_cA); P1sg_Im.add(CASE_FORMS, COPULAR_FORMS).add(A2sg_sIn, A1pl_yIz, A2pl_sInIz, A3sg_EMPTY, Equ_cA); P2sg_In.add(CASE_FORMS, COPULAR_FORMS).add(A1sg_yIm, A1pl_yIz, A3sg_EMPTY, Equ_cA); P3sg_sI.add(COPULAR_FORMS) .add(Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA) .add(A1sg_yIm, A1pl_yIz, A2sg_sIn, A2pl_sInIz, A3sg_EMPTY, Equ_ncA); P1pl_ImIz.add(CASE_FORMS, COPULAR_FORMS).add(A1sg_yIm, A2sg_sIn, A3sg_EMPTY, Equ_cA, A2pl_sInIz); P2pl_InIz.add(CASE_FORMS, COPULAR_FORMS).add(A1sg_yIm, A2sg_sIn, A1pl_yIz, A2pl_sInIz, A3sg_EMPTY, Equ_cA); P3pl_lArI.add(P3sg_sI.getSuccSetCopy()).add(A1sg_yIm, A2sg_sIn, A3sg_EMPTY, A1pl_yIz, A2pl_sInIz, Equ_ncA); Rel_ki.add(COPULAR_FORMS, PERSON_FORMS_N).add(Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA, Pl_lAr); Rel_kI.add(Rel_ki.getSuccSetCopy()); Dat_yA.add(COPULAR_FORMS); Dat_nA.add(COPULAR_FORMS); Loc_dA.add(COPULAR_FORMS, PERSON_FORMS_N).add(Rel_ki); Loc_ndA.add(COPULAR_FORMS, PERSON_FORMS_N).add(Rel_ki); Inst_ylA.add(COPULAR_FORMS, PERSON_FORMS_N, POSSESSIVE_FORMS); Abl_dAn.add(COPULAR_FORMS, PERSON_FORMS_N); Abl_ndAn.add(COPULAR_FORMS, PERSON_FORMS_N); Gen_nIn.add(COPULAR_FORMS, PERSON_FORMS_N).add(Rel_ki); A1sg_yIm.add(Cop_dIr); A2sg_sIn.add(Cop_dIr); A3sg_EMPTY.add(Cop_dIr); A1pl_yIz.add(Cop_dIr); A2pl_sInIz.add(Cop_dIr); A3pl_lAr.add(Pl_lAr.getSuccSetCopy()); A3pl_Comp_lAr.add(Pl_lAr.getSuccSetCopy()); Dim_cIk.add(Loc_dA, Abl_dAn, Inst_ylA, P3pl_lArI, A2sg_sIn, A2pl_sInIz, A3pl_lAr, Pl_lAr, Inst_ylA).add(COPULAR_FORMS); Dim2_cAgIz.add(CASE_FORMS, COPULAR_FORMS, POSSESSIVE_FORMS, PERSON_FORMS_N).add(Pl_lAr); With_lI.add(CASE_FORMS, COPULAR_FORMS, POSSESSIVE_FORMS, PERSON_FORMS_N).add(Pl_lAr, Ness_lIk, Become_lAs, Ly_cA); Without_sIz.add(CASE_FORMS, COPULAR_FORMS, POSSESSIVE_FORMS, PERSON_FORMS_N).add(Pl_lAr, Ness_lIk, Become_lAs, Ly_cA); Resemb_msI.add(CASE_FORMS, PERSON_FORMS_N, COPULAR_FORMS, POSSESSIVE_FORMS) .add(Pl_lAr, Ness_lIk, With_lI, Without_sIz, Become_lAs); Resemb_ImsI.add(Resemb_ImsI.getSuccSetCopy()); Ness_lIk.add(CASE_FORMS, POSSESSIVE_FORMS, COPULAR_FORMS, CASE_FORMS).add(Pl_lAr, Agt_cI, With_lI, Without_sIz, Equ_cA); Related_sAl.add(Adj_Main.getSuccSetCopy()).remove(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Related_sAl, Resemb_msI, Resemb_msI); PastCop_ydI.add(PERSON_FORMS_COP); EvidCop_ymIs.add(A1sg_yIm, A2sg_sIn, A3sg_EMPTY, A1pl_yIz, A2pl_sInIz, A3pl_lAr, AsIf_cAsInA); CondCop_ysA.add(PERSON_FORMS_COP); Cop_dIr.add(A3pl_lAr); Neg_mA.add(Aor_z, AorPart_z, Aor_EMPTY, Prog2_mAktA, Imp_EMPTY, Opt_yA, Des_sA, Fut_yAcAk, Past_dI, Evid_mIs, Cond_sA, Abil_yAbil, Necess_mAlI, NotState_mAzlIk, ActOf_mAcA, PastPart_dIk, FutPart_yAcAk, EvidPart_mIs, Agt_yIcI) .add(AsLongAs_dIkcA, PresPart_yAn) .add(Inf1_mAk, Inf2_mA, Inf3_yIs) .add(When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing2_mAksIzIn) .add(AfterDoing_yIp, When_yIncA, InsteadOfDoing_mAktAnsA) .add(KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Hastily_yIver); Neg_m.add(Prog_Iyor); Aor_Ar.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA); Aor_Ir.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA); Aor_z.add(COPULAR_FORMS).add(A3sg_sIn, Cond_sA); Aor_EMPTY.add(A1sg_m, A1pl_yIz); Set<SuffixFormSet> noParticipleSuff = Sets.newHashSet(Become_lAs, Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Related_sAl, Resemb_msI, Resemb_msI); AorPart_Ar.add(Adj_Main.getSuccSetCopy()).remove(noParticipleSuff).add(AsIf_cAsInA); AorPart_Ir.add(AorPart_Ar.getSuccSetCopy()); AorPart_z.add(AorPart_Ar.getSuccSetCopy()); FutPart_yAcAk.add(Adj_Exp_C.getSuccSetCopy()); NotState_mAzlIk.add(Adj_Exp_C.getSuccSetCopy()); PresPart_yAn.add(AorPart_Ar.getSuccSetCopy()); EvidPart_mIs.add(AorPart_Ar.getSuccSetCopy()); PastPart_dIk.add(Adj_Exp_C.getSuccSetCopy()).remove(AsIf_cAsInA).remove(noParticipleSuff); Prog_Iyor.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA); Prog2_mAktA.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA); Fut_yAcAk.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA, AsIf_cAsInA); Past_dI.add(A1sg_m, A2sg_n, A3sg_EMPTY, A1pl_k, A2pl_nIz, A3pl_lAr, CondCop_ysA, PastCop_ydI); Evid_mIs.add(PERSON_FORMS_N).add(CondCop_ysA, PastCop_ydI, EvidCop_ymIs, While_ken, Cop_dIr); Cond_sA.add(A1sg_m, A2sg_n, A3sg_EMPTY, A1pl_k, A2pl_nIz, A3pl_lAr, PastCop_ydI, EvidCop_ymIs); Imp_EMPTY.add(A2sg_EMPTY, A2sg2_sAnA, A2sg3_yInIz, A2pl2_sAnIzA, A2pl_yIn, A3sg_sIn, A3pl_sInlAr); Imp_EMPTY_C.add(A2sg_EMPTY, A2sg2_sAnA, A2pl2_sAnIzA, A3sg_sIn, A3pl_sInlAr); Imp_EMPTY_V.add(A2sg3_yInIz, A2pl_yIn); Agt_cI.add(CASE_FORMS, PERSON_FORMS_N, POSSESSIVE_FORMS, COPULAR_FORMS).add(Pl_lAr, Become_lAs, With_lI, Without_sIz, Ness_lIk); Agt_yIcI.add(Agt_cI.getSuccSetCopy()); Abil_yAbil.add(Verb_Main.getSuccSetCopy()).remove(Abil_yAbil, Abil_yA, Neg_mA, Pass_nIl).add(Cond_sA, Pass_In); Abil_yA.add(Neg_mA, Neg_m); Opt_yA.add(A1sg_yIm, A2sg_sIn, A3sg_EMPTY, A1pl_lIm, A2pl_sInIz, A3pl_lAr); Des_sA.add(COPULAR_FORMS).add(A1sg_m, A2sg_n, A3sg_EMPTY, A1pl_k, A2pl_nIz, A3pl_lAr, PastCop_ydI, EvidCop_ymIs); Caus_t.add(Verb_Main.getSuccSetCopy()).add(Pass_nIl); Caus_tIr.add(Verb_Main.getSuccSetCopy()).remove(Caus_tIr).add(Caus_t, Pass_nIl); Pass_nIl.add(Verb_Main.getSuccSetCopy()).remove(Pass_In, Pass_nIl, Caus_tIr).add(Caus_t); Pass_In.add(Verb_Main.getSuccSetCopy()).remove(Pass_In); Reflex_In.add(Verb_Main.getSuccSetCopy()); Recip_Is.add(Verb_Main.getSuccSetCopy()).remove(Recip_Is); Recip_yIs.add(Verb_Main.getSuccSetCopy()).remove(Recip_Is); Inf1_mAk.add(COPULAR_FORMS).add(Abl_dAn, Loc_dA, Inst_ylA); Inf2_mA.add(Noun_Main.getSuccessors()); Inf3_yIs.add(Noun_Main.getSuccessors()); NounDeriv_nIm.add(Noun_Main.getSuccSetCopy()); When_yIncA.add(Dat_yA); While_ken.add(Rel_ki).add(PastCop_ydI, EvidCop_ymIs, CondCop_ysA); FeelLike_yAsI.add(POSSESSIVE_FORMS).add(COPULAR_FORMS); KeepDoing_yAgor.add(Neg_mA.getSuccSetCopy()).remove(Aor_z).add(Neg_mA, Neg_m, Aor_Ir, Prog_Iyor); KeepDoing2_yAdur.add(KeepDoing_yAgor.getSuccSetCopy()); EverSince_yAgel.add(KeepDoing_yAgor.getSuccSetCopy()); Almost_yAyAz.add(KeepDoing_yAgor.getSuccSetCopy()); Hastily_yIver.add(KeepDoing_yAgor.getSuccSetCopy()); Stay_yAkal.add(KeepDoing_yAgor.getSuccSetCopy()); Necess_mAlI.add(COPULAR_FORMS, PERSON_FORMS_N); */ }
public TurkishSuffixes() { // noun template. it has all possible suffix forms that a noun can follow Noun_Main.directSuccessors.add(A3pl_lAr, A3pl_Comp_lAr, A3sg_EMPTY); Noun_Main.successors.add(POSSESSIVE_FORMS, CASE_FORMS) .add(Dat_nA, Loc_ndA, Abl_ndAn, Acc_nI, Equ_ncA) .add(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI, Ness_lIk, Related_sAl) .add(Become_lAs); // default noun suffix form. we remove some suffixes so that words like araba-na (dative) Noun_Default.directSuccessors.add(A3pl_lAr, A3sg_EMPTY); Noun_Default.successors.add(Noun_Main.successors) .remove(Dat_nA, Loc_ndA, Abl_ndAn, Acc_nI); // P3sg compound suffixes. (full form. such as zeytinyağı-na) Noun_Comp_P3sg.directSuccessors.add(A3sg_EMPTY); Noun_Comp_P3sg.successors.add(POSSESSIVE_FORMS) .add(Pnon_EMPTY, Nom_EMPTY) .add(Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA) .add(A1sg_yIm, A1pl_yIz, A2sg_sIn, A2pl_sInIz); // P3sg compound suffixes. (root form. such as zeytinyağ-lar-ı) Noun_Comp_P3sg_Root.directSuccessors.add(A3pl_Comp_lAr, A3sg_EMPTY); // A3pl_Comp_lAr is used, because zeytinyağ-lar is not allowed. Noun_Comp_P3sg_Root.successors.add(Pnon_EMPTY, Nom_EMPTY, With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI, Ness_lIk, Related_sAl, Dim_cIk) .add(P3pl_lArI); // Proper noun default //TODO: should be a template ProperNoun_Main.directSuccessors.add(A3pl_lAr, A3sg_EMPTY); ProperNoun_Main.successors.add(CASE_FORMS, POSSESSIVE_FORMS) .add(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, A3sg_EMPTY, Agt_cI, Ness_lIk); A3pl_lAr.directSuccessors.add(POSSESSIVE_FORMS).remove(P3pl_lArI); A3pl_lAr.successors.add(CASE_FORMS) .add(A1pl_yIz, A2pl_sInIz); //TODO: check below. A3pl_Comp_lAr.directSuccessors.add(A3pl_lAr.directSuccessors); A3pl_Comp_lAr.successors.add(CASE_FORMS) .add(A1pl_yIz, A2pl_sInIz); A3sg_EMPTY.directSuccessors.add(POSSESSIVE_FORMS); A3sg_EMPTY.successors.add(Noun_Main.successors).remove(POSSESSIVE_FORMS); Nom_EMPTY.directSuccessors.add(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI) .add(Ness_lIk, Related_sAl, Become_lAs, Equ_cA); Dim_cIk.directSuccessors.add(Noun_Main); Dim_cIk.successors.add(Noun_Main.allSuccessors().remove(Dim_cIk, Dim2_cAgIz)); Dim2_cAgIz.directSuccessors.add(Noun_Main); Dim2_cAgIz.successors.add(Noun_Main.allSuccessors().remove(Dim_cIk, Dim2_cAgIz)); Pnon_EMPTY.directSuccessors.add(CASE_FORMS) .add(Dat_nA, Loc_ndA, Abl_ndAn, Acc_nI); Pnon_EMPTY.successors.add(Nom_EMPTY.directSuccessors); P1sg_Im.directSuccessors.add(CASE_FORMS); P2sg_In.directSuccessors.add(CASE_FORMS); P3sg_sI.directSuccessors.add(Nom_EMPTY, Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA, Equ_ncA); P1pl_ImIz.directSuccessors.add(CASE_FORMS); P2pl_InIz.directSuccessors.add(CASE_FORMS); P3pl_lArI.directSuccessors.add(CASE_FORMS); With_lI.directSuccessors.add(Adj_Main); With_lI.successors.add(Adj_Main.directSuccessors); Without_sIz.directSuccessors.add(Adj_Main); Without_sIz.successors.add(Adj_Main.directSuccessors); Loc_dA.directSuccessors.add(Rel_ki); Rel_ki.directSuccessors.add(Adj_Main_Rel); Resemb_msI.directSuccessors.add(Adj_Main); Resemb_msI.successors.add(Adj_Main.allSuccessors()); Resemb_ImsI.directSuccessors.add(Adj_Main); Resemb_ImsI.successors.add(Adj_Main.allSuccessors()); //---------------------------- Adjective ----------------------------------------------------------------------- Adj_Main.directSuccessors.add(Ly_cA, Become_lAs, Quite_cA, Resemb_ImsI, Resemb_msI); Adj_Main.successors.add(Noun_Main.allSuccessors().remove(Related_sAl)); Adj_Default.directSuccessors.add(Adj_Main.directSuccessors); Adj_Default.successors.add(Adj_Main.getSuccessors()); Adj_Main_Rel.directSuccessors.add(Adj_Main.directSuccessors); Adj_Main_Rel.successors.add(Adj_Main.getSuccessors()); Become_lAs.directSuccessors.add(Verb_Main); Become_lAs.successors.add(Verb_Main.allSuccessors()); Quite_cA.directSuccessors.add(Adj_Main); Ly_cA.directSuccessors.add(Adv_Main); //---------------------------- Verb ---------------------------------------------------------------------------- Verb_Main.directSuccessors.add(Neg_mA, Neg_m, Pos_EMPTY, Caus_t, Caus_tIr, Pass_In, Pass_nIl); Verb_Main.successors.add(Prog_Iyor, Prog2_mAktA, Fut_yAcAk, Past_dI, Evid_mIs, Aor_Ir, AorPart_Ir) .add(Abil_yAbil, Abil_yA, Caus_tIr, Opt_yA, Imp_EMPTY, Agt_yIcI, Des_sA) .add(NotState_mAzlIk, ActOf_mAcA, PastPart_dIk, EvidPart_mIs) .add(FutPart_yAcAk, PresPart_yAn, AsLongAs_dIkcA) .add(Inf1_mAk, Inf2_mA, Inf3_yIs) .add(When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing_mAdAn, WithoutDoing2_mAksIzIn) .add(AfterDoing_yIp, When_yIncA, UnableToDo_yAmAdAn, InsteadOfDoing_mAktAnsA) .add(KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Almost_yAyAz, Hastily_yIver, Stay_yAkal, Recip_Is) .add(NounDeriv_nIm, UntilDoing_yAsIyA); Verb_Default.directSuccessors.add(Verb_Main.directSuccessors); Verb_Default.successors.add(Verb_Main.successors); Pos_EMPTY.directSuccessors.add(Imp_EMPTY); Pos_EMPTY.successors.add(Verb_Default.successors).remove(Neg_m, Neg_mA); Neg_mA.directSuccessors.add(Aor_z, AorPart_z, Aor_EMPTY, Prog2_mAktA, Imp_EMPTY, Opt_yA, Des_sA, Fut_yAcAk, Past_dI, Evid_mIs, Cond_sA, Abil_yAbil, Necess_mAlI, NotState_mAzlIk, ActOf_mAcA, PastPart_dIk, FutPart_yAcAk, EvidPart_mIs, Agt_yIcI) .add(AsLongAs_dIkcA, PresPart_yAn) .add(Inf1_mAk, Inf2_mA, Inf3_yIs) .add(When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing2_mAksIzIn) .add(AfterDoing_yIp, When_yIncA, InsteadOfDoing_mAktAnsA) .add(KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Hastily_yIver); Imp_EMPTY.directSuccessors.add(A2sg_EMPTY, A2sg2_sAnA, A2sg3_yInIz, A2pl2_sAnIzA, A2pl_yIn, A3sg_sIn, A3pl_sInlAr); Caus_t.directSuccessors.add(Verb_Main); Caus_t.successors.add(Verb_Main.allSuccessors()).add(Pass_nIl).remove(Caus_t); Caus_tIr.directSuccessors.add(Verb_Main); Caus_tIr.successors.add(Verb_Main.allSuccessors()).add(Pass_nIl).remove(Caus_tIr); Pass_nIl.directSuccessors.add(Verb_Main); Pass_nIl.directSuccessors.add(Verb_Main.allSuccessors()).remove(Caus_t, Caus_tIr, Pass_nIl, Pass_In); registerForms( Noun_Default, Nom_EMPTY, Verb_Default, Pnon_EMPTY, Dat_yA, Dat_nA, Loc_dA, Loc_ndA, Abl_dAn, Abl_ndAn, Gen_nIn, Acc_yI, Acc_nI, Inst_ylA, P1sg_Im, P2sg_In, P3sg_sI, P1pl_ImIz, P2pl_InIz, P3pl_lArI, Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Rel_ki, Rel_kI, A1sg_yIm, A1sg_m, A1sg_EMPTY, A2sg_sIn, A2sg_n, A2sg_EMPTY, A2sg2_sAnA, A2sg3_yInIz, A3sg_EMPTY, A3sg_sIn, A1pl_yIz, A1pl_k, A1pl_lIm, A1pl_EMPTY, A2pl_sInIz, A2pl_nIz, A2pl_yIn, A2pl_EMPTY, A2pl2_sAnIzA, A3pl_lAr, A3pl_sInlAr, Agt_cI, Agt_yIcI, Ness_lIk, Become_lAs, Resemb_ImsI, Resemb_msI, Related_sAl, Aor_Ir, Aor_Ar, Aor_z, Des_sA, Aor_EMPTY, AorPart_Ir, AorPart_Ar, AorPart_z, Prog_Iyor, Prog2_mAktA, Fut_yAcAk, FutPart_yAcAk, Past_dI, PastPart_dIk, Evid_mIs, EvidPart_mIs, PresPart_yAn, Neg_mA, Neg_m, Cond_sA, Necess_mAlI, Opt_yA, Pass_In, Pass_nIl, Caus_t, Caus_tIr, Imp_EMPTY, Imp_EMPTY_V, Imp_EMPTY_C, Recip_Is, Recip_yIs, Reflex_In, Abil_yAbil, Abil_yA, Cop_dIr, PastCop_ydI, EvidCop_ymIs, CondCop_ysA, While_ken, NotState_mAzlIk, ActOf_mAcA, AsIf_cAsInA, AsLongAs_dIkcA, When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing_mAdAn, WithoutDoing2_mAksIzIn, AfterDoing_yIp, UnableToDo_yAmAdAn, InsteadOfDoing_mAktAnsA, KeepDoing_yAgor, KeepDoing2_yAdur, EverSince_yAgel, Almost_yAyAz, Hastily_yIver, Stay_yAkal, Inf1_mAk, Inf2_mA, Inf3_yIs, Ly_cA, Quite_cA, Equ_cA, Equ_ncA, UntilDoing_yAsIyA, Noun_Main, Noun_Comp_P3sg, Noun_Comp_P3sg_Root, A3pl_Comp_lAr, Adj_Main, Adv_Main, Adj_Main_Rel, Interj_Main, Verb_Main, Verb_Prog_Drop, PersPron_Main, PersPron_BenSen, PersPron_BanSan, Numeral_Main, Ordinal_IncI, Grouping_sAr, Ques_mI, Particle_Main, NounDeriv_nIm); /* Noun_Main.add(CASE_FORMS, POSSESSIVE_FORMS, COPULAR_FORMS, PERSON_FORMS_N) .add(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI, Ness_lIk, Related_sAl, Become_lAs, Equ_cA); Noun_Exp_V.add(Dat_yA, Acc_yI, Gen_nIn, P1sg_Im, P2sg_In, P3sg_sI, P1pl_ImIz, P2pl_InIz, A1sg_yIm, A1pl_yIz, Resemb_ImsI); Noun_Exp_C.add(Noun_Main.getSuccSetCopy()).remove(Noun_Exp_V.getSuccSetCopy()); Noun_Comp_P3sg.add(COPULAR_FORMS, POSSESSIVE_FORMS) .add(Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA) .add(A1sg_yIm, A1pl_yIz, A2sg_sIn, A2pl_sInIz); Noun_Comp_P3sg_Root.add(With_lI, Without_sIz, Agt_cI, Resemb_msI, Resemb_ImsI, Ness_lIk, Related_sAl, P1sg_Im, P2sg_In, P1pl_ImIz, P2pl_InIz, P3pl_lArI, A3pl_Comp_lAr); ProperNoun_Main .add(CASE_FORMS, POSSESSIVE_FORMS, COPULAR_FORMS, PERSON_FORMS_N) .add(Pl_lAr, Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, A3sg_EMPTY, Agt_cI, Ness_lIk); Verb_Main.add(Prog_Iyor, Prog2_mAktA, Fut_yAcAk, Past_dI, Evid_mIs, Aor_Ir, AorPart_Ir) .add(Neg_mA, Neg_m, Abil_yAbil, Abil_yA, Caus_tIr, Opt_yA, Imp_EMPTY, Agt_yIcI, Des_sA) .add(Pass_nIl, NotState_mAzlIk, ActOf_mAcA, PastPart_dIk, EvidPart_mIs) .add(FutPart_yAcAk, PresPart_yAn, AsLongAs_dIkcA) .add(Inf1_mAk, Inf2_mA, Inf3_yIs) .add(When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing_mAdAn, WithoutDoing2_mAksIzIn) .add(AfterDoing_yIp, When_yIncA, UnableToDo_yAmAdAn, InsteadOfDoing_mAktAnsA) .add(KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Almost_yAyAz, Hastily_yIver, Stay_yAkal, Recip_Is) .add(NounDeriv_nIm, UntilDoing_yAsIyA); Verb_Exp_V.add(Opt_yA, Fut_yAcAk, Aor_Ar, AorPart_Ar, Prog_Iyor, PresPart_yAn, Pass_nIl, KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Almost_yAyAz, Hastily_yIver, Stay_yAkal, When_yIncA, UnableToDo_yAmAdAn, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, Inf3_yIs, Abil_yA, Abil_yAbil, AfterDoing_yIp, Agt_yIcI, FutPart_yAcAk, Imp_EMPTY_V).remove(Imp_EMPTY); Verb_Exp_C.add(Verb_Main.getSuccSetCopy()) .remove(Verb_Exp_V.getSuccSetCopy()).remove(Aor_Ir, AorPart_Ir, Imp_EMPTY) .add(Imp_EMPTY_V); Verb_Prog_Drop.add(Prog_Iyor); Adv_Main.add(COPULAR_FORMS); PersPron_Main.add(CASE_FORMS).add(PastCop_ydI, EvidCop_ymIs, CondCop_ysA, While_ken); PersPron_BenSen.add(PersPron_Main.getSuccSetCopy()).remove(Dat_yA); PersPron_BanSan.add(Dat_yA); Ques_mI.add(PERSON_FORMS_N).add(Cop_dIr, EvidCop_ymIs, PastCop_ydI); Adj_Main.add(Noun_Main.getSuccSetCopy()).add(Ly_cA, Become_lAs, Quite_cA).remove(Related_sAl); Adj_Exp_C.add(Noun_Exp_C.getSuccSetCopy()).add(Ly_cA, Become_lAs, Quite_cA); Adj_Exp_V.add(Noun_Exp_V.getSuccSetCopy()); Become_lAs.add(Verb_Main.getSuccSetCopy()); Quite_cA.add(Noun_Main.getSuccSetCopy()).remove(Related_sAl); Numeral_Main.add(COPULAR_FORMS, CASE_FORMS, POSSESSIVE_FORMS, PERSON_FORMS_N) .add(Ordinal_IncI, Grouping_sAr, With_lI, Without_sIz, Ness_lIk, Pl_lAr); Ordinal_IncI.add(Numeral_Main.getSuccSetCopy()).remove(Ordinal_IncI, Grouping_sAr); Grouping_sAr.add(With_lI, Ness_lIk, Abl_dAn).add(COPULAR_FORMS); Pl_lAr.add(CASE_FORMS, COPULAR_FORMS) .add(P1sg_Im, P2sg_In, P1pl_ImIz, P2pl_InIz, A1pl_yIz, A2pl_sInIz, Equ_cA); P1sg_Im.add(CASE_FORMS, COPULAR_FORMS).add(A2sg_sIn, A1pl_yIz, A2pl_sInIz, A3sg_EMPTY, Equ_cA); P2sg_In.add(CASE_FORMS, COPULAR_FORMS).add(A1sg_yIm, A1pl_yIz, A3sg_EMPTY, Equ_cA); P3sg_sI.add(COPULAR_FORMS) .add(Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA) .add(A1sg_yIm, A1pl_yIz, A2sg_sIn, A2pl_sInIz, A3sg_EMPTY, Equ_ncA); P1pl_ImIz.add(CASE_FORMS, COPULAR_FORMS).add(A1sg_yIm, A2sg_sIn, A3sg_EMPTY, Equ_cA, A2pl_sInIz); P2pl_InIz.add(CASE_FORMS, COPULAR_FORMS).add(A1sg_yIm, A2sg_sIn, A1pl_yIz, A2pl_sInIz, A3sg_EMPTY, Equ_cA); P3pl_lArI.add(P3sg_sI.getSuccSetCopy()).add(A1sg_yIm, A2sg_sIn, A3sg_EMPTY, A1pl_yIz, A2pl_sInIz, Equ_ncA); Rel_ki.add(COPULAR_FORMS, PERSON_FORMS_N).add(Dat_nA, Loc_ndA, Abl_ndAn, Gen_nIn, Acc_nI, Inst_ylA, Pl_lAr); Rel_kI.add(Rel_ki.getSuccSetCopy()); Dat_yA.add(COPULAR_FORMS); Dat_nA.add(COPULAR_FORMS); Loc_dA.add(COPULAR_FORMS, PERSON_FORMS_N).add(Rel_ki); Loc_ndA.add(COPULAR_FORMS, PERSON_FORMS_N).add(Rel_ki); Inst_ylA.add(COPULAR_FORMS, PERSON_FORMS_N, POSSESSIVE_FORMS); Abl_dAn.add(COPULAR_FORMS, PERSON_FORMS_N); Abl_ndAn.add(COPULAR_FORMS, PERSON_FORMS_N); Gen_nIn.add(COPULAR_FORMS, PERSON_FORMS_N).add(Rel_ki); A1sg_yIm.add(Cop_dIr); A2sg_sIn.add(Cop_dIr); A3sg_EMPTY.add(Cop_dIr); A1pl_yIz.add(Cop_dIr); A2pl_sInIz.add(Cop_dIr); A3pl_lAr.add(Pl_lAr.getSuccSetCopy()); A3pl_Comp_lAr.add(Pl_lAr.getSuccSetCopy()); Dim_cIk.add(Loc_dA, Abl_dAn, Inst_ylA, P3pl_lArI, A2sg_sIn, A2pl_sInIz, A3pl_lAr, Pl_lAr, Inst_ylA).add(COPULAR_FORMS); Dim2_cAgIz.add(CASE_FORMS, COPULAR_FORMS, POSSESSIVE_FORMS, PERSON_FORMS_N).add(Pl_lAr); With_lI.add(CASE_FORMS, COPULAR_FORMS, POSSESSIVE_FORMS, PERSON_FORMS_N).add(Pl_lAr, Ness_lIk, Become_lAs, Ly_cA); Without_sIz.add(CASE_FORMS, COPULAR_FORMS, POSSESSIVE_FORMS, PERSON_FORMS_N).add(Pl_lAr, Ness_lIk, Become_lAs, Ly_cA); Resemb_msI.add(CASE_FORMS, PERSON_FORMS_N, COPULAR_FORMS, POSSESSIVE_FORMS) .add(Pl_lAr, Ness_lIk, With_lI, Without_sIz, Become_lAs); Resemb_ImsI.add(Resemb_ImsI.getSuccSetCopy()); Ness_lIk.add(CASE_FORMS, POSSESSIVE_FORMS, COPULAR_FORMS, CASE_FORMS).add(Pl_lAr, Agt_cI, With_lI, Without_sIz, Equ_cA); Related_sAl.add(Adj_Main.getSuccSetCopy()).remove(Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Related_sAl, Resemb_msI, Resemb_msI); PastCop_ydI.add(PERSON_FORMS_COP); EvidCop_ymIs.add(A1sg_yIm, A2sg_sIn, A3sg_EMPTY, A1pl_yIz, A2pl_sInIz, A3pl_lAr, AsIf_cAsInA); CondCop_ysA.add(PERSON_FORMS_COP); Cop_dIr.add(A3pl_lAr); Neg_mA.add(Aor_z, AorPart_z, Aor_EMPTY, Prog2_mAktA, Imp_EMPTY, Opt_yA, Des_sA, Fut_yAcAk, Past_dI, Evid_mIs, Cond_sA, Abil_yAbil, Necess_mAlI, NotState_mAzlIk, ActOf_mAcA, PastPart_dIk, FutPart_yAcAk, EvidPart_mIs, Agt_yIcI) .add(AsLongAs_dIkcA, PresPart_yAn) .add(Inf1_mAk, Inf2_mA, Inf3_yIs) .add(When_yIncA, FeelLike_yAsI, SinceDoing_yAlI, ByDoing_yArAk, WithoutDoing2_mAksIzIn) .add(AfterDoing_yIp, When_yIncA, InsteadOfDoing_mAktAnsA) .add(KeepDoing2_yAdur, KeepDoing_yAgor, EverSince_yAgel, Hastily_yIver); Neg_m.add(Prog_Iyor); Aor_Ar.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA); Aor_Ir.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA); Aor_z.add(COPULAR_FORMS).add(A3sg_sIn, Cond_sA); Aor_EMPTY.add(A1sg_m, A1pl_yIz); Set<SuffixFormSet> noParticipleSuff = Sets.newHashSet(Become_lAs, Dim_cIk, Dim2_cAgIz, With_lI, Without_sIz, Related_sAl, Resemb_msI, Resemb_msI); AorPart_Ar.add(Adj_Main.getSuccSetCopy()).remove(noParticipleSuff).add(AsIf_cAsInA); AorPart_Ir.add(AorPart_Ar.getSuccSetCopy()); AorPart_z.add(AorPart_Ar.getSuccSetCopy()); FutPart_yAcAk.add(Adj_Exp_C.getSuccSetCopy()); NotState_mAzlIk.add(Adj_Exp_C.getSuccSetCopy()); PresPart_yAn.add(AorPart_Ar.getSuccSetCopy()); EvidPart_mIs.add(AorPart_Ar.getSuccSetCopy()); PastPart_dIk.add(Adj_Exp_C.getSuccSetCopy()).remove(AsIf_cAsInA).remove(noParticipleSuff); Prog_Iyor.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA); Prog2_mAktA.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA); Fut_yAcAk.add(PERSON_FORMS_N, COPULAR_FORMS).add(Cond_sA, AsIf_cAsInA); Past_dI.add(A1sg_m, A2sg_n, A3sg_EMPTY, A1pl_k, A2pl_nIz, A3pl_lAr, CondCop_ysA, PastCop_ydI); Evid_mIs.add(PERSON_FORMS_N).add(CondCop_ysA, PastCop_ydI, EvidCop_ymIs, While_ken, Cop_dIr); Cond_sA.add(A1sg_m, A2sg_n, A3sg_EMPTY, A1pl_k, A2pl_nIz, A3pl_lAr, PastCop_ydI, EvidCop_ymIs); Imp_EMPTY.add(A2sg_EMPTY, A2sg2_sAnA, A2sg3_yInIz, A2pl2_sAnIzA, A2pl_yIn, A3sg_sIn, A3pl_sInlAr); Imp_EMPTY_C.add(A2sg_EMPTY, A2sg2_sAnA, A2pl2_sAnIzA, A3sg_sIn, A3pl_sInlAr); Imp_EMPTY_V.add(A2sg3_yInIz, A2pl_yIn); Agt_cI.add(CASE_FORMS, PERSON_FORMS_N, POSSESSIVE_FORMS, COPULAR_FORMS).add(Pl_lAr, Become_lAs, With_lI, Without_sIz, Ness_lIk); Agt_yIcI.add(Agt_cI.getSuccSetCopy()); Abil_yAbil.add(Verb_Main.getSuccSetCopy()).remove(Abil_yAbil, Abil_yA, Neg_mA, Pass_nIl).add(Cond_sA, Pass_In); Abil_yA.add(Neg_mA, Neg_m); Opt_yA.add(A1sg_yIm, A2sg_sIn, A3sg_EMPTY, A1pl_lIm, A2pl_sInIz, A3pl_lAr); Des_sA.add(COPULAR_FORMS).add(A1sg_m, A2sg_n, A3sg_EMPTY, A1pl_k, A2pl_nIz, A3pl_lAr, PastCop_ydI, EvidCop_ymIs); Caus_t.add(Verb_Main.getSuccSetCopy()).add(Pass_nIl); Caus_tIr.add(Verb_Main.getSuccSetCopy()).remove(Caus_tIr).add(Caus_t, Pass_nIl); Pass_nIl.add(Verb_Main.getSuccSetCopy()).remove(Pass_In, Pass_nIl, Caus_tIr).add(Caus_t); Pass_In.add(Verb_Main.getSuccSetCopy()).remove(Pass_In); Reflex_In.add(Verb_Main.getSuccSetCopy()); Recip_Is.add(Verb_Main.getSuccSetCopy()).remove(Recip_Is); Recip_yIs.add(Verb_Main.getSuccSetCopy()).remove(Recip_Is); Inf1_mAk.add(COPULAR_FORMS).add(Abl_dAn, Loc_dA, Inst_ylA); Inf2_mA.add(Noun_Main.getSuccessors()); Inf3_yIs.add(Noun_Main.getSuccessors()); NounDeriv_nIm.add(Noun_Main.getSuccSetCopy()); When_yIncA.add(Dat_yA); While_ken.add(Rel_ki).add(PastCop_ydI, EvidCop_ymIs, CondCop_ysA); FeelLike_yAsI.add(POSSESSIVE_FORMS).add(COPULAR_FORMS); KeepDoing_yAgor.add(Neg_mA.getSuccSetCopy()).remove(Aor_z).add(Neg_mA, Neg_m, Aor_Ir, Prog_Iyor); KeepDoing2_yAdur.add(KeepDoing_yAgor.getSuccSetCopy()); EverSince_yAgel.add(KeepDoing_yAgor.getSuccSetCopy()); Almost_yAyAz.add(KeepDoing_yAgor.getSuccSetCopy()); Hastily_yIver.add(KeepDoing_yAgor.getSuccSetCopy()); Stay_yAkal.add(KeepDoing_yAgor.getSuccSetCopy()); Necess_mAlI.add(COPULAR_FORMS, PERSON_FORMS_N); */ }
diff --git a/connectors/juli/src/java/org/apache/juli/FileHandler.java b/connectors/juli/src/java/org/apache/juli/FileHandler.java index a867e194..7e30587a 100644 --- a/connectors/juli/src/java/org/apache/juli/FileHandler.java +++ b/connectors/juli/src/java/org/apache/juli/FileHandler.java @@ -1,312 +1,313 @@ /* * 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.juli; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.sql.Timestamp; import java.util.logging.ErrorManager; import java.util.logging.Filter; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.LogRecord; import java.util.logging.SimpleFormatter; /** * Implementation of <b>Handler</b> that appends log messages to a file * named {prefix}{date}{suffix} in a configured directory. * * <p>The following configuration properties are available:</p> * * <ul> * <li><code>directory</code> - The directory where to create the log file. * If the path is not absolute, it is relative to the current working * directory of the application. The Apache Tomcat configuration files usually * specify an absolute path for this property, * <code>${catalina.base}/logs</code> * Default value: <code>logs</code></li> * <li><code>prefix</code> - The leading part of the log file name. * Default value: <code>juli.</code></li> * <li><code>suffix</code> - The trailing part of the log file name. * Default value: <code>.log</code></li> * <li><code>encoding</code> - Character set used by the log file. Default value: * empty string, which means to use the system default character set.</li> * <li><code>level</code> - The level threshold for this Handler. See the * <code>java.util.logging.Level</code> class for the possible levels. * Default value: <code>ALL</code></li> * <li><code>filter</code> - The <code>java.util.logging.Filter</code> * implementation class name for this Handler. Default value: unset</li> * <li><code>formatter</code> - The <code>java.util.logging.Formatter</code> * implementation class name for this Handler. Default value: * <code>java.util.logging.SimpleFormatter</code></li> * </ul> * * @version $Id$ */ public class FileHandler extends Handler { // ------------------------------------------------------------ Constructor public FileHandler() { this(null, null, null); } public FileHandler(String directory, String prefix, String suffix) { this.directory = directory; this.prefix = prefix; this.suffix = suffix; configure(); open(); } // ----------------------------------------------------- Instance Variables /** * The as-of date for the currently open log file, or a zero-length * string if there is no open log file. */ private String date = ""; /** * The directory in which log files are created. */ private String directory = null; /** * The prefix that is added to log file filenames. */ private String prefix = null; /** * The suffix that is added to log file filenames. */ private String suffix = null; /** * The PrintWriter to which we are currently logging, if any. */ private PrintWriter writer = null; // --------------------------------------------------------- Public Methods /** * Format and publish a <tt>LogRecord</tt>. * * @param record description of the log event */ public void publish(LogRecord record) { if (!isLoggable(record)) { return; } // Construct the timestamp we will use, if requested Timestamp ts = new Timestamp(System.currentTimeMillis()); String tsString = ts.toString().substring(0, 19); String tsDate = tsString.substring(0, 10); // If the date has changed, switch log files if (!date.equals(tsDate)) { synchronized (this) { if (!date.equals(tsDate)) { close(); date = tsDate; open(); } } } String result = null; try { result = getFormatter().format(record); } catch (Exception e) { reportError(null, e, ErrorManager.FORMAT_FAILURE); return; } try { writer.write(result); writer.flush(); } catch (Exception e) { reportError(null, e, ErrorManager.WRITE_FAILURE); return; } } // -------------------------------------------------------- Private Methods /** * Close the currently open log file (if any). */ public void close() { try { if (writer == null) return; writer.write(getFormatter().getTail(this)); writer.flush(); writer.close(); writer = null; date = ""; } catch (Exception e) { reportError(null, e, ErrorManager.CLOSE_FAILURE); } } /** * Flush the writer. */ public void flush() { try { writer.flush(); } catch (Exception e) { reportError(null, e, ErrorManager.FLUSH_FAILURE); } } /** * Configure from <code>LogManager</code> properties. */ private void configure() { Timestamp ts = new Timestamp(System.currentTimeMillis()); String tsString = ts.toString().substring(0, 19); date = tsString.substring(0, 10); String className = FileHandler.class.getName(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); // Retrieve configuration of logging file name if (directory == null) directory = getProperty(className + ".directory", "logs"); if (prefix == null) prefix = getProperty(className + ".prefix", "juli."); if (suffix == null) suffix = getProperty(className + ".suffix", ".log"); // Get encoding for the logging file String encoding = getProperty(className + ".encoding", null); if (encoding != null && encoding.length() > 0) { try { setEncoding(encoding); } catch (UnsupportedEncodingException ex) { // Ignore } } // Get logging level for the handler setLevel(Level.parse(getProperty(className + ".level", "" + Level.ALL))); // Get filter configuration String filterName = getProperty(className + ".filter", null); if (filterName != null) { try { setFilter((Filter) cl.loadClass(filterName).newInstance()); } catch (Exception e) { // Ignore } } // Set formatter String formatterName = getProperty(className + ".formatter", null); if (formatterName != null) { try { setFormatter((Formatter) cl.loadClass(formatterName).newInstance()); } catch (Exception e) { - // Ignore + // Ignore and fallback to defaults + setFormatter(new SimpleFormatter()); } } else { setFormatter(new SimpleFormatter()); } // Set error manager setErrorManager(new ErrorManager()); } private String getProperty(String name, String defaultValue) { String value = LogManager.getLogManager().getProperty(name); if (value == null) { value = defaultValue; } else { value = value.trim(); } return value; } /** * Open the new log file for the date specified by <code>date</code>. */ private void open() { // Create the directory if necessary File dir = new File(directory); dir.mkdirs(); // Open the current log file try { String pathname = dir.getAbsolutePath() + File.separator + prefix + date + suffix; String encoding = getEncoding(); OutputStream os = new BufferedOutputStream(new FileOutputStream( pathname, true)); writer = new PrintWriter( (encoding != null) ? new OutputStreamWriter(os, encoding) : new OutputStreamWriter(os), true); writer.write(getFormatter().getHead(this)); } catch (Exception e) { reportError(null, e, ErrorManager.OPEN_FAILURE); writer = null; } } }
true
true
private void configure() { Timestamp ts = new Timestamp(System.currentTimeMillis()); String tsString = ts.toString().substring(0, 19); date = tsString.substring(0, 10); String className = FileHandler.class.getName(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); // Retrieve configuration of logging file name if (directory == null) directory = getProperty(className + ".directory", "logs"); if (prefix == null) prefix = getProperty(className + ".prefix", "juli."); if (suffix == null) suffix = getProperty(className + ".suffix", ".log"); // Get encoding for the logging file String encoding = getProperty(className + ".encoding", null); if (encoding != null && encoding.length() > 0) { try { setEncoding(encoding); } catch (UnsupportedEncodingException ex) { // Ignore } } // Get logging level for the handler setLevel(Level.parse(getProperty(className + ".level", "" + Level.ALL))); // Get filter configuration String filterName = getProperty(className + ".filter", null); if (filterName != null) { try { setFilter((Filter) cl.loadClass(filterName).newInstance()); } catch (Exception e) { // Ignore } } // Set formatter String formatterName = getProperty(className + ".formatter", null); if (formatterName != null) { try { setFormatter((Formatter) cl.loadClass(formatterName).newInstance()); } catch (Exception e) { // Ignore } } else { setFormatter(new SimpleFormatter()); } // Set error manager setErrorManager(new ErrorManager()); }
private void configure() { Timestamp ts = new Timestamp(System.currentTimeMillis()); String tsString = ts.toString().substring(0, 19); date = tsString.substring(0, 10); String className = FileHandler.class.getName(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); // Retrieve configuration of logging file name if (directory == null) directory = getProperty(className + ".directory", "logs"); if (prefix == null) prefix = getProperty(className + ".prefix", "juli."); if (suffix == null) suffix = getProperty(className + ".suffix", ".log"); // Get encoding for the logging file String encoding = getProperty(className + ".encoding", null); if (encoding != null && encoding.length() > 0) { try { setEncoding(encoding); } catch (UnsupportedEncodingException ex) { // Ignore } } // Get logging level for the handler setLevel(Level.parse(getProperty(className + ".level", "" + Level.ALL))); // Get filter configuration String filterName = getProperty(className + ".filter", null); if (filterName != null) { try { setFilter((Filter) cl.loadClass(filterName).newInstance()); } catch (Exception e) { // Ignore } } // Set formatter String formatterName = getProperty(className + ".formatter", null); if (formatterName != null) { try { setFormatter((Formatter) cl.loadClass(formatterName).newInstance()); } catch (Exception e) { // Ignore and fallback to defaults setFormatter(new SimpleFormatter()); } } else { setFormatter(new SimpleFormatter()); } // Set error manager setErrorManager(new ErrorManager()); }
diff --git a/src/main/java/com/wormhole_xtreme/wormhole/model/StargateShapeLayer.java b/src/main/java/com/wormhole_xtreme/wormhole/model/StargateShapeLayer.java index 264d50f..7004134 100644 --- a/src/main/java/com/wormhole_xtreme/wormhole/model/StargateShapeLayer.java +++ b/src/main/java/com/wormhole_xtreme/wormhole/model/StargateShapeLayer.java @@ -1,146 +1,145 @@ package com.wormhole_xtreme.wormhole.model; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.wormhole_xtreme.wormhole.WormholeXTreme; public class StargateShapeLayer { /** The stargate_positions. */ public ArrayList<Integer[]> blockPositions = new ArrayList<Integer[]>(); /** The sign_position. */ public int[] signPosition = null; /** The enter_position. */ public int[] enterPosition = null; /** The enter_position. */ public int[] activationPosition = null; /** The enter_position. */ public int[] irisActivationPosition = null; /** The enter_position. */ public int[] dialerPosition = null; /** Position of point that allows gate to be activated via redstone. */ public int[] redstoneActivationPosition = null; /** Position of point that allows gate to cycle sign targets via redstone */ public int[] redstoneDialerActivationPosition = null; /** The light_positions. */ public ArrayList<ArrayList<Integer[]>> lightPositions = new ArrayList<ArrayList<Integer[]>>(); /** The positions of woosh. First array is the order to activate them. Inner array is list of points */ public ArrayList<ArrayList<Integer[]>> wooshPositions = new ArrayList<ArrayList<Integer[]>>(); /** The water_positions. */ public ArrayList<Integer[]> portalPositions = new ArrayList<Integer[]>(); public StargateShapeLayer(String[] layerLines, int height, int width) { int numBlocks = 0; // 1. scan all lines for lines beginning with [ - that is the height of the gate for ( int i = 0; i < layerLines.length; i++ ) { - Pattern p = Pattern.compile("(\\[.*?\\])"); + Pattern p = Pattern.compile("\\[(.+?)\\]"); Matcher m = p.matcher(layerLines[i]); int j = 0; while ( m.find() ) { - String block = m.group(0); + String block = m.group(1); Integer[] point = { 0, (height - 1 - i), (width - 1 - j) }; String[] modifiers = block.split(":"); for ( String mod : modifiers ) { - WormholeXTreme.getThisPlugin().prettyLog(Level.FINE, false, "START: " + mod ); if ( mod.equals("S") ) { numBlocks++; this.blockPositions.add(point); } else if ( mod.equals("P") ) { this.portalPositions.add(point); } else if ( mod.equals("N") || mod.equals("E") || mod.equals("A") || mod.equals("D") || mod.equals("IA") ) { int[] pointI = new int[3]; for (int k = 0; k < 3; k++ ) pointI[k] = point[k]; if ( mod.equals("N") ) { this.signPosition = pointI; } if ( mod.equals("E") ) { this.enterPosition = pointI; } if ( mod.equals("A") ) { this.activationPosition = pointI; } if ( mod.equals("D") ) { this.dialerPosition = pointI; } if ( mod.equals("IA") ) { this.irisActivationPosition = pointI; } if ( mod.equals("RA") ) { this.redstoneActivationPosition = pointI; } if ( mod.equals("RD") ) { this.redstoneDialerActivationPosition = pointI; } } else if ( mod.equals("L") ) { String[] light_parts = mod.split("#"); int light_iteration = Integer.parseInt(light_parts[1]); if ( this.lightPositions.get(light_iteration) == null ) { ArrayList<Integer[]> new_it = new ArrayList<Integer[]>(); while( this.lightPositions.size() < light_iteration) this.lightPositions.add(null); this.lightPositions.set(light_iteration, new_it); } this.lightPositions.get(light_iteration).add(point); } else if ( mod.equals("W") ) { String[] w_parts = mod.split("#"); int w_iteration = Integer.parseInt(w_parts[1]); if ( this.wooshPositions.get(w_iteration) == null ) { ArrayList<Integer[]> new_it = new ArrayList<Integer[]>(); while( this.wooshPositions.size() < w_iteration) this.wooshPositions.add(null); this.wooshPositions.set(w_iteration, new_it); } this.wooshPositions.get(w_iteration).add(point); } } j++; } } //TODO: debug printout for the materials the gate uses. //TODO: debug printout for the redstone_activated WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Sign Position: \"" + Arrays.toString(signPosition) + "\""); WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Enter Position: \"" + Arrays.toString(enterPosition) + "\""); WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Activation Position: \"" + Arrays.toString(activationPosition) + "\""); WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Activation Position: \"" + Arrays.toString(irisActivationPosition) + "\""); //WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Portal Positions: \"" + Arrays.deepToString((int[][])this.waterPositions) + "\""); WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Light Material Positions: \"" + lightPositions.toString() + "\""); //WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Material Positions: \"" + Arrays.deepToString((int[][])this.stargatePositions) + "\""); } }
false
true
public StargateShapeLayer(String[] layerLines, int height, int width) { int numBlocks = 0; // 1. scan all lines for lines beginning with [ - that is the height of the gate for ( int i = 0; i < layerLines.length; i++ ) { Pattern p = Pattern.compile("(\\[.*?\\])"); Matcher m = p.matcher(layerLines[i]); int j = 0; while ( m.find() ) { String block = m.group(0); Integer[] point = { 0, (height - 1 - i), (width - 1 - j) }; String[] modifiers = block.split(":"); for ( String mod : modifiers ) { WormholeXTreme.getThisPlugin().prettyLog(Level.FINE, false, "START: " + mod ); if ( mod.equals("S") ) { numBlocks++; this.blockPositions.add(point); } else if ( mod.equals("P") ) { this.portalPositions.add(point); } else if ( mod.equals("N") || mod.equals("E") || mod.equals("A") || mod.equals("D") || mod.equals("IA") ) { int[] pointI = new int[3]; for (int k = 0; k < 3; k++ ) pointI[k] = point[k]; if ( mod.equals("N") ) { this.signPosition = pointI; } if ( mod.equals("E") ) { this.enterPosition = pointI; } if ( mod.equals("A") ) { this.activationPosition = pointI; } if ( mod.equals("D") ) { this.dialerPosition = pointI; } if ( mod.equals("IA") ) { this.irisActivationPosition = pointI; } if ( mod.equals("RA") ) { this.redstoneActivationPosition = pointI; } if ( mod.equals("RD") ) { this.redstoneDialerActivationPosition = pointI; } } else if ( mod.equals("L") ) { String[] light_parts = mod.split("#"); int light_iteration = Integer.parseInt(light_parts[1]); if ( this.lightPositions.get(light_iteration) == null ) { ArrayList<Integer[]> new_it = new ArrayList<Integer[]>(); while( this.lightPositions.size() < light_iteration) this.lightPositions.add(null); this.lightPositions.set(light_iteration, new_it); } this.lightPositions.get(light_iteration).add(point); } else if ( mod.equals("W") ) { String[] w_parts = mod.split("#"); int w_iteration = Integer.parseInt(w_parts[1]); if ( this.wooshPositions.get(w_iteration) == null ) { ArrayList<Integer[]> new_it = new ArrayList<Integer[]>(); while( this.wooshPositions.size() < w_iteration) this.wooshPositions.add(null); this.wooshPositions.set(w_iteration, new_it); } this.wooshPositions.get(w_iteration).add(point); } } j++; } } //TODO: debug printout for the materials the gate uses. //TODO: debug printout for the redstone_activated WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Sign Position: \"" + Arrays.toString(signPosition) + "\""); WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Enter Position: \"" + Arrays.toString(enterPosition) + "\""); WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Activation Position: \"" + Arrays.toString(activationPosition) + "\""); WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Activation Position: \"" + Arrays.toString(irisActivationPosition) + "\""); //WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Portal Positions: \"" + Arrays.deepToString((int[][])this.waterPositions) + "\""); WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Light Material Positions: \"" + lightPositions.toString() + "\""); //WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Material Positions: \"" + Arrays.deepToString((int[][])this.stargatePositions) + "\""); }
public StargateShapeLayer(String[] layerLines, int height, int width) { int numBlocks = 0; // 1. scan all lines for lines beginning with [ - that is the height of the gate for ( int i = 0; i < layerLines.length; i++ ) { Pattern p = Pattern.compile("\\[(.+?)\\]"); Matcher m = p.matcher(layerLines[i]); int j = 0; while ( m.find() ) { String block = m.group(1); Integer[] point = { 0, (height - 1 - i), (width - 1 - j) }; String[] modifiers = block.split(":"); for ( String mod : modifiers ) { if ( mod.equals("S") ) { numBlocks++; this.blockPositions.add(point); } else if ( mod.equals("P") ) { this.portalPositions.add(point); } else if ( mod.equals("N") || mod.equals("E") || mod.equals("A") || mod.equals("D") || mod.equals("IA") ) { int[] pointI = new int[3]; for (int k = 0; k < 3; k++ ) pointI[k] = point[k]; if ( mod.equals("N") ) { this.signPosition = pointI; } if ( mod.equals("E") ) { this.enterPosition = pointI; } if ( mod.equals("A") ) { this.activationPosition = pointI; } if ( mod.equals("D") ) { this.dialerPosition = pointI; } if ( mod.equals("IA") ) { this.irisActivationPosition = pointI; } if ( mod.equals("RA") ) { this.redstoneActivationPosition = pointI; } if ( mod.equals("RD") ) { this.redstoneDialerActivationPosition = pointI; } } else if ( mod.equals("L") ) { String[] light_parts = mod.split("#"); int light_iteration = Integer.parseInt(light_parts[1]); if ( this.lightPositions.get(light_iteration) == null ) { ArrayList<Integer[]> new_it = new ArrayList<Integer[]>(); while( this.lightPositions.size() < light_iteration) this.lightPositions.add(null); this.lightPositions.set(light_iteration, new_it); } this.lightPositions.get(light_iteration).add(point); } else if ( mod.equals("W") ) { String[] w_parts = mod.split("#"); int w_iteration = Integer.parseInt(w_parts[1]); if ( this.wooshPositions.get(w_iteration) == null ) { ArrayList<Integer[]> new_it = new ArrayList<Integer[]>(); while( this.wooshPositions.size() < w_iteration) this.wooshPositions.add(null); this.wooshPositions.set(w_iteration, new_it); } this.wooshPositions.get(w_iteration).add(point); } } j++; } } //TODO: debug printout for the materials the gate uses. //TODO: debug printout for the redstone_activated WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Sign Position: \"" + Arrays.toString(signPosition) + "\""); WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Enter Position: \"" + Arrays.toString(enterPosition) + "\""); WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Activation Position: \"" + Arrays.toString(activationPosition) + "\""); WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Activation Position: \"" + Arrays.toString(irisActivationPosition) + "\""); //WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Portal Positions: \"" + Arrays.deepToString((int[][])this.waterPositions) + "\""); WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Light Material Positions: \"" + lightPositions.toString() + "\""); //WormholeXTreme.getThisPlugin().prettyLog(Level.CONFIG, false, "Stargate Material Positions: \"" + Arrays.deepToString((int[][])this.stargatePositions) + "\""); }
diff --git a/BetterBatteryStats/src/com/asksven/betterbatterystats/StatsActivity.java b/BetterBatteryStats/src/com/asksven/betterbatterystats/StatsActivity.java index 24b4f005..c4c5f55e 100644 --- a/BetterBatteryStats/src/com/asksven/betterbatterystats/StatsActivity.java +++ b/BetterBatteryStats/src/com/asksven/betterbatterystats/StatsActivity.java @@ -1,1213 +1,1212 @@ /* * Copyright (C) 2011-2012 asksven * * 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.asksven.betterbatterystats; /** * @author sven * */ import java.util.ArrayList; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.app.NotificationManager; import android.app.ProgressDialog; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.pm.PackageInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.preference.CheckBoxPreference; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.asksven.android.common.AppRater; import com.asksven.android.common.CommonLogSettings; import com.asksven.android.common.ReadmeActivity; import com.asksven.android.common.utils.DataStorage; import com.asksven.android.common.utils.DateUtils; import com.asksven.android.common.utils.SysUtils; import com.asksven.android.common.privateapiproxies.BatteryInfoUnavailableException; import com.asksven.android.common.privateapiproxies.BatteryStatsProxy; import com.asksven.betterbatterystats.R; import com.asksven.betterbatterystats.adapters.ReferencesAdapter; import com.asksven.betterbatterystats.adapters.StatsAdapter; import com.asksven.betterbatterystats.data.GoogleAnalytics; import com.asksven.betterbatterystats.data.Reading; import com.asksven.betterbatterystats.data.Reference; import com.asksven.betterbatterystats.data.ReferenceDBHelper; import com.asksven.betterbatterystats.data.ReferenceStore; import com.asksven.betterbatterystats.data.StatsProvider; import com.asksven.betterbatterystats.services.EventWatcherService; import com.asksven.betterbatterystats.services.WriteCurrentReferenceService; import com.asksven.betterbatterystats.services.WriteCustomReferenceService; import com.asksven.betterbatterystats.services.WriteScreenOffReferenceService; import com.asksven.betterbatterystats.services.WriteUnpluggedReferenceService; import com.asksven.betterbatterystats.services.WriteBootReferenceService; public class StatsActivity extends ListActivity implements AdapterView.OnItemSelectedListener, OnSharedPreferenceChangeListener { public static String STAT = "STAT"; public static String STAT_TYPE_FROM = "STAT_TYPE_FROM"; public static String STAT_TYPE_TO = "STAT_TYPE_TO"; public static String FROM_NOTIFICATION = "FROM_NOTIFICATION"; /** * The logging TAG */ private static final String TAG = "StatsActivity"; /** * The logfile TAG */ private static final String LOGFILE = "BetterBatteryStats_Dump.log"; /** * a progess dialog to be used for long running tasks */ ProgressDialog m_progressDialog; /** * The ArrayAdpater for rendering the ListView */ private StatsAdapter m_listViewAdapter; private ReferencesAdapter m_spinnerFromAdapter; private ReferencesAdapter m_spinnerToAdapter; /** * The Type of Stat to be displayed (default is "Since charged") */ // private int m_iStatType = 0; private String m_refFromName = ""; private String m_refToName = Reference.CURRENT_REF_FILENAME; /** * The Stat to be displayed (default is "Process") */ private int m_iStat = 0; /** * the selected sorting */ private int m_iSorting = 0; private BroadcastReceiver m_referenceSavedReceiver = null; /** * @see android.app.Activity#onCreate(Bundle@SuppressWarnings("rawtypes") */ @Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "OnCreated called"); super.onCreate(savedInstanceState); setContentView(R.layout.stats); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); // set debugging if (sharedPrefs.getBoolean("debug_logging", false)) { LogSettings.DEBUG=true; CommonLogSettings.DEBUG=true; } else { LogSettings.DEBUG=false; CommonLogSettings.DEBUG=false; } /////////////////////////////////////////////// // check if we have a new release /////////////////////////////////////////////// // if yes do some migration (if required) and show release notes String strLastRelease = sharedPrefs.getString("last_release", "0"); String strCurrentRelease = ""; try { PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0); strCurrentRelease = Integer.toString(pinfo.versionCode); } catch (Exception e) { // nop strCurrentRelease is set to "" } if (strLastRelease.equals("0")) { // show the initial run screen FirstLaunch.app_launched(this); SharedPreferences.Editor updater = sharedPrefs.edit(); updater.putString("last_release", strCurrentRelease); updater.commit(); } else if (!strLastRelease.equals(strCurrentRelease)) { // save the current release to properties so that the dialog won't be shown till next version SharedPreferences.Editor updater = sharedPrefs.edit(); updater.putString("last_release", strCurrentRelease); updater.commit(); Toast.makeText(this, "Deleting and re-creating references", Toast.LENGTH_SHORT).show(); ReferenceStore.deleteAllRefs(this); Intent i = new Intent(this, WriteBootReferenceService.class); this.startService(i); i = new Intent(this, WriteUnpluggedReferenceService.class); this.startService(i); // Show Kitkat info if ( (Build.VERSION.SDK_INT >= 19) && !SysUtils.hasBatteryStatsPermission(this) ) { // prepare the alert box AlertDialog.Builder alertbox = new AlertDialog.Builder(this); // set the message to display - alertbox.setMessage("Since google has revoked rights for apps to access the battery stats without" - + " root partial wakelocks will not be available anymore for non rooted users." - + " See <a href=\"http://forum.xda-developers.com/showthread.php?t=2529455\">here</a> for more info."); + alertbox.setMessage("Google has revoked rights for apps to access the battery stats without" + + " root. Partial wakelocks will not be available anymore for non rooted users. Please make sure to enable the root advanced options if you have root."); // add a neutral button to the alert box and assign a click listener alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() { // click listener on the alert box public void onClick(DialogInterface arg0, int arg1) { } }); // show it alertbox.show(); } } else { // can't do this at the same time as the popup dialog would be masked by the readme /////////////////////////////////////////////// // check if we have shown the opt-out from analytics /////////////////////////////////////////////// boolean bWarningShown = sharedPrefs.getBoolean("analytics_opt_out", false); boolean bAnalyticsEnabled = sharedPrefs.getBoolean("use_analytics", true); if (bAnalyticsEnabled && !bWarningShown) { // prepare the alert box AlertDialog.Builder alertbox = new AlertDialog.Builder(this); // set the message to display alertbox.setMessage("BetterBatteryStats makes use of Google Analytics to collect usage statitics. If you disagree or do not want to participate you can opt-out by disabling \"Google Analytics\" in the \"Advanced Preferences\""); // add a neutral button to the alert box and assign a click listener alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() { // click listener on the alert box public void onClick(DialogInterface arg0, int arg1) { // opt out info was displayed SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(StatsActivity.this); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("analytics_opt_out", true); editor.commit(); } }); // show it alertbox.show(); } else { // show "rate" dialog // for testing: AppRater.showRateDialog(this, null); AppRater.app_launched(this); } } /////////////////////////////////////////////// // retrieve default selections for spinners // if none were passed /////////////////////////////////////////////// m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0")); m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME); if (!ReferenceStore.hasReferenceByName(m_refFromName, this)) { if (sharedPrefs.getBoolean("fallback_to_since_boot", false)) { m_refFromName = Reference.BOOT_REF_FILENAME; Toast.makeText(this, "Fallback to 'Since Boot'", Toast.LENGTH_SHORT).show(); } } try { // recover any saved state if ( (savedInstanceState != null) && (!savedInstanceState.isEmpty())) { m_iStat = (Integer) savedInstanceState.getSerializable("stat"); m_refFromName = (String) savedInstanceState.getSerializable("stattypeFrom"); m_refToName = (String) savedInstanceState.getSerializable("stattypeTo"); } } catch (Exception e) { m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0")); m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME); Log.e(TAG, "Exception: " + e.getMessage()); DataStorage.LogToFile(LOGFILE, "Exception in onCreate restoring Bundle"); DataStorage.LogToFile(LOGFILE, e.getMessage()); DataStorage.LogToFile(LOGFILE, e.getStackTrace()); Toast.makeText(this, "An error occured while recovering the previous state", Toast.LENGTH_SHORT).show(); } // Handle the case the Activity was called from an intent with paramaters Bundle extras = getIntent().getExtras(); if (extras != null) { // Override if some values were passed to the intent m_iStat = extras.getInt(StatsActivity.STAT); m_refFromName = extras.getString(StatsActivity.STAT_TYPE_FROM); m_refToName = extras.getString(StatsActivity.STAT_TYPE_TO); boolean bCalledFromNotification = extras.getBoolean(StatsActivity.FROM_NOTIFICATION, false); // Clear the notifications that was clicked to call the activity if (bCalledFromNotification) { NotificationManager nM = (NotificationManager)getSystemService(Service.NOTIFICATION_SERVICE); nM.cancel(EventWatcherService.NOTFICATION_ID); } } // Display the reference of the stat TextView tvSince = (TextView) findViewById(R.id.TextViewSince); if (tvSince != null) { Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, this); Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, this); long sinceMs = StatsProvider.getInstance(this).getSince(myReferenceFrom, myReferenceTo); if (sinceMs != -1) { String sinceText = DateUtils.formatDuration(sinceMs); boolean bShowBatteryLevels = sharedPrefs.getBoolean("show_batt", true); if (bShowBatteryLevels) { sinceText += " " + StatsProvider.getInstance(this).getBatteryLevelFromTo(myReferenceFrom, myReferenceTo); } tvSince.setText(sinceText); Log.i(TAG, "Since " + sinceText); } else { tvSince.setText("n/a"); Log.i(TAG, "Since: n/a "); } } // Spinner for selecting the stat Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat); ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource( this, R.array.stats, android.R.layout.simple_spinner_item); spinnerStatAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerStat.setAdapter(spinnerStatAdapter); // setSelection MUST be called after setAdapter spinnerStat.setSelection(m_iStat); spinnerStat.setOnItemSelectedListener(this); /////////////////////////////////////////////// // Spinner for Selecting the Stat type /////////////////////////////////////////////// Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType); m_spinnerFromAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item); m_spinnerFromAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerStatType.setAdapter(m_spinnerFromAdapter); try { this.setListViewAdapter(); } catch (BatteryInfoUnavailableException e) { // Log.e(TAG, e.getMessage(), e.fillInStackTrace()); Log.e(TAG, "Exception: "+Log.getStackTraceString(e)); Toast.makeText(this, "BatteryInfo Service could not be contacted.", Toast.LENGTH_LONG).show(); } catch (Exception e) { //Log.e(TAG, e.getMessage(), e.fillInStackTrace()); Log.e(TAG, "Exception: "+Log.getStackTraceString(e)); Toast.makeText(this, "An unhandled error occured. Please check your logcat", Toast.LENGTH_LONG).show(); } // setSelection MUST be called after setAdapter spinnerStatType.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName)); spinnerStatType.setOnItemSelectedListener(this); /////////////////////////////////////////////// // Spinner for Selecting the end sample /////////////////////////////////////////////// Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd); m_spinnerToAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item); m_spinnerToAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); boolean bShowSpinner = sharedPrefs.getBoolean("show_to_ref", true); if (bShowSpinner) { spinnerStatSampleEnd.setVisibility(View.VISIBLE); spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter); // setSelection must be called after setAdapter if ((m_refToName != null) && !m_refToName.equals("") ) { int pos = m_spinnerToAdapter.getPosition(m_refToName); spinnerStatSampleEnd.setSelection(pos); } else { spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME)); } } else { spinnerStatSampleEnd.setVisibility(View.GONE); spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter); // setSelection must be called after setAdapter spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME)); } spinnerStatSampleEnd.setOnItemSelectedListener(this); /////////////////////////////////////////////// // sorting /////////////////////////////////////////////// String strOrderBy = sharedPrefs.getString("default_orderby", "0"); try { m_iSorting = Integer.valueOf(strOrderBy); } catch(Exception e) { // handle error here m_iSorting = 0; } GoogleAnalytics.getInstance(this).trackStats(this, GoogleAnalytics.ACTIVITY_STATS, m_iStat, m_refFromName, m_refToName, m_iSorting); // Set up a listener whenever a key changes PreferenceManager.getDefaultSharedPreferences(this) .registerOnSharedPreferenceChangeListener(this); // log reference store ReferenceStore.logReferences(this); } /* Request updates at startup */ @Override protected void onResume() { Log.i(TAG, "OnResume called"); super.onResume(); // register the broadcast receiver IntentFilter intentFilter = new IntentFilter(ReferenceStore.REF_UPDATED); m_referenceSavedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //extract our message from intent String refName = intent.getStringExtra(Reference.EXTRA_REF_NAME); //log our message value Log.i(TAG, "Received broadcast, reference was updated:" + refName); // reload the spinners to make sure all refs are in the right sequence when current gets refreshed // if (refName.equals(Reference.CURRENT_REF_FILENAME)) // { refreshSpinners(); // } } }; //registering our receiver this.registerReceiver(m_referenceSavedReceiver, intentFilter); // the service is always started as it handles the widget updates too SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); boolean serviceShouldBeRunning = sharedPrefs.getBoolean("ref_for_screen_off", false); // we need to run the service also if we are on kitkat without root boolean rootEnabled = sharedPrefs.getBoolean("root_features", false); // if on kitkat make sure that we always collect screen on time: if no root then count the time if ( !rootEnabled && !SysUtils.hasBatteryStatsPermission(this) ) { serviceShouldBeRunning = true; } if (serviceShouldBeRunning) { if (!EventWatcherService.isServiceRunning(this)) { Intent i = new Intent(this, EventWatcherService.class); this.startService(i); } } // make sure to create a valid "current" stat if none exists // or if prefs re set to auto refresh boolean bAutoRefresh = sharedPrefs.getBoolean("auto_refresh", true); if ((bAutoRefresh) || (!ReferenceStore.hasReferenceByName(Reference.CURRENT_REF_FILENAME, this))) { Intent serviceIntent = new Intent(this, WriteCurrentReferenceService.class); this.startService(serviceIntent); doRefresh(true); } else { refreshSpinners(); doRefresh(false); } // check if active monitoring is on: if yes make sure the alarm is scheduled if (sharedPrefs.getBoolean("active_mon_enabled", false)) { if (!StatsProvider.isActiveMonAlarmScheduled(this)) { StatsProvider.scheduleActiveMonAlarm(this); } } } /* Remove the locationlistener updates when Activity is paused */ @Override protected void onPause() { super.onPause(); // unregister boradcast receiver for saved references this.unregisterReceiver(this.m_referenceSavedReceiver); // make sure to dispose any running dialog if (m_progressDialog != null) { m_progressDialog.dismiss(); m_progressDialog = null; } // this.unregisterReceiver(m_batteryHandler); } /** * Save state, the application is going to get moved out of memory * @see http://stackoverflow.com/questions/151777/how-do-i-save-an-android-applications-state */ @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putSerializable("stattypeFrom", m_refFromName); savedInstanceState.putSerializable("stattypeTo", m_refToName); savedInstanceState.putSerializable("stat", m_iStat); //StatsProvider.getInstance(this).writeToBundle(savedInstanceState); } /** * Add menu items * * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mainmenu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean bSortingEnabled = true; MenuItem sortCount = menu.findItem(R.id.by_count_desc); MenuItem sortTime = menu.findItem(R.id.by_time_desc); if (m_iSorting == 0) { // sorting is by time sortTime.setEnabled(false); sortCount.setEnabled(true); } else { // sorting is by count sortTime.setEnabled(true); sortCount.setEnabled(false); } if (m_iStat == 2) // @see arrays.xml, dependency to string-array name="stats" { // disable menu group bSortingEnabled = true; } else { // enable menu group bSortingEnabled = true; } menu.setGroupEnabled(R.id.sorting_group, bSortingEnabled); return true; } /** * Define menu action * * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.preferences: Intent intentPrefs = new Intent(this, PreferencesActivity.class); GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_PREFERENCES); this.startActivity(intentPrefs); break; case R.id.graph: Intent intentGraph = new Intent(this, BatteryGraphActivity.class); GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_BATTERY_GRAPH); this.startActivity(intentGraph); break; case R.id.rawstats: Intent intentRaw = new Intent(this, RawStatsActivity.class); GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_RAW); this.startActivity(intentRaw); break; case R.id.refresh: // Refresh ReferenceStore.rebuildCache(this); doRefresh(true); break; case R.id.custom_ref: // Set custom reference GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTION_SET_CUSTOM_REF); // start service to persist reference Intent serviceIntent = new Intent(this, WriteCustomReferenceService.class); this.startService(serviceIntent); break; case R.id.credits: Intent intentCredits = new Intent(this, CreditsActivity.class); this.startActivity(intentCredits); break; case R.id.by_time_desc: // Enable "count" option m_iSorting = 0; doRefresh(false); break; case R.id.by_count_desc: // Enable "count" option m_iSorting = 1; doRefresh(false); break; // case R.id.test: // Intent serviceIntent = new Intent(this, WriteUnpluggedReferenceService.class); // this.startService(serviceIntent); // break; case R.id.about: // About Intent intentAbout = new Intent(this, AboutActivity.class); GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_ABOUT); this.startActivity(intentAbout); break; case R.id.getting_started: // Help Intent intentHelp = new Intent(this, HelpActivity.class); GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_HELP); intentHelp.putExtra("filename", "help.html"); this.startActivity(intentHelp); break; case R.id.howto: // How To Intent intentHowTo = new Intent(this, HelpActivity.class); GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_HOWTO); intentHowTo.putExtra("filename", "howto.html"); this.startActivity(intentHowTo); break; case R.id.releasenotes: // Release notes Intent intentReleaseNotes = new Intent(this, ReadmeActivity.class); GoogleAnalytics.getInstance(this).trackPage(GoogleAnalytics.ACTIVITY_README); intentReleaseNotes.putExtra("filename", "readme.html"); this.startActivity(intentReleaseNotes); break; case R.id.share: // Share getShareDialog().show(); break; } return false; } /** * Take the change of selection from the spinners into account and refresh the ListView * with the right data */ public void onItemSelected(AdapterView<?> parent, View v, int position, long id) { // this method is fired even if nothing has changed so we nee to find that out SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); boolean bChanged = false; // id is in the order of the spinners, 0 is stat, 1 is stat_type if (parent == (Spinner) findViewById(R.id.spinnerStatType)) { // detect if something changed String newStat = (String) ( (ReferencesAdapter) parent.getAdapter()).getItemName(position); if ((m_refFromName != null) && ( !m_refFromName.equals(newStat) )) { Log.i(TAG, "Spinner from changed from " + m_refFromName + " to " + newStat); m_refFromName = newStat; bChanged = true; // we need to update the second spinner m_spinnerToAdapter.filterToSpinner(newStat, this); m_spinnerToAdapter.notifyDataSetChanged(); // select the right element Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd); if (spinnerStatSampleEnd.isShown()) { spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(m_refToName)); } else { spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME)); } } else { return; } } else if (parent == (Spinner) findViewById(R.id.spinnerStatSampleEnd)) { String newStat = (String) ( (ReferencesAdapter) parent.getAdapter()).getItemName(position); if ((m_refFromName != null) && ( !m_refToName.equals(newStat) )) { Log.i(TAG, "Spinner to changed from " + m_refToName + " to " + newStat); m_refToName = newStat; bChanged = true; } else { return; } } else if (parent == (Spinner) findViewById(R.id.spinnerStat)) { int iNewStat = position; if ( m_iStat != iNewStat ) { m_iStat = iNewStat; bChanged = true; } else { return; } // inform the user when he tries to use functions requiring root and he doesn't have root enabled boolean rootEnabled = sharedPrefs.getBoolean("root_features", false); if (!rootEnabled) { if ((m_iStat == 4) || (m_iStat == 3)) { Toast.makeText(this, "This function requires root access. Check \"Advanced\" preferences", Toast.LENGTH_LONG).show(); } } } else { Log.e(TAG, "ProcessStatsActivity.onItemSelected error. ID could not be resolved"); Toast.makeText(this, "Error: could not resolve what changed", Toast.LENGTH_SHORT).show(); } Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, this); Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, this); TextView tvSince = (TextView) findViewById(R.id.TextViewSince); // long sinceMs = getSince(); long sinceMs = StatsProvider.getInstance(this).getSince(myReferenceFrom, myReferenceTo); if (sinceMs != -1) { String sinceText = DateUtils.formatDuration(sinceMs); boolean bShowBatteryLevels = sharedPrefs.getBoolean("show_batt", true); if (bShowBatteryLevels) { sinceText += " " + StatsProvider.getInstance(this).getBatteryLevelFromTo(myReferenceFrom, myReferenceTo); } tvSince.setText(sinceText); Log.i(TAG, "Since " + sinceText); } else { tvSince.setText("n/a "); Log.i(TAG, "Since: n/a "); } // @todo fix this: this method is called twice //m_listViewAdapter.notifyDataSetChanged(); if (bChanged) { GoogleAnalytics.getInstance(this).trackStats(this, GoogleAnalytics.ACTIVITY_STATS, m_iStat, m_refFromName, m_refToName, m_iSorting); //new LoadStatData().execute(this); // as the source changed fetch the data doRefresh(false); } } public void onNothingSelected(AdapterView<?> parent) { // Log.i(TAG, "OnNothingSelected called"); // do nothing } public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (key.equals("show_to_ref")) { Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd); boolean bShowSpinner = prefs.getBoolean("show_to_ref", true); if (bShowSpinner) { spinnerStatSampleEnd.setVisibility(View.VISIBLE); } else { spinnerStatSampleEnd.setVisibility(View.GONE); } } } private void refreshSpinners() { // reload the spinners to make sure all refs are in the right sequence m_spinnerFromAdapter.refreshFromSpinner(this); m_spinnerToAdapter.filterToSpinner(m_refFromName, this); // after we reloaded the spinners we need to reset the selections Spinner spinnerStatTypeFrom = (Spinner) findViewById(R.id.spinnerStatType); Spinner spinnerStatTypeTo = (Spinner) findViewById(R.id.spinnerStatSampleEnd); Log.i(TAG, "refreshSpinners: reset spinner selections: from='" + m_refFromName + "', to='" + m_refToName + "'"); Log.i(TAG, "refreshSpinners Spinner values: SpinnerFrom=" + m_spinnerFromAdapter.getNames() + " SpinnerTo=" + m_spinnerToAdapter.getNames()); Log.i(TAG, "refreshSpinners: request selections: from='" + m_spinnerFromAdapter.getPosition(m_refFromName) + "', to='" + m_spinnerToAdapter.getPosition(m_refToName) + "'"); // restore positions spinnerStatTypeFrom.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName), true); if (spinnerStatTypeTo.isShown()) { spinnerStatTypeTo.setSelection(m_spinnerToAdapter.getPosition(m_refToName), true); } else { spinnerStatTypeTo.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME), true); } Log.i(TAG, "refreshSpinners result positions: from='" + spinnerStatTypeFrom.getSelectedItemPosition() + "', to='" + spinnerStatTypeTo.getSelectedItemPosition() + "'"); if ((spinnerStatTypeFrom.getSelectedItemPosition() == -1)||(spinnerStatTypeTo.getSelectedItemPosition() == -1)) { Toast.makeText(StatsActivity.this, "Selected 'from' or 'to' reference could not be loaded. Please refresh", Toast.LENGTH_LONG).show(); } } /** * In order to refresh the ListView we need to re-create the Adapter * (should be the case but notifyDataSetChanged doesn't work so * we recreate and set a new one) */ private void setListViewAdapter() throws Exception { // make sure we only instanciate when the reference does not exist if (m_listViewAdapter == null) { m_listViewAdapter = new StatsAdapter(this, StatsProvider.getInstance(this).getStatList(m_iStat, m_refFromName, m_iSorting, m_refToName)); setListAdapter(m_listViewAdapter); } } private void doRefresh(boolean updateCurrent) { if (Build.VERSION.SDK_INT < 19) BatteryStatsProxy.getInstance(this).invalidate(); refreshSpinners(); new LoadStatData().execute(updateCurrent); } // @see http://code.google.com/p/makemachine/source/browse/trunk/android/examples/async_task/src/makemachine/android/examples/async/AsyncTaskExample.java // for more details private class LoadStatData extends AsyncTask<Boolean, Integer, StatsAdapter> { private Exception m_exception = null; @Override protected StatsAdapter doInBackground(Boolean... refresh) { // do we need to refresh current if (refresh[0]) { // make sure to create a valid "current" stat StatsProvider.getInstance(StatsActivity.this).setCurrentReference(m_iSorting); } //super.doInBackground(params); m_listViewAdapter = null; try { Log.i(TAG, "LoadStatData: refreshing display for stats " + m_refFromName + " to " + m_refToName); m_listViewAdapter = new StatsAdapter( StatsActivity.this, StatsProvider.getInstance(StatsActivity.this).getStatList(m_iStat, m_refFromName, m_iSorting, m_refToName)); } catch (BatteryInfoUnavailableException e) { //Log.e(TAG, e.getMessage(), e.fillInStackTrace()); Log.e(TAG, "Exception: "+Log.getStackTraceString(e)); m_exception = e; } catch (Exception e) { //Log.e(TAG, e.getMessage(), e.fillInStackTrace()); Log.e(TAG, "Exception: "+Log.getStackTraceString(e)); m_exception = e; } //StatsActivity.this.setListAdapter(m_listViewAdapter); // getStatList(); return m_listViewAdapter; } // @Override protected void onPostExecute(StatsAdapter o) { // super.onPostExecute(o); // update hourglass try { if (m_progressDialog != null) { m_progressDialog.dismiss(); //hide(); m_progressDialog = null; } } catch (Exception e) { // nop } finally { m_progressDialog = null; } if (m_exception != null) { if (m_exception instanceof BatteryInfoUnavailableException) { Toast.makeText(StatsActivity.this, "BatteryInfo Service could not be contacted.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(StatsActivity.this, "An unknown error occured while retrieving stats.", Toast.LENGTH_LONG).show(); } } TextView tvSince = (TextView) findViewById(R.id.TextViewSince); Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, StatsActivity.this); Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, StatsActivity.this); long sinceMs = StatsProvider.getInstance(StatsActivity.this).getSince(myReferenceFrom, myReferenceTo); if (sinceMs != -1) { String sinceText = DateUtils.formatDuration(sinceMs); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(StatsActivity.this); boolean bShowBatteryLevels = sharedPrefs.getBoolean("show_batt", true); if (bShowBatteryLevels) { sinceText += " " + StatsProvider.getInstance(StatsActivity.this).getBatteryLevelFromTo(myReferenceFrom, myReferenceTo); } tvSince.setText(sinceText); Log.i(TAG, "Since " + sinceText); } else { tvSince.setText("n/a"); Log.i(TAG, "Since: n/a "); } StatsActivity.this.setListAdapter(o); } // @Override protected void onPreExecute() { // update hourglass // @todo this code is only there because onItemSelected is called twice if (m_progressDialog == null) { try { m_progressDialog = new ProgressDialog(StatsActivity.this); m_progressDialog.setMessage("Computing..."); m_progressDialog.setIndeterminate(true); m_progressDialog.setCancelable(false); m_progressDialog.show(); } catch (Exception e) { m_progressDialog = null; } } } } public Dialog getShareDialog() { final ArrayList<Integer> selectedSaveActions = new ArrayList<Integer>(); AlertDialog.Builder builder = new AlertDialog.Builder(this); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); boolean saveAsText = sharedPrefs.getBoolean("save_as_text", true); boolean saveAsJson = sharedPrefs.getBoolean("save_as_json", false); boolean saveLogcat = sharedPrefs.getBoolean("save_logcat", false); boolean saveDmesg = sharedPrefs.getBoolean("save_dmesg", false); if (saveAsText) { selectedSaveActions.add(0); } if (saveAsJson) { selectedSaveActions.add(1); } if (saveLogcat) { selectedSaveActions.add(2); } if (saveDmesg) { selectedSaveActions.add(3); } // Set the dialog title builder.setTitle(R.string.title_share_dialog) .setMultiChoiceItems(R.array.saveAsLabels, new boolean[]{saveAsText, saveAsJson, saveLogcat, saveDmesg}, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (isChecked) { // If the user checked the item, add it to the // selected items selectedSaveActions.add(which); } else if (selectedSaveActions.contains(which)) { // Else, if the item is already in the array, // remove it selectedSaveActions.remove(Integer.valueOf(which)); } } }) // Set the action buttons .setPositiveButton(R.string.label_button_share, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { GoogleAnalytics.getInstance(StatsActivity.this).trackPage(GoogleAnalytics.ACTION_DUMP); ArrayList<Uri> attachements = new ArrayList<Uri>(); Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, StatsActivity.this); Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, StatsActivity.this); Reading reading = new Reading(StatsActivity.this, myReferenceFrom, myReferenceTo); // save as text is selected if (selectedSaveActions.contains(0)) { attachements.add(reading.writeToFileText(StatsActivity.this)); } // save as JSON if selected if (selectedSaveActions.contains(1)) { attachements.add(reading.writeToFileJson(StatsActivity.this)); } // save logcat if selected if (selectedSaveActions.contains(2)) { attachements.add(StatsProvider.getInstance(StatsActivity.this).writeLogcatToFile()); } // save dmesg if selected if (selectedSaveActions.contains(3)) { attachements.add(StatsProvider.getInstance(StatsActivity.this).writeDmesgToFile()); } if (!attachements.isEmpty()) { Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE); shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachements); shareIntent.setType("text/*"); startActivity(Intent.createChooser(shareIntent, "Share info to..")); } } }) .setNeutralButton(R.string.label_button_save, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { GoogleAnalytics.getInstance(StatsActivity.this).trackPage(GoogleAnalytics.ACTION_DUMP); Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, StatsActivity.this); Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, StatsActivity.this); Reading reading = new Reading(StatsActivity.this, myReferenceFrom, myReferenceTo); // save as text is selected // save as text is selected if (selectedSaveActions.contains(0)) { reading.writeToFileText(StatsActivity.this); } // save as JSON if selected if (selectedSaveActions.contains(1)) { reading.writeToFileJson(StatsActivity.this); } // save logcat if selected if (selectedSaveActions.contains(2)) { StatsProvider.getInstance(StatsActivity.this).writeLogcatToFile(); } // save dmesg if selected if (selectedSaveActions.contains(3)) { StatsProvider.getInstance(StatsActivity.this).writeDmesgToFile(); } } }).setNegativeButton(R.string.label_button_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // do nothing } }); return builder.create(); } }
true
true
protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "OnCreated called"); super.onCreate(savedInstanceState); setContentView(R.layout.stats); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); // set debugging if (sharedPrefs.getBoolean("debug_logging", false)) { LogSettings.DEBUG=true; CommonLogSettings.DEBUG=true; } else { LogSettings.DEBUG=false; CommonLogSettings.DEBUG=false; } /////////////////////////////////////////////// // check if we have a new release /////////////////////////////////////////////// // if yes do some migration (if required) and show release notes String strLastRelease = sharedPrefs.getString("last_release", "0"); String strCurrentRelease = ""; try { PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0); strCurrentRelease = Integer.toString(pinfo.versionCode); } catch (Exception e) { // nop strCurrentRelease is set to "" } if (strLastRelease.equals("0")) { // show the initial run screen FirstLaunch.app_launched(this); SharedPreferences.Editor updater = sharedPrefs.edit(); updater.putString("last_release", strCurrentRelease); updater.commit(); } else if (!strLastRelease.equals(strCurrentRelease)) { // save the current release to properties so that the dialog won't be shown till next version SharedPreferences.Editor updater = sharedPrefs.edit(); updater.putString("last_release", strCurrentRelease); updater.commit(); Toast.makeText(this, "Deleting and re-creating references", Toast.LENGTH_SHORT).show(); ReferenceStore.deleteAllRefs(this); Intent i = new Intent(this, WriteBootReferenceService.class); this.startService(i); i = new Intent(this, WriteUnpluggedReferenceService.class); this.startService(i); // Show Kitkat info if ( (Build.VERSION.SDK_INT >= 19) && !SysUtils.hasBatteryStatsPermission(this) ) { // prepare the alert box AlertDialog.Builder alertbox = new AlertDialog.Builder(this); // set the message to display alertbox.setMessage("Since google has revoked rights for apps to access the battery stats without" + " root partial wakelocks will not be available anymore for non rooted users." + " See <a href=\"http://forum.xda-developers.com/showthread.php?t=2529455\">here</a> for more info."); // add a neutral button to the alert box and assign a click listener alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() { // click listener on the alert box public void onClick(DialogInterface arg0, int arg1) { } }); // show it alertbox.show(); } } else { // can't do this at the same time as the popup dialog would be masked by the readme /////////////////////////////////////////////// // check if we have shown the opt-out from analytics /////////////////////////////////////////////// boolean bWarningShown = sharedPrefs.getBoolean("analytics_opt_out", false); boolean bAnalyticsEnabled = sharedPrefs.getBoolean("use_analytics", true); if (bAnalyticsEnabled && !bWarningShown) { // prepare the alert box AlertDialog.Builder alertbox = new AlertDialog.Builder(this); // set the message to display alertbox.setMessage("BetterBatteryStats makes use of Google Analytics to collect usage statitics. If you disagree or do not want to participate you can opt-out by disabling \"Google Analytics\" in the \"Advanced Preferences\""); // add a neutral button to the alert box and assign a click listener alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() { // click listener on the alert box public void onClick(DialogInterface arg0, int arg1) { // opt out info was displayed SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(StatsActivity.this); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("analytics_opt_out", true); editor.commit(); } }); // show it alertbox.show(); } else { // show "rate" dialog // for testing: AppRater.showRateDialog(this, null); AppRater.app_launched(this); } } /////////////////////////////////////////////// // retrieve default selections for spinners // if none were passed /////////////////////////////////////////////// m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0")); m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME); if (!ReferenceStore.hasReferenceByName(m_refFromName, this)) { if (sharedPrefs.getBoolean("fallback_to_since_boot", false)) { m_refFromName = Reference.BOOT_REF_FILENAME; Toast.makeText(this, "Fallback to 'Since Boot'", Toast.LENGTH_SHORT).show(); } } try { // recover any saved state if ( (savedInstanceState != null) && (!savedInstanceState.isEmpty())) { m_iStat = (Integer) savedInstanceState.getSerializable("stat"); m_refFromName = (String) savedInstanceState.getSerializable("stattypeFrom"); m_refToName = (String) savedInstanceState.getSerializable("stattypeTo"); } } catch (Exception e) { m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0")); m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME); Log.e(TAG, "Exception: " + e.getMessage()); DataStorage.LogToFile(LOGFILE, "Exception in onCreate restoring Bundle"); DataStorage.LogToFile(LOGFILE, e.getMessage()); DataStorage.LogToFile(LOGFILE, e.getStackTrace()); Toast.makeText(this, "An error occured while recovering the previous state", Toast.LENGTH_SHORT).show(); } // Handle the case the Activity was called from an intent with paramaters Bundle extras = getIntent().getExtras(); if (extras != null) { // Override if some values were passed to the intent m_iStat = extras.getInt(StatsActivity.STAT); m_refFromName = extras.getString(StatsActivity.STAT_TYPE_FROM); m_refToName = extras.getString(StatsActivity.STAT_TYPE_TO); boolean bCalledFromNotification = extras.getBoolean(StatsActivity.FROM_NOTIFICATION, false); // Clear the notifications that was clicked to call the activity if (bCalledFromNotification) { NotificationManager nM = (NotificationManager)getSystemService(Service.NOTIFICATION_SERVICE); nM.cancel(EventWatcherService.NOTFICATION_ID); } } // Display the reference of the stat TextView tvSince = (TextView) findViewById(R.id.TextViewSince); if (tvSince != null) { Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, this); Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, this); long sinceMs = StatsProvider.getInstance(this).getSince(myReferenceFrom, myReferenceTo); if (sinceMs != -1) { String sinceText = DateUtils.formatDuration(sinceMs); boolean bShowBatteryLevels = sharedPrefs.getBoolean("show_batt", true); if (bShowBatteryLevels) { sinceText += " " + StatsProvider.getInstance(this).getBatteryLevelFromTo(myReferenceFrom, myReferenceTo); } tvSince.setText(sinceText); Log.i(TAG, "Since " + sinceText); } else { tvSince.setText("n/a"); Log.i(TAG, "Since: n/a "); } } // Spinner for selecting the stat Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat); ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource( this, R.array.stats, android.R.layout.simple_spinner_item); spinnerStatAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerStat.setAdapter(spinnerStatAdapter); // setSelection MUST be called after setAdapter spinnerStat.setSelection(m_iStat); spinnerStat.setOnItemSelectedListener(this); /////////////////////////////////////////////// // Spinner for Selecting the Stat type /////////////////////////////////////////////// Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType); m_spinnerFromAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item); m_spinnerFromAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerStatType.setAdapter(m_spinnerFromAdapter); try { this.setListViewAdapter(); } catch (BatteryInfoUnavailableException e) { // Log.e(TAG, e.getMessage(), e.fillInStackTrace()); Log.e(TAG, "Exception: "+Log.getStackTraceString(e)); Toast.makeText(this, "BatteryInfo Service could not be contacted.", Toast.LENGTH_LONG).show(); } catch (Exception e) { //Log.e(TAG, e.getMessage(), e.fillInStackTrace()); Log.e(TAG, "Exception: "+Log.getStackTraceString(e)); Toast.makeText(this, "An unhandled error occured. Please check your logcat", Toast.LENGTH_LONG).show(); } // setSelection MUST be called after setAdapter spinnerStatType.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName)); spinnerStatType.setOnItemSelectedListener(this); /////////////////////////////////////////////// // Spinner for Selecting the end sample /////////////////////////////////////////////// Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd); m_spinnerToAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item); m_spinnerToAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); boolean bShowSpinner = sharedPrefs.getBoolean("show_to_ref", true); if (bShowSpinner) { spinnerStatSampleEnd.setVisibility(View.VISIBLE); spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter); // setSelection must be called after setAdapter if ((m_refToName != null) && !m_refToName.equals("") ) { int pos = m_spinnerToAdapter.getPosition(m_refToName); spinnerStatSampleEnd.setSelection(pos); } else { spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME)); } } else { spinnerStatSampleEnd.setVisibility(View.GONE); spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter); // setSelection must be called after setAdapter spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME)); } spinnerStatSampleEnd.setOnItemSelectedListener(this); /////////////////////////////////////////////// // sorting /////////////////////////////////////////////// String strOrderBy = sharedPrefs.getString("default_orderby", "0"); try { m_iSorting = Integer.valueOf(strOrderBy); } catch(Exception e) { // handle error here m_iSorting = 0; } GoogleAnalytics.getInstance(this).trackStats(this, GoogleAnalytics.ACTIVITY_STATS, m_iStat, m_refFromName, m_refToName, m_iSorting); // Set up a listener whenever a key changes PreferenceManager.getDefaultSharedPreferences(this) .registerOnSharedPreferenceChangeListener(this); // log reference store ReferenceStore.logReferences(this); }
protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "OnCreated called"); super.onCreate(savedInstanceState); setContentView(R.layout.stats); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); // set debugging if (sharedPrefs.getBoolean("debug_logging", false)) { LogSettings.DEBUG=true; CommonLogSettings.DEBUG=true; } else { LogSettings.DEBUG=false; CommonLogSettings.DEBUG=false; } /////////////////////////////////////////////// // check if we have a new release /////////////////////////////////////////////// // if yes do some migration (if required) and show release notes String strLastRelease = sharedPrefs.getString("last_release", "0"); String strCurrentRelease = ""; try { PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0); strCurrentRelease = Integer.toString(pinfo.versionCode); } catch (Exception e) { // nop strCurrentRelease is set to "" } if (strLastRelease.equals("0")) { // show the initial run screen FirstLaunch.app_launched(this); SharedPreferences.Editor updater = sharedPrefs.edit(); updater.putString("last_release", strCurrentRelease); updater.commit(); } else if (!strLastRelease.equals(strCurrentRelease)) { // save the current release to properties so that the dialog won't be shown till next version SharedPreferences.Editor updater = sharedPrefs.edit(); updater.putString("last_release", strCurrentRelease); updater.commit(); Toast.makeText(this, "Deleting and re-creating references", Toast.LENGTH_SHORT).show(); ReferenceStore.deleteAllRefs(this); Intent i = new Intent(this, WriteBootReferenceService.class); this.startService(i); i = new Intent(this, WriteUnpluggedReferenceService.class); this.startService(i); // Show Kitkat info if ( (Build.VERSION.SDK_INT >= 19) && !SysUtils.hasBatteryStatsPermission(this) ) { // prepare the alert box AlertDialog.Builder alertbox = new AlertDialog.Builder(this); // set the message to display alertbox.setMessage("Google has revoked rights for apps to access the battery stats without" + " root. Partial wakelocks will not be available anymore for non rooted users. Please make sure to enable the root advanced options if you have root."); // add a neutral button to the alert box and assign a click listener alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() { // click listener on the alert box public void onClick(DialogInterface arg0, int arg1) { } }); // show it alertbox.show(); } } else { // can't do this at the same time as the popup dialog would be masked by the readme /////////////////////////////////////////////// // check if we have shown the opt-out from analytics /////////////////////////////////////////////// boolean bWarningShown = sharedPrefs.getBoolean("analytics_opt_out", false); boolean bAnalyticsEnabled = sharedPrefs.getBoolean("use_analytics", true); if (bAnalyticsEnabled && !bWarningShown) { // prepare the alert box AlertDialog.Builder alertbox = new AlertDialog.Builder(this); // set the message to display alertbox.setMessage("BetterBatteryStats makes use of Google Analytics to collect usage statitics. If you disagree or do not want to participate you can opt-out by disabling \"Google Analytics\" in the \"Advanced Preferences\""); // add a neutral button to the alert box and assign a click listener alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() { // click listener on the alert box public void onClick(DialogInterface arg0, int arg1) { // opt out info was displayed SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(StatsActivity.this); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("analytics_opt_out", true); editor.commit(); } }); // show it alertbox.show(); } else { // show "rate" dialog // for testing: AppRater.showRateDialog(this, null); AppRater.app_launched(this); } } /////////////////////////////////////////////// // retrieve default selections for spinners // if none were passed /////////////////////////////////////////////// m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0")); m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME); if (!ReferenceStore.hasReferenceByName(m_refFromName, this)) { if (sharedPrefs.getBoolean("fallback_to_since_boot", false)) { m_refFromName = Reference.BOOT_REF_FILENAME; Toast.makeText(this, "Fallback to 'Since Boot'", Toast.LENGTH_SHORT).show(); } } try { // recover any saved state if ( (savedInstanceState != null) && (!savedInstanceState.isEmpty())) { m_iStat = (Integer) savedInstanceState.getSerializable("stat"); m_refFromName = (String) savedInstanceState.getSerializable("stattypeFrom"); m_refToName = (String) savedInstanceState.getSerializable("stattypeTo"); } } catch (Exception e) { m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0")); m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME); Log.e(TAG, "Exception: " + e.getMessage()); DataStorage.LogToFile(LOGFILE, "Exception in onCreate restoring Bundle"); DataStorage.LogToFile(LOGFILE, e.getMessage()); DataStorage.LogToFile(LOGFILE, e.getStackTrace()); Toast.makeText(this, "An error occured while recovering the previous state", Toast.LENGTH_SHORT).show(); } // Handle the case the Activity was called from an intent with paramaters Bundle extras = getIntent().getExtras(); if (extras != null) { // Override if some values were passed to the intent m_iStat = extras.getInt(StatsActivity.STAT); m_refFromName = extras.getString(StatsActivity.STAT_TYPE_FROM); m_refToName = extras.getString(StatsActivity.STAT_TYPE_TO); boolean bCalledFromNotification = extras.getBoolean(StatsActivity.FROM_NOTIFICATION, false); // Clear the notifications that was clicked to call the activity if (bCalledFromNotification) { NotificationManager nM = (NotificationManager)getSystemService(Service.NOTIFICATION_SERVICE); nM.cancel(EventWatcherService.NOTFICATION_ID); } } // Display the reference of the stat TextView tvSince = (TextView) findViewById(R.id.TextViewSince); if (tvSince != null) { Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, this); Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, this); long sinceMs = StatsProvider.getInstance(this).getSince(myReferenceFrom, myReferenceTo); if (sinceMs != -1) { String sinceText = DateUtils.formatDuration(sinceMs); boolean bShowBatteryLevels = sharedPrefs.getBoolean("show_batt", true); if (bShowBatteryLevels) { sinceText += " " + StatsProvider.getInstance(this).getBatteryLevelFromTo(myReferenceFrom, myReferenceTo); } tvSince.setText(sinceText); Log.i(TAG, "Since " + sinceText); } else { tvSince.setText("n/a"); Log.i(TAG, "Since: n/a "); } } // Spinner for selecting the stat Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat); ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource( this, R.array.stats, android.R.layout.simple_spinner_item); spinnerStatAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerStat.setAdapter(spinnerStatAdapter); // setSelection MUST be called after setAdapter spinnerStat.setSelection(m_iStat); spinnerStat.setOnItemSelectedListener(this); /////////////////////////////////////////////// // Spinner for Selecting the Stat type /////////////////////////////////////////////// Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType); m_spinnerFromAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item); m_spinnerFromAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerStatType.setAdapter(m_spinnerFromAdapter); try { this.setListViewAdapter(); } catch (BatteryInfoUnavailableException e) { // Log.e(TAG, e.getMessage(), e.fillInStackTrace()); Log.e(TAG, "Exception: "+Log.getStackTraceString(e)); Toast.makeText(this, "BatteryInfo Service could not be contacted.", Toast.LENGTH_LONG).show(); } catch (Exception e) { //Log.e(TAG, e.getMessage(), e.fillInStackTrace()); Log.e(TAG, "Exception: "+Log.getStackTraceString(e)); Toast.makeText(this, "An unhandled error occured. Please check your logcat", Toast.LENGTH_LONG).show(); } // setSelection MUST be called after setAdapter spinnerStatType.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName)); spinnerStatType.setOnItemSelectedListener(this); /////////////////////////////////////////////// // Spinner for Selecting the end sample /////////////////////////////////////////////// Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd); m_spinnerToAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item); m_spinnerToAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); boolean bShowSpinner = sharedPrefs.getBoolean("show_to_ref", true); if (bShowSpinner) { spinnerStatSampleEnd.setVisibility(View.VISIBLE); spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter); // setSelection must be called after setAdapter if ((m_refToName != null) && !m_refToName.equals("") ) { int pos = m_spinnerToAdapter.getPosition(m_refToName); spinnerStatSampleEnd.setSelection(pos); } else { spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME)); } } else { spinnerStatSampleEnd.setVisibility(View.GONE); spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter); // setSelection must be called after setAdapter spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME)); } spinnerStatSampleEnd.setOnItemSelectedListener(this); /////////////////////////////////////////////// // sorting /////////////////////////////////////////////// String strOrderBy = sharedPrefs.getString("default_orderby", "0"); try { m_iSorting = Integer.valueOf(strOrderBy); } catch(Exception e) { // handle error here m_iSorting = 0; } GoogleAnalytics.getInstance(this).trackStats(this, GoogleAnalytics.ACTIVITY_STATS, m_iStat, m_refFromName, m_refToName, m_iSorting); // Set up a listener whenever a key changes PreferenceManager.getDefaultSharedPreferences(this) .registerOnSharedPreferenceChangeListener(this); // log reference store ReferenceStore.logReferences(this); }
diff --git a/src/main/java/org/apache/hadoop/hoya/exec/RunLongLivedApp.java b/src/main/java/org/apache/hadoop/hoya/exec/RunLongLivedApp.java index 9c067d3f..dae62d71 100644 --- a/src/main/java/org/apache/hadoop/hoya/exec/RunLongLivedApp.java +++ b/src/main/java/org/apache/hadoop/hoya/exec/RunLongLivedApp.java @@ -1,404 +1,404 @@ /* * 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.hoya.exec; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hoya.exceptions.HoyaException; import org.apache.hadoop.hoya.exceptions.HoyaInternalStateException; import org.apache.hadoop.io.IOUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * Execute an application. * * Hadoop's Shell class isn't used because it assumes it is executing * a short lived application: */ public class RunLongLivedApp implements Runnable { public static final int STREAM_READER_SLEEP_TIME = 200; public static final int RECENT_LINE_LOG_LIMIT = 64; Log LOG = LogFactory.getLog(RunLongLivedApp.class); private final ProcessBuilder builder; private Process process; private Exception exception; private Integer exitCode = null; volatile boolean done; private Thread execThread; private Thread logThread; private ProcessStreamReader processStreamReader; //list of recent lines, recorded for extraction into reports private final List<String> recentLines = new LinkedList<String>(); private final int recentLineLimit = RECENT_LINE_LOG_LIMIT; private ApplicationEventHandler applicationEventHandler; public RunLongLivedApp(String... commands) { builder = new ProcessBuilder(commands); initBuilder(); } public RunLongLivedApp(List<String> commands) { builder = new ProcessBuilder(commands); initBuilder(); } private void initBuilder() { builder.redirectErrorStream(false); } public ProcessBuilder getBuilder() { return builder; } /** * Set an optional application exit callback * @param applicationEventHandler callback to notify on application exit */ public void setApplicationEventHandler(ApplicationEventHandler applicationEventHandler) { this.applicationEventHandler = applicationEventHandler; } public void putEnv(String key, String val) { if (val == null) { throw new RuntimeException("Null value for key " + key); } builder.environment().put(key, val); } /** * Bulk set the environment from a map. This does * not replace the existing environment, just extend it/overwrite single * entries. * @param map map to add */ public void putEnvMap(Map<String, String> map) { for (Map.Entry<String, String> entry : map.entrySet()) { String val = entry.getValue(); String key = entry.getKey(); putEnv(key, val); } } public String getEnv(String key) { return builder.environment().get(key); } public Process getProcess() { return process; } public Exception getException() { return exception; } public List<String> getCommands() { return builder.command(); } public String getCommand() { return getCommands().get(0); } public boolean isRunning() { return process != null && !done; } /** * Get the exit code: null until the process has finished * @return the exit code or null */ public Integer getExitCode() { return exitCode; } public void stop() { if (!isRunning()) { return; } process.destroy(); } /** * Get a text description of the builder suitable for log output * @return a multiline string */ protected String describeBuilder() { StringBuilder buffer = new StringBuilder(); for (String arg : builder.command()) { buffer.append('"').append(arg).append("\" "); } // dumpEnv(buffer); return buffer.toString(); } private void dumpEnv(StringBuilder buffer) { buffer.append("\nEnvironment\n-----------"); Map<String, String> env = builder.environment(); Set<String> keys = env.keySet(); List<String> sortedKeys = new ArrayList<String>(keys); Collections.sort(sortedKeys); for (String key : sortedKeys) { buffer.append(key).append("=").append(env.get(key)).append('\n'); } } /** * Exec the process * @return the process * @throws IOException */ private Process spawnChildProcess() throws IOException, HoyaException { if (process != null) { throw new HoyaInternalStateException("Process already started"); } if (LOG.isDebugEnabled()) { LOG.debug("Spawning process:\n " + describeBuilder()); } process = builder.start(); return process; } /** * Entry point for waiting for the program to finish */ @Override // Runnable public void run() { //notify the callback that the process has started if (applicationEventHandler != null) { applicationEventHandler.onApplicationStarted(this); } try { exitCode = process.waitFor(); } catch (InterruptedException e) { LOG.debug("Process wait interrupted -exiting thread"); } finally { //here the process has finished LOG.info("process has finished"); //tell the logger it has to finish too done = true; //now call the callback if it is set if (applicationEventHandler != null) { applicationEventHandler.onApplicationExited(this, exitCode); } try { logThread.join(); } catch (InterruptedException ignored) { //ignored } } } /** * Create a thread to wait for this command to complete. * THE THREAD IS NOT STARTED. * @return the thread * @throws IOException Execution problems */ private Thread spawnIntoThread() throws IOException, HoyaException { spawnChildProcess(); return new Thread(this, getCommand()); } /** * Spawn the application * @throws IOException IO problems * @throws HoyaException internal state of this class is wrong */ public void spawnApplication() throws IOException, HoyaException { execThread = spawnIntoThread(); execThread.start(); processStreamReader = new ProcessStreamReader(LOG, STREAM_READER_SLEEP_TIME); logThread = new Thread(processStreamReader); logThread.start(); } /** * Get the lines of recent output * @return the last few lines of output; an empty list if there are none * or the process is not actually running */ public List<String> getRecentOutput() { return new ArrayList<String>(recentLines); } /** * add the recent line to the list of recent lines; deleting * an earlier on if the limit is reached. * * Implementation note: yes, a circular array would be more * efficient, especially with some power of two as the modulo, * but is it worth the complexity and risk of errors for * something that is only called once per line of IO? * @param line line to record * @param isErrorStream is the line from the error stream */ private synchronized void recordRecentLine(String line, boolean isErrorStream) { if (line == null) { return; } String entry = (isErrorStream ? "[ERR] " : "[OUT] ") + line; recentLines.add(entry); if (recentLines.size() > recentLineLimit) { recentLines.remove(0); } } /** * Class to read data from the two process streams, and, when run in a thread * to keep running until the <code>done</code> flag is set. * Lines are fetched from stdout and stderr and logged at info and error * respectively. */ private class ProcessStreamReader implements Runnable { private final Log streamLog; private final int sleepTime; private ProcessStreamReader(Log streamLog, int sleepTime) { this.streamLog = streamLog; this.sleepTime = sleepTime; } private int readCharNonBlocking(BufferedReader reader) throws IOException { if (reader.ready()) { return reader.read(); } else { return -1; } } /** * Read in a line, or, if the limit has been reached, the buffer * so far * @param reader source of data * @param line line to build * @param limit limit of line length * @return true if the line can be printed * @throws IOException IO trouble */ private boolean readAnyLine(BufferedReader reader, StringBuilder line, int limit) throws IOException { int next; while ((-1 != (next = readCharNonBlocking(reader)))) { if (next != '\n') { line.append((char) next); limit--; if (line.length() > limit) { //enough has been read in to print it any return true; } } else { //line end return flag to say so return true; } } //here the end of the stream is hit, or the limit return false; } @Override //Runnable @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") public void run() { BufferedReader errReader = null; BufferedReader outReader = null; StringBuilder outLine = new StringBuilder(256); StringBuilder errorLine = new StringBuilder(256); try { errReader = new BufferedReader(new InputStreamReader(process .getErrorStream())); outReader = new BufferedReader(new InputStreamReader(process .getInputStream())); while (!done) { boolean processed = false; if (readAnyLine(errReader, errorLine, 256)) { String line = errorLine.toString(); recordRecentLine(line, true); - streamLog.error(line); + streamLog.warn(line); errorLine.setLength(0); processed = true; } if (readAnyLine(outReader, outLine, 256)) { String line = outLine.toString(); recordRecentLine(line, false); streamLog.info(line); outLine.setLength(0); processed |= true; } if (!processed) { //nothing processed: wait a bit for data. try { Thread.sleep(sleepTime); } catch (InterruptedException e) { //ignore this, rely on the done flag LOG.debug("Ignoring ", e); } } } //get here, done time //print the current error line then stream through the rest streamLog.error(errorLine); String line = errReader.readLine(); while (line != null) { streamLog.error(line); if (Thread.interrupted()) { break; } line = errReader.readLine(); recordRecentLine(line, true); } //now do the info line streamLog.info(outLine); line = outReader.readLine(); while (line != null) { streamLog.info(line); if (Thread.interrupted()) { break; } line = outReader.readLine(); recordRecentLine(line, false); } } catch (Exception ignored) { //process connection has been torn down } finally { IOUtils.closeStream(errReader); IOUtils.closeStream(outReader); } } } }
true
true
public void run() { BufferedReader errReader = null; BufferedReader outReader = null; StringBuilder outLine = new StringBuilder(256); StringBuilder errorLine = new StringBuilder(256); try { errReader = new BufferedReader(new InputStreamReader(process .getErrorStream())); outReader = new BufferedReader(new InputStreamReader(process .getInputStream())); while (!done) { boolean processed = false; if (readAnyLine(errReader, errorLine, 256)) { String line = errorLine.toString(); recordRecentLine(line, true); streamLog.error(line); errorLine.setLength(0); processed = true; } if (readAnyLine(outReader, outLine, 256)) { String line = outLine.toString(); recordRecentLine(line, false); streamLog.info(line); outLine.setLength(0); processed |= true; } if (!processed) { //nothing processed: wait a bit for data. try { Thread.sleep(sleepTime); } catch (InterruptedException e) { //ignore this, rely on the done flag LOG.debug("Ignoring ", e); } } } //get here, done time //print the current error line then stream through the rest streamLog.error(errorLine); String line = errReader.readLine(); while (line != null) { streamLog.error(line); if (Thread.interrupted()) { break; } line = errReader.readLine(); recordRecentLine(line, true); } //now do the info line streamLog.info(outLine); line = outReader.readLine(); while (line != null) { streamLog.info(line); if (Thread.interrupted()) { break; } line = outReader.readLine(); recordRecentLine(line, false); } } catch (Exception ignored) { //process connection has been torn down } finally { IOUtils.closeStream(errReader); IOUtils.closeStream(outReader); } }
public void run() { BufferedReader errReader = null; BufferedReader outReader = null; StringBuilder outLine = new StringBuilder(256); StringBuilder errorLine = new StringBuilder(256); try { errReader = new BufferedReader(new InputStreamReader(process .getErrorStream())); outReader = new BufferedReader(new InputStreamReader(process .getInputStream())); while (!done) { boolean processed = false; if (readAnyLine(errReader, errorLine, 256)) { String line = errorLine.toString(); recordRecentLine(line, true); streamLog.warn(line); errorLine.setLength(0); processed = true; } if (readAnyLine(outReader, outLine, 256)) { String line = outLine.toString(); recordRecentLine(line, false); streamLog.info(line); outLine.setLength(0); processed |= true; } if (!processed) { //nothing processed: wait a bit for data. try { Thread.sleep(sleepTime); } catch (InterruptedException e) { //ignore this, rely on the done flag LOG.debug("Ignoring ", e); } } } //get here, done time //print the current error line then stream through the rest streamLog.error(errorLine); String line = errReader.readLine(); while (line != null) { streamLog.error(line); if (Thread.interrupted()) { break; } line = errReader.readLine(); recordRecentLine(line, true); } //now do the info line streamLog.info(outLine); line = outReader.readLine(); while (line != null) { streamLog.info(line); if (Thread.interrupted()) { break; } line = outReader.readLine(); recordRecentLine(line, false); } } catch (Exception ignored) { //process connection has been torn down } finally { IOUtils.closeStream(errReader); IOUtils.closeStream(outReader); } }
diff --git a/nuget-tests/src/jetbrains/buildServer/nuget/tests/server/settings/NuGetSettingsManagerPersitedTest.java b/nuget-tests/src/jetbrains/buildServer/nuget/tests/server/settings/NuGetSettingsManagerPersitedTest.java index 1893bff8..263023a0 100644 --- a/nuget-tests/src/jetbrains/buildServer/nuget/tests/server/settings/NuGetSettingsManagerPersitedTest.java +++ b/nuget-tests/src/jetbrains/buildServer/nuget/tests/server/settings/NuGetSettingsManagerPersitedTest.java @@ -1,238 +1,238 @@ /* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.buildServer.nuget.tests.server.settings; import jetbrains.buildServer.nuget.server.settings.NuGetSettingsComponent; import jetbrains.buildServer.nuget.server.settings.NuGetSettingsEventAdapter; import jetbrains.buildServer.nuget.server.settings.NuGetSettingsManager; import jetbrains.buildServer.nuget.server.settings.NuGetSettingsReader; import jetbrains.buildServer.nuget.server.settings.impl.NuGetSettingsManagerConfiguration; import jetbrains.buildServer.nuget.server.settings.impl.NuGetSettingsManagerImpl; import jetbrains.buildServer.nuget.server.settings.impl.NuGetSettingsPersistance; import jetbrains.buildServer.nuget.server.settings.impl.NuGetSettingsWatcher; import jetbrains.buildServer.serverSide.BuildServerListener; import jetbrains.buildServer.util.EventDispatcher; import jetbrains.buildServer.util.FileUtil; import jetbrains.buildServer.util.WaitForAssert; import org.jetbrains.annotations.NotNull; import org.jmock.Expectations; import org.jmock.Mockery; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import static jetbrains.buildServer.nuget.server.settings.NuGetSettingsComponent.SERVER; /** * @author Eugene Petrenko ([email protected]) * Date: 30.10.11 15:56 */ public class NuGetSettingsManagerPersitedTest extends NuGetSettingsManagerTest { private Mockery m; private NuGetSettingsManagerConfiguration myConfig; private File myFile; private NuGetSettingsPersistance myPersistance; private NuGetSettingsWatcher myWatcher; private EventDispatcher<BuildServerListener> myListener; @BeforeMethod @Override protected void setUp() throws Exception { super.setUp(); m = new Mockery(); myConfig = m.mock(NuGetSettingsManagerConfiguration.class); myFile = createTempFile(); m.checking(new Expectations(){{ allowing(myConfig).getNuGetConfigXml(); will(returnValue(myFile)); }}); recreateSettings(); } @Override protected void recreateSettings() { super.recreateSettings(); if (myConfig == null) return; if (myListener != null) { myListener.getMulticaster().serverShutdown(); } myPersistance = new NuGetSettingsPersistance(myConfig); myListener = EventDispatcher.create(BuildServerListener.class); myWatcher = new NuGetSettingsWatcher(myConfig, myListener, myPersistance, (NuGetSettingsManagerImpl) mySettings); myWatcher.setWatchInterval(10); myListener.getMulticaster().serverStartup(); } @Test public void testReadWriteRecreate() { testReadWrite(); recreateSettings(); mySettings.readSettings(SERVER, new NuGetSettingsManager.Func<NuGetSettingsReader, Object>() { public Object executeAction(@NotNull NuGetSettingsReader action) { Assert.assertEquals(true, action.getBooleanParameter("bool1", false)); Assert.assertEquals(44, action.getIntParameter("int1", 42)); Assert.assertEquals("zzz", action.getStringParameter("string1")); return null; } }); } @Test public void testRemoveKeyRecreate() { testRemoveKey(); recreateSettings(); mySettings.readSettings(SERVER, new NuGetSettingsManager.Func<NuGetSettingsReader, Object>() { public Object executeAction(@NotNull NuGetSettingsReader action) { Assert.assertEquals(false, action.getBooleanParameter("bool1", false)); Assert.assertEquals(42, action.getIntParameter("int1", 42)); Assert.assertEquals(null, action.getStringParameter("string1")); return null; } }); } @Test public void testUpdateKeyRecreate() { testUpdateKey(); recreateSettings(); mySettings.readSettings(SERVER, new NuGetSettingsManager.Func<NuGetSettingsReader, Object>() { public Object executeAction(@NotNull NuGetSettingsReader action) { Assert.assertEquals(false, action.getBooleanParameter("bool1", true)); Assert.assertEquals(445, action.getIntParameter("int1", 42)); Assert.assertEquals("uuu", action.getStringParameter("string1")); return null; } }); } @Test public void testReadWrongTypeRecreate() { testReadWrongType(); recreateSettings(); mySettings.readSettings(SERVER, new NuGetSettingsManager.Func<NuGetSettingsReader, Object>() { public Object executeAction(@NotNull NuGetSettingsReader action) { Assert.assertEquals(true, action.getBooleanParameter("bool1", false)); Assert.assertEquals(44, action.getIntParameter("bool1", 44)); Assert.assertEquals("true", action.getStringParameter("bool1")); Assert.assertEquals(false, action.getBooleanParameter("int1", false)); Assert.assertEquals(44, action.getIntParameter("int1", 42)); Assert.assertEquals("44", action.getStringParameter("int1")); Assert.assertEquals("zzz", action.getStringParameter("string1")); Assert.assertEquals(444, action.getIntParameter("string1", 444)); Assert.assertEquals(false, action.getBooleanParameter("string1", false)); return null; } }); } @Test public void testFileWatcherReload() throws IOException { testReadWrite(); File tmp = createTempFile(); FileUtil.copy(myFile, tmp); FileUtil.delete(myFile); recreateSettings(); myWatcher.setWatchInterval(10); mySettings.readSettings(NuGetSettingsComponent.SERVER, new NuGetSettingsManager.Func<NuGetSettingsReader, Object>() { public Object executeAction(@NotNull NuGetSettingsReader action) { Assert.assertNull(action.getStringParameter("string1")); return null; } }); FileUtil.copy(tmp, myFile); new WaitForAssert(){ @Override protected boolean condition() { return mySettings.readSettings(NuGetSettingsComponent.SERVER, new NuGetSettingsManager.Func<NuGetSettingsReader, Boolean>() { public Boolean executeAction(@NotNull NuGetSettingsReader action) { return "zzz".equals(action.getStringParameter("string1")); } }); } }; } @Test - public void testFileWatcherReload_event() throws IOException { + public void testFileWatcherReload_event() throws IOException, InterruptedException { testReadWrite(); File tmp = createTempFile(); FileUtil.copy(myFile, tmp); FileUtil.delete(myFile); recreateSettings(); final AtomicBoolean componentReloadCalled = new AtomicBoolean(); final AtomicBoolean reloadCalled = new AtomicBoolean(); - mySettings.addListener(new NuGetSettingsEventAdapter(){ + mySettings.addListener(new NuGetSettingsEventAdapter() { @Override public void settingsChanged(@NotNull NuGetSettingsComponent component) { componentReloadCalled.set(true); } @Override public void settingsReloaded() { reloadCalled.set(true); } }); - myWatcher.setWatchInterval(10); mySettings.readSettings(NuGetSettingsComponent.SERVER, new NuGetSettingsManager.Func<NuGetSettingsReader, Object>() { public Object executeAction(@NotNull NuGetSettingsReader action) { Assert.assertNull(action.getStringParameter("string1")); return null; } }); + Thread.sleep(300); FileUtil.copy(tmp, myFile); new WaitForAssert(){ @Override protected boolean condition() { return mySettings.readSettings(NuGetSettingsComponent.SERVER, new NuGetSettingsManager.Func<NuGetSettingsReader, Boolean>() { public Boolean executeAction(@NotNull NuGetSettingsReader action) { return "zzz".equals(action.getStringParameter("string1")); } }); } }; Assert.assertFalse(componentReloadCalled.get()); Assert.assertTrue(reloadCalled.get()); } }
false
true
public void testFileWatcherReload_event() throws IOException { testReadWrite(); File tmp = createTempFile(); FileUtil.copy(myFile, tmp); FileUtil.delete(myFile); recreateSettings(); final AtomicBoolean componentReloadCalled = new AtomicBoolean(); final AtomicBoolean reloadCalled = new AtomicBoolean(); mySettings.addListener(new NuGetSettingsEventAdapter(){ @Override public void settingsChanged(@NotNull NuGetSettingsComponent component) { componentReloadCalled.set(true); } @Override public void settingsReloaded() { reloadCalled.set(true); } }); myWatcher.setWatchInterval(10); mySettings.readSettings(NuGetSettingsComponent.SERVER, new NuGetSettingsManager.Func<NuGetSettingsReader, Object>() { public Object executeAction(@NotNull NuGetSettingsReader action) { Assert.assertNull(action.getStringParameter("string1")); return null; } }); FileUtil.copy(tmp, myFile); new WaitForAssert(){ @Override protected boolean condition() { return mySettings.readSettings(NuGetSettingsComponent.SERVER, new NuGetSettingsManager.Func<NuGetSettingsReader, Boolean>() { public Boolean executeAction(@NotNull NuGetSettingsReader action) { return "zzz".equals(action.getStringParameter("string1")); } }); } }; Assert.assertFalse(componentReloadCalled.get()); Assert.assertTrue(reloadCalled.get()); }
public void testFileWatcherReload_event() throws IOException, InterruptedException { testReadWrite(); File tmp = createTempFile(); FileUtil.copy(myFile, tmp); FileUtil.delete(myFile); recreateSettings(); final AtomicBoolean componentReloadCalled = new AtomicBoolean(); final AtomicBoolean reloadCalled = new AtomicBoolean(); mySettings.addListener(new NuGetSettingsEventAdapter() { @Override public void settingsChanged(@NotNull NuGetSettingsComponent component) { componentReloadCalled.set(true); } @Override public void settingsReloaded() { reloadCalled.set(true); } }); mySettings.readSettings(NuGetSettingsComponent.SERVER, new NuGetSettingsManager.Func<NuGetSettingsReader, Object>() { public Object executeAction(@NotNull NuGetSettingsReader action) { Assert.assertNull(action.getStringParameter("string1")); return null; } }); Thread.sleep(300); FileUtil.copy(tmp, myFile); new WaitForAssert(){ @Override protected boolean condition() { return mySettings.readSettings(NuGetSettingsComponent.SERVER, new NuGetSettingsManager.Func<NuGetSettingsReader, Boolean>() { public Boolean executeAction(@NotNull NuGetSettingsReader action) { return "zzz".equals(action.getStringParameter("string1")); } }); } }; Assert.assertFalse(componentReloadCalled.get()); Assert.assertTrue(reloadCalled.get()); }
diff --git a/test/functional/test/java/lang/ClassTest.java b/test/functional/test/java/lang/ClassTest.java index 51676073..d2e4ba54 100644 --- a/test/functional/test/java/lang/ClassTest.java +++ b/test/functional/test/java/lang/ClassTest.java @@ -1,91 +1,91 @@ package test.java.lang; import jvm.TestCase; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; public class ClassTest extends TestCase { public static void testGetAnnotation() { Tag tag = TaggedClass.class.getAnnotation(Tag.class); assertEquals(Byte.MAX_VALUE, tag.byteValue()); assertEquals(Character.MAX_VALUE, tag.charValue()); assertEquals(Short.MAX_VALUE, tag.shortValue()); assertEquals(Integer.MAX_VALUE, tag.intValue()); assertEquals(Long.MAX_VALUE, tag.longValue()); assertEquals(Float.MAX_VALUE, tag.floatValue()); assertEquals(Double.MAX_VALUE, tag.doubleValue()); assertEquals("hello, world", tag.stringValue()); // assertEquals(Required.YES, tag.enumValue()); // assertEquals(Object.class, tag.classValue()); assertArrayEquals(new byte[] { Byte.MIN_VALUE, Byte.MAX_VALUE }, tag.byteArrayValue()); assertArrayEquals(new char[] { Character.MIN_VALUE, Character.MAX_VALUE }, tag.charArrayValue()); assertArrayEquals(new short[] { Short.MIN_VALUE, Short.MAX_VALUE }, tag.shortArrayValue()); assertArrayEquals(new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE }, tag.intArrayValue()); // assertArrayEquals(new long[] { Long.MIN_VALUE, Long.MAX_VALUE }, tag.longArrayValue()); assertArrayEquals(new float[] { Float.MIN_VALUE, Float.MAX_VALUE }, tag.floatArrayValue()); // assertArrayEquals(new double[] { Double.MIN_VALUE, Double.MAX_VALUE }, tag.doubleArrayValue()); -// assertArrayEquals(new String[] { "hello, world", "Hello, World!" }, tag.stringArrayValue()); + assertArrayEquals(new String[] { "hello, world", "Hello, World!" }, tag.stringArrayValue()); // assertArrayEquals(new Required[] { Required.YES, Required.NO }, tag.enumArrayValue()); // assertArrayEquals(new Class<?>[] { Integer.class, Long.class }, tag.classArrayValue()); } @Tag( byteValue = Byte.MAX_VALUE, charValue = Character.MAX_VALUE, shortValue = Short.MAX_VALUE, intValue = Integer.MAX_VALUE, longValue = Long.MAX_VALUE, floatValue = Float.MAX_VALUE, doubleValue = Double.MAX_VALUE, stringValue = "hello, world", enumValue = Required.YES, classValue = Object.class, byteArrayValue = { Byte.MIN_VALUE, Byte.MAX_VALUE }, charArrayValue = { Character.MIN_VALUE, Character.MAX_VALUE }, shortArrayValue = { Short.MIN_VALUE, Short.MAX_VALUE }, intArrayValue = { Integer.MIN_VALUE, Integer.MAX_VALUE }, longArrayValue = { Long.MIN_VALUE, Long.MAX_VALUE }, floatArrayValue = { Float.MIN_VALUE, Float.MAX_VALUE }, doubleArrayValue = { Double.MIN_VALUE, Double.MAX_VALUE }, stringArrayValue = { "hello, world", "Hello, World!" }, enumArrayValue = { Required.YES, Required.NO }, classArrayValue = { Integer.class, Long.class } ) public static class TaggedClass { } @Retention(RetentionPolicy.RUNTIME) public @interface Tag { byte byteValue(); char charValue(); short shortValue(); int intValue(); long longValue(); float floatValue(); double doubleValue(); String stringValue(); Required enumValue(); Class<?> classValue(); byte[] byteArrayValue(); char[] charArrayValue(); short[] shortArrayValue(); int[] intArrayValue(); long[] longArrayValue(); float[] floatArrayValue(); double[] doubleArrayValue(); String[] stringArrayValue(); Required[] enumArrayValue(); Class<?>[] classArrayValue(); } public static enum Required { YES, NO } public static void main(String[] args) { testGetAnnotation(); } }
true
true
public static void testGetAnnotation() { Tag tag = TaggedClass.class.getAnnotation(Tag.class); assertEquals(Byte.MAX_VALUE, tag.byteValue()); assertEquals(Character.MAX_VALUE, tag.charValue()); assertEquals(Short.MAX_VALUE, tag.shortValue()); assertEquals(Integer.MAX_VALUE, tag.intValue()); assertEquals(Long.MAX_VALUE, tag.longValue()); assertEquals(Float.MAX_VALUE, tag.floatValue()); assertEquals(Double.MAX_VALUE, tag.doubleValue()); assertEquals("hello, world", tag.stringValue()); // assertEquals(Required.YES, tag.enumValue()); // assertEquals(Object.class, tag.classValue()); assertArrayEquals(new byte[] { Byte.MIN_VALUE, Byte.MAX_VALUE }, tag.byteArrayValue()); assertArrayEquals(new char[] { Character.MIN_VALUE, Character.MAX_VALUE }, tag.charArrayValue()); assertArrayEquals(new short[] { Short.MIN_VALUE, Short.MAX_VALUE }, tag.shortArrayValue()); assertArrayEquals(new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE }, tag.intArrayValue()); // assertArrayEquals(new long[] { Long.MIN_VALUE, Long.MAX_VALUE }, tag.longArrayValue()); assertArrayEquals(new float[] { Float.MIN_VALUE, Float.MAX_VALUE }, tag.floatArrayValue()); // assertArrayEquals(new double[] { Double.MIN_VALUE, Double.MAX_VALUE }, tag.doubleArrayValue()); // assertArrayEquals(new String[] { "hello, world", "Hello, World!" }, tag.stringArrayValue()); // assertArrayEquals(new Required[] { Required.YES, Required.NO }, tag.enumArrayValue()); // assertArrayEquals(new Class<?>[] { Integer.class, Long.class }, tag.classArrayValue()); }
public static void testGetAnnotation() { Tag tag = TaggedClass.class.getAnnotation(Tag.class); assertEquals(Byte.MAX_VALUE, tag.byteValue()); assertEquals(Character.MAX_VALUE, tag.charValue()); assertEquals(Short.MAX_VALUE, tag.shortValue()); assertEquals(Integer.MAX_VALUE, tag.intValue()); assertEquals(Long.MAX_VALUE, tag.longValue()); assertEquals(Float.MAX_VALUE, tag.floatValue()); assertEquals(Double.MAX_VALUE, tag.doubleValue()); assertEquals("hello, world", tag.stringValue()); // assertEquals(Required.YES, tag.enumValue()); // assertEquals(Object.class, tag.classValue()); assertArrayEquals(new byte[] { Byte.MIN_VALUE, Byte.MAX_VALUE }, tag.byteArrayValue()); assertArrayEquals(new char[] { Character.MIN_VALUE, Character.MAX_VALUE }, tag.charArrayValue()); assertArrayEquals(new short[] { Short.MIN_VALUE, Short.MAX_VALUE }, tag.shortArrayValue()); assertArrayEquals(new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE }, tag.intArrayValue()); // assertArrayEquals(new long[] { Long.MIN_VALUE, Long.MAX_VALUE }, tag.longArrayValue()); assertArrayEquals(new float[] { Float.MIN_VALUE, Float.MAX_VALUE }, tag.floatArrayValue()); // assertArrayEquals(new double[] { Double.MIN_VALUE, Double.MAX_VALUE }, tag.doubleArrayValue()); assertArrayEquals(new String[] { "hello, world", "Hello, World!" }, tag.stringArrayValue()); // assertArrayEquals(new Required[] { Required.YES, Required.NO }, tag.enumArrayValue()); // assertArrayEquals(new Class<?>[] { Integer.class, Long.class }, tag.classArrayValue()); }
diff --git a/svnkit/src/org/tmatesoft/svn/core/internal/wc/SVNCommitUtil.java b/svnkit/src/org/tmatesoft/svn/core/internal/wc/SVNCommitUtil.java index 9d4a2b483..557cd1053 100644 --- a/svnkit/src/org/tmatesoft/svn/core/internal/wc/SVNCommitUtil.java +++ b/svnkit/src/org/tmatesoft/svn/core/internal/wc/SVNCommitUtil.java @@ -1,869 +1,869 @@ /* * ==================================================================== * Copyright (c) 2004-2007 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.wc; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.admin.SVNAdminArea; import org.tmatesoft.svn.core.internal.wc.admin.SVNEntry; import org.tmatesoft.svn.core.internal.wc.admin.SVNVersionedProperties; import org.tmatesoft.svn.core.internal.wc.admin.SVNWCAccess; import org.tmatesoft.svn.core.io.ISVNEditor; import org.tmatesoft.svn.core.wc.ISVNCommitParameters; import org.tmatesoft.svn.core.wc.ISVNEventHandler; import org.tmatesoft.svn.core.wc.SVNCommitItem; import org.tmatesoft.svn.core.wc.SVNEvent; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNStatus; import org.tmatesoft.svn.core.wc.SVNStatusClient; import org.tmatesoft.svn.core.wc.SVNStatusType; import org.tmatesoft.svn.core.wc.SVNWCUtil; /** * @version 1.1.1 * @author TMate Software Ltd. */ public class SVNCommitUtil { public static void driveCommitEditor(ISVNCommitPathHandler handler, Collection paths, ISVNEditor editor, long revision) throws SVNException { if (paths == null || paths.isEmpty() || handler == null || editor == null) { return; } String[] pathsArray = (String[]) paths.toArray(new String[paths.size()]); Arrays.sort(pathsArray, SVNPathUtil.PATH_COMPARATOR); int index = 0; String lastPath = null; if ("".equals(pathsArray[index])) { handler.handleCommitPath("", editor); lastPath = pathsArray[index]; index++; } else { editor.openRoot(revision); } for (; index < pathsArray.length; index++) { String commitPath = pathsArray[index]; String commonAncestor = lastPath == null || "".equals(lastPath) ? "" : SVNPathUtil.getCommonPathAncestor(commitPath, lastPath); if (lastPath != null) { while (!lastPath.equals(commonAncestor)) { editor.closeDir(); if (lastPath.lastIndexOf('/') >= 0) { lastPath = lastPath.substring(0, lastPath.lastIndexOf('/')); } else { lastPath = ""; } } } String relativeCommitPath = commitPath.substring(commonAncestor.length()); if (relativeCommitPath.startsWith("/")) { relativeCommitPath = relativeCommitPath.substring(1); } for (StringTokenizer tokens = new StringTokenizer( relativeCommitPath, "/"); tokens.hasMoreTokens();) { String token = tokens.nextToken(); commonAncestor = "".equals(commonAncestor) ? token : commonAncestor + "/" + token; if (!commonAncestor.equals(commitPath)) { editor.openDir(commonAncestor, revision); } else { break; } } boolean closeDir = handler.handleCommitPath(commitPath, editor); if (closeDir) { lastPath = commitPath; } else { if (index + 1 < pathsArray.length) { lastPath = SVNPathUtil.removeTail(commitPath); } else { lastPath = commitPath; } } } while (lastPath != null && !"".equals(lastPath)) { editor.closeDir(); lastPath = lastPath.lastIndexOf('/') >= 0 ? lastPath.substring(0, lastPath.lastIndexOf('/')) : ""; } } public static SVNWCAccess createCommitWCAccess(File[] paths, boolean recursive, boolean force, Collection relativePaths, final SVNStatusClient statusClient) throws SVNException { String[] validatedPaths = new String[paths.length]; for (int i = 0; i < paths.length; i++) { statusClient.checkCancelled(); File file = paths[i]; validatedPaths[i] = SVNPathUtil.validateFilePath(file.getAbsolutePath()); } String rootPath = SVNPathUtil.condencePaths(validatedPaths, relativePaths, recursive); if (rootPath == null) { return null; } File baseDir = new File(rootPath).getAbsoluteFile(); rootPath = baseDir.getAbsolutePath().replace(File.separatorChar, '/'); Collection dirsToLock = new HashSet(); // relative paths to lock. Collection dirsToLockRecursively = new HashSet(); boolean lockAll = false; if (relativePaths.isEmpty()) { statusClient.checkCancelled(); String target = getTargetName(baseDir); if (!"".equals(target)) { // we will have to lock target as well, not only base dir. SVNFileType targetType = SVNFileType.getType(new File(rootPath)); relativePaths.add(target); if (targetType == SVNFileType.DIRECTORY) { // lock recursively if forced and copied... if (recursive || (force && isRecursiveCommitForced(baseDir))) { // dir is copied, include children dirsToLockRecursively.add(target); } else { dirsToLock.add(target); } } baseDir = baseDir.getParentFile(); } else { lockAll = true; } } else { baseDir = adjustRelativePaths(baseDir, relativePaths); // there are multiple paths. for (Iterator targets = relativePaths.iterator(); targets.hasNext();) { statusClient.checkCancelled(); String targetPath = (String) targets.next(); File targetFile = new File(baseDir, targetPath); SVNFileType targetKind = SVNFileType.getType(targetFile); if (targetKind == SVNFileType.DIRECTORY) { if (recursive || (force && isRecursiveCommitForced(targetFile))) { dirsToLockRecursively.add(targetPath); } else if (!targetFile.equals(baseDir)){ dirsToLock.add(targetPath); } } if (!targetFile.equals(baseDir)) { targetFile = targetFile.getParentFile(); targetPath = SVNPathUtil.removeTail(targetPath); while (targetFile != null && !targetFile.equals(baseDir) && !dirsToLock.contains(targetPath)) { dirsToLock.add(targetPath); targetPath = SVNPathUtil.removeTail(targetPath); targetFile = targetFile.getParentFile(); } } } } SVNWCAccess baseAccess = SVNWCAccess.newInstance(new ISVNEventHandler() { public void handleEvent(SVNEvent event, double progress) throws SVNException { } public void checkCancelled() throws SVNCancelException { statusClient.checkCancelled(); } }); baseAccess.setOptions(statusClient.getOptions()); try { baseAccess.open(baseDir, true, lockAll ? SVNWCAccess.INFINITE_DEPTH : 0); statusClient.checkCancelled(); dirsToLock = new ArrayList(dirsToLock); dirsToLockRecursively = new ArrayList(dirsToLockRecursively); Collections.sort((List) dirsToLock, SVNPathUtil.PATH_COMPARATOR); Collections.sort((List) dirsToLockRecursively, SVNPathUtil.PATH_COMPARATOR); if (!lockAll) { List uniqueDirsToLockRecursively = new ArrayList(); uniqueDirsToLockRecursively.addAll(dirsToLockRecursively); for(Iterator ps = uniqueDirsToLockRecursively.iterator(); ps.hasNext();) { String pathToLock = (String) ps.next(); for(Iterator existing = dirsToLockRecursively.iterator(); existing.hasNext();) { String existingPath = (String) existing.next(); if (pathToLock.startsWith(existingPath + "/")) { // child of other path ps.remove(); break; } } } Collections.sort(uniqueDirsToLockRecursively, SVNPathUtil.PATH_COMPARATOR); dirsToLockRecursively = uniqueDirsToLockRecursively; removeRedundantPaths(dirsToLockRecursively, dirsToLock); for (Iterator nonRecusivePaths = dirsToLock.iterator(); nonRecusivePaths.hasNext();) { statusClient.checkCancelled(); String path = (String) nonRecusivePaths.next(); File pathFile = new File(baseDir, path); baseAccess.open(pathFile, true, 0); } for (Iterator recusivePaths = dirsToLockRecursively.iterator(); recusivePaths.hasNext();) { statusClient.checkCancelled(); String path = (String) recusivePaths.next(); File pathFile = new File(baseDir, path); baseAccess.open(pathFile, true, SVNWCAccess.INFINITE_DEPTH); } } for(int i = 0; i < paths.length; i++) { statusClient.checkCancelled(); File path = new File(SVNPathUtil.validateFilePath(paths[i].getAbsolutePath())); path = path.getAbsoluteFile(); try { baseAccess.probeRetrieve(path); } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage().wrap("Are all the targets part of the same working copy?"); SVNErrorManager.error(err); } if (!recursive && !force) { if (SVNFileType.getType(path) == SVNFileType.DIRECTORY) { // TODO replace with direct SVNStatusEditor call. SVNStatus status = statusClient.doStatus(path, false); if (status != null && (status.getContentsStatus() == SVNStatusType.STATUS_DELETED || status.getContentsStatus() == SVNStatusType.STATUS_REPLACED)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot non-recursively commit a directory deletion"); SVNErrorManager.error(err); } } } } // if commit is non-recursive and forced, remove those child dirs // that were not explicitly added but are explicitly copied. ufff. if (!recursive && force) { SVNAdminArea[] lockedDirs = baseAccess.getAdminAreas(); for (int i = 0; i < lockedDirs.length; i++) { statusClient.checkCancelled(); SVNAdminArea dir = lockedDirs[i]; SVNEntry rootEntry = baseAccess.getEntry(dir.getRoot(), true); if (rootEntry.getCopyFromURL() != null) { File dirRoot = dir.getRoot(); boolean keep = false; for (int j = 0; j < paths.length; j++) { if (dirRoot.equals(paths[j])) { keep = true; break; } } if (!keep) { baseAccess.closeAdminArea(dir.getRoot()); } } } } } catch (SVNException e) { baseAccess.close(); throw e; } baseAccess.setAnchor(baseDir); return baseAccess; } public static SVNWCAccess[] createCommitWCAccess2(File[] paths, boolean recursive, boolean force, Map relativePathsMap, SVNStatusClient statusClient) throws SVNException { Map rootsMap = new HashMap(); // wc root file -> paths to be committed (paths). Map localRootsCache = new HashMap(); for (int i = 0; i < paths.length; i++) { statusClient.checkCancelled(); File path = paths[i]; File rootPath = path; if (rootPath.isFile()) { rootPath = rootPath.getParentFile(); } File wcRoot = localRootsCache.containsKey(rootPath) ? (File) localRootsCache.get(rootPath) : SVNWCUtil.getWorkingCopyRoot(rootPath, true); localRootsCache.put(path, wcRoot); if (!rootsMap.containsKey(wcRoot)) { rootsMap.put(wcRoot, new ArrayList()); } Collection wcPaths = (Collection) rootsMap.get(wcRoot); wcPaths.add(path); } Collection result = new ArrayList(); try { for (Iterator roots = rootsMap.keySet().iterator(); roots.hasNext();) { statusClient.checkCancelled(); File root = (File) roots.next(); Collection filesList = (Collection) rootsMap.get(root); File[] filesArray = (File[]) filesList.toArray(new File[filesList.size()]); Collection relativePaths = new ArrayList(); SVNWCAccess wcAccess = createCommitWCAccess(filesArray, recursive, force, relativePaths, statusClient); relativePathsMap.put(wcAccess, relativePaths); result.add(wcAccess); } } catch (SVNException e) { for (Iterator wcAccesses = result.iterator(); wcAccesses.hasNext();) { SVNWCAccess wcAccess = (SVNWCAccess) wcAccesses.next(); wcAccess.close(); } throw e; } return (SVNWCAccess[]) result.toArray(new SVNWCAccess[result.size()]); } public static SVNCommitItem[] harvestCommitables(SVNWCAccess baseAccess, Collection paths, Map lockTokens, boolean justLocked, boolean recursive, boolean force, ISVNCommitParameters params) throws SVNException { Map commitables = new TreeMap(); Collection danglers = new HashSet(); Iterator targets = paths.iterator(); boolean isRecursionForced = false; do { baseAccess.checkCancelled(); String target = targets.hasNext() ? (String) targets.next() : ""; // get entry for target File targetFile = new File(baseAccess.getAnchor(), target); String targetName = "".equals(target) ? "" : SVNPathUtil.tail(target); String parentPath = SVNPathUtil.removeTail(target); SVNAdminArea dir = baseAccess.probeRetrieve(targetFile); SVNEntry entry = baseAccess.getEntry(targetFile, false); String url = null; if (entry == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_NOT_FOUND, "''{0}'' is not under version control", targetFile); SVNErrorManager.error(err); } else if (entry.getURL() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_MISSING_URL, "''{0}'' has no URL", targetFile); SVNErrorManager.error(err); } else { url = entry.getURL(); } SVNEntry parentEntry = null; if (entry != null && (entry.isScheduledForAddition() || entry.isScheduledForReplacement())) { // get parent (for file or dir-> get ""), otherwise open parent // dir and get "". try { baseAccess.retrieve(targetFile.getParentFile()); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) { baseAccess.open(targetFile.getParentFile(), true, 0); } else { throw e; } } parentEntry = baseAccess.getEntry(targetFile.getParentFile(), false); if (parentEntry == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "''{0}'' is scheduled for addition within unversioned parent", targetFile); SVNErrorManager.error(err); } else if (parentEntry.isScheduledForAddition() || parentEntry.isScheduledForReplacement()) { danglers.add(targetFile.getParentFile()); } } boolean recurse = recursive; if (entry != null && entry.isCopied() && entry.getSchedule() == null) { // if commit is forced => we could collect this entry, assuming // that its parent is already included into commit // it will be later removed from commit anyway. if (!force) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "Entry for ''{0}''" + " is marked as 'copied' but is not itself scheduled\n" + "for addition. Perhaps you're committing a target that is\n" + "inside an unversioned (or not-yet-versioned) directory?", targetFile); SVNErrorManager.error(err); } else { // just do not process this item as in case of recursive // commit. continue; } } else if (entry != null && entry.isCopied() && entry.isScheduledForAddition()) { if (force) { isRecursionForced = !recursive; recurse = true; } } else if (entry != null && entry.isScheduledForDeletion() && force && !recursive) { // if parent is also deleted -> skip this entry if (!"".equals(targetName)) { parentEntry = dir.getEntry("", false); } else { File parentFile = targetFile.getParentFile(); try { baseAccess.retrieve(parentFile); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) { baseAccess.open(targetFile.getParentFile(), true, 0); } else { throw e; } } parentEntry = baseAccess.getEntry(parentFile, false); } if (parentEntry != null && parentEntry.isScheduledForDeletion() && paths.contains(parentPath)) { continue; } // this recursion is not considered as "forced", all children should be // deleted anyway. recurse = true; } // String relativePath = entry.getKind() == SVNNodeKind.DIR ? target : SVNPathUtil.removeTail(target); harvestCommitables(commitables, dir, targetFile, parentEntry, entry, url, null, false, false, justLocked, lockTokens, recurse, isRecursionForced, params); } while (targets.hasNext()); for (Iterator ds = danglers.iterator(); ds.hasNext();) { baseAccess.checkCancelled(); File file = (File) ds.next(); if (!commitables.containsKey(file)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET, "''{0}'' is not under version control\n" + "and is not part of the commit, \n" + "yet its child is part of the commit", file); SVNErrorManager.error(err); } } if (isRecursionForced) { // if commit is non-recursive and forced and there are elements included into commit // that not only 'copied' but also has local mods (modified or deleted), remove those items? // or not? for (Iterator items = commitables.values().iterator(); items.hasNext();) { baseAccess.checkCancelled(); SVNCommitItem item = (SVNCommitItem) items.next(); if (item.isDeleted()) { // to detect deleted copied items. File file = item.getFile(); if (item.getKind() == SVNNodeKind.DIR) { if (!file.exists()) { continue; } } else { String name = SVNPathUtil.tail(item.getPath()); SVNAdminArea dir = baseAccess.retrieve(item.getFile().getParentFile()); if (!dir.getBaseFile(name, false).exists()) { continue; } } } if (item.isContentsModified() || item.isDeleted() || item.isPropertiesModified()) { // if item was not explicitly included into commit, then just make it 'added' // but do not remove that are marked as 'deleted' String itemPath = item.getPath(); if (!paths.contains(itemPath)) { items.remove(); } } } } return (SVNCommitItem[]) commitables.values().toArray(new SVNCommitItem[commitables.values().size()]); } public static String translateCommitables(SVNCommitItem[] items, Map decodedPaths) throws SVNException { Map itemsMap = new TreeMap(); for (int i = 0; i < items.length; i++) { SVNCommitItem item = items[i]; if (itemsMap.containsKey(item.getURL().toString())) { SVNCommitItem oldItem = (SVNCommitItem) itemsMap.get(item.getURL().toString()); SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_DUPLICATE_COMMIT_URL, "Cannot commit both ''{0}'' and ''{1}'' as they refer to the same URL", new Object[] {item.getFile(), oldItem.getFile()}); SVNErrorManager.error(err); } itemsMap.put(item.getURL().toString(), item); } Iterator urls = itemsMap.keySet().iterator(); String baseURL = (String) urls.next(); while (urls.hasNext()) { String url = (String) urls.next(); baseURL = SVNPathUtil.getCommonURLAncestor(baseURL, url); } if (itemsMap.containsKey(baseURL)) { SVNCommitItem root = (SVNCommitItem) itemsMap.get(baseURL); if (root.getKind() != SVNNodeKind.DIR) { baseURL = SVNPathUtil.removeTail(baseURL); } else if (root.getKind() == SVNNodeKind.DIR && (root.isAdded() || root.isDeleted() || root.isCopied() || root .isLocked())) { baseURL = SVNPathUtil.removeTail(baseURL); } } urls = itemsMap.keySet().iterator(); while (urls.hasNext()) { String url = (String) urls.next(); SVNCommitItem item = (SVNCommitItem) itemsMap.get(url); String realPath = url.equals(baseURL) ? "" : url.substring(baseURL.length() + 1); decodedPaths.put(SVNEncodingUtil.uriDecode(realPath), item); } return baseURL; } public static Map translateLockTokens(Map lockTokens, String baseURL) { Map translatedLocks = new TreeMap(); for (Iterator urls = lockTokens.keySet().iterator(); urls.hasNext();) { String url = (String) urls.next(); String token = (String) lockTokens.get(url); url = url.equals(baseURL) ? "" : url.substring(baseURL.length() + 1); translatedLocks.put(SVNEncodingUtil.uriDecode(url), token); } lockTokens.clear(); lockTokens.putAll(translatedLocks); return lockTokens; } public static void harvestCommitables(Map commitables, SVNAdminArea dir, File path, SVNEntry parentEntry, SVNEntry entry, String url, String copyFromURL, boolean copyMode, boolean addsOnly, boolean justLocked, Map lockTokens, boolean recursive, boolean forcedRecursion, ISVNCommitParameters params) throws SVNException { if (commitables.containsKey(path)) { return; } if (dir != null && dir.getWCAccess() != null) { dir.getWCAccess().checkCancelled(); } long cfRevision = entry.getCopyFromRevision(); String cfURL = null; if (entry.getKind() != SVNNodeKind.DIR && entry.getKind() != SVNNodeKind.FILE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknown entry kind for ''{0}''", path); SVNErrorManager.error(err); } SVNFileType fileType = SVNFileType.getType(path); if (fileType == SVNFileType.UNKNOWN) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknown entry kind for ''{0}''", path); SVNErrorManager.error(err); } String specialPropertyValue = dir.getProperties(entry.getName()).getPropertyValue(SVNProperty.SPECIAL); boolean specialFile = fileType == SVNFileType.SYMLINK; if (SVNFileType.isSymlinkSupportEnabled()) { if (((specialPropertyValue == null && specialFile) || (!SVNFileUtil.isWindows && specialPropertyValue != null && !specialFile)) && fileType != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNEXPECTED_KIND, "Entry ''{0}'' has unexpectedly changed special status", path); SVNErrorManager.error(err); } } boolean propConflicts; boolean textConflicts = false; SVNAdminArea entries = null; if (entry.getKind() == SVNNodeKind.DIR) { SVNAdminArea childDir = null; try { childDir = dir.getWCAccess().retrieve(dir.getFile(entry.getName())); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) { childDir = null; } else { throw e; } } if (childDir != null && childDir.entries(true) != null) { entries = childDir; if (entries.getEntry("", false) != null) { entry = entries.getEntry("", false); dir = childDir; } } - propConflicts = entries.hasPropConflict(entry.getName()); + propConflicts = dir.hasPropConflict(entry.getName()); } else { - propConflicts = entries.hasPropConflict(entry.getName()); - textConflicts = entries.hasTextConflict(entry.getName()); + propConflicts = dir.hasPropConflict(entry.getName()); + textConflicts = dir.hasTextConflict(entry.getName()); } if (propConflicts || textConflicts) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT, "Aborting commit: ''{0}'' remains in conflict", path); SVNErrorManager.error(err); } if (entry.getURL() != null && !copyMode) { url = entry.getURL(); } boolean commitDeletion = !addsOnly && ((entry.isDeleted() && entry.getSchedule() == null) || entry.isScheduledForDeletion() || entry.isScheduledForReplacement()); if (!addsOnly && !commitDeletion && fileType == SVNFileType.NONE && params != null) { ISVNCommitParameters.Action action = entry.getKind() == SVNNodeKind.DIR ? params.onMissingDirectory(path) : params.onMissingFile(path); if (action == ISVNCommitParameters.ERROR) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy file ''{0}'' is missing", path); SVNErrorManager.error(err); } else if (action == ISVNCommitParameters.DELETE) { commitDeletion = true; entry.scheduleForDeletion(); dir.saveEntries(false); } } boolean commitAddition = false; boolean commitCopy = false; if (entry.isScheduledForAddition() || entry.isScheduledForReplacement()) { commitAddition = true; if (entry.getCopyFromURL() != null) { cfURL = entry.getCopyFromURL(); addsOnly = false; commitCopy = true; } else { addsOnly = true; } } if ((entry.isCopied() || copyMode) && !entry.isDeleted() && entry.getSchedule() == null) { long parentRevision = entry.getRevision() - 1; if (!dir.getWCAccess().isWCRoot(path)) { if (parentEntry != null) { parentRevision = parentEntry.getRevision(); } } else if (!copyMode) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Did not expect ''{0}'' to be a working copy root", path); SVNErrorManager.error(err); } if (parentRevision != entry.getRevision()) { commitAddition = true; commitCopy = true; addsOnly = false; cfRevision = entry.getRevision(); if (copyMode) { cfURL = entry.getURL(); } else if (copyFromURL != null) { cfURL = copyFromURL; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", path); SVNErrorManager.error(err); } } } boolean textModified = false; boolean propsModified = false; boolean commitLock; if (commitAddition) { SVNVersionedProperties props = dir.getProperties(entry.getName()); SVNVersionedProperties baseProps = dir.getBaseProperties(entry.getName()); Map propDiff = null; if (entry.isScheduledForReplacement()) { propDiff = props.asMap(); } else { propDiff = baseProps.compareTo(props).asMap(); } boolean eolChanged = textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); if (entry.getKind() == SVNNodeKind.FILE) { if (commitCopy) { textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); if (!textModified) { textModified = dir.hasTextModifications(entry.getName(), eolChanged); } } else { textModified = true; } } propsModified = propDiff != null && !propDiff.isEmpty(); } else if (!commitDeletion) { SVNVersionedProperties props = dir.getProperties(entry.getName()); SVNVersionedProperties baseProps = dir.getBaseProperties(entry.getName()); Map propDiff = baseProps.compareTo(props).asMap(); boolean eolChanged = textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); propsModified = propDiff != null && !propDiff.isEmpty(); if (entry.getKind() == SVNNodeKind.FILE) { textModified = dir.hasTextModifications(entry.getName(), eolChanged); } } commitLock = entry.getLockToken() != null && (justLocked || textModified || propsModified || commitDeletion || commitAddition || commitCopy); if (commitAddition || commitDeletion || textModified || propsModified || commitCopy || commitLock) { SVNCommitItem item = new SVNCommitItem(path, SVNURL.parseURIEncoded(url), cfURL != null ? SVNURL.parseURIEncoded(cfURL) : null, entry.getKind(), SVNRevision.create(entry.getRevision()), SVNRevision.create(cfRevision), commitAddition, commitDeletion, propsModified, textModified, commitCopy, commitLock); String itemPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor())); if ("".equals(itemPath)) { itemPath += entry.getName(); } else if (!"".equals(entry.getName())) { itemPath += "/" + entry.getName(); } item.setPath(itemPath); commitables.put(path, item); if (lockTokens != null && entry.getLockToken() != null) { lockTokens.put(url, entry.getLockToken()); } } if (entries != null && recursive && (commitAddition || !commitDeletion)) { // recurse. for (Iterator ents = entries.entries(copyMode); ents.hasNext();) { if (dir != null && dir.getWCAccess() != null) { dir.getWCAccess().checkCancelled(); } SVNEntry currentEntry = (SVNEntry) ents.next(); if ("".equals(currentEntry.getName())) { continue; } // if recursion is forced and entry is explicitly copied, skip it. if (forcedRecursion && currentEntry.isCopied() && currentEntry.getCopyFromURL() != null) { continue; } String currentCFURL = cfURL != null ? cfURL : copyFromURL; if (currentCFURL != null) { currentCFURL = SVNPathUtil.append(currentCFURL, SVNEncodingUtil.uriEncode(currentEntry.getName())); } String currentURL = currentEntry.getURL(); if (copyMode || entry.getURL() == null) { currentURL = SVNPathUtil.append(url, SVNEncodingUtil.uriEncode(currentEntry.getName())); } File currentFile = dir.getFile(currentEntry.getName()); SVNAdminArea childDir; if (currentEntry.getKind() == SVNNodeKind.DIR) { try { childDir = dir.getWCAccess().retrieve(dir.getFile(currentEntry.getName())); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) { childDir = null; } else { throw e; } } if (childDir == null) { SVNFileType currentType = SVNFileType.getType(currentFile); if (currentType == SVNFileType.NONE && currentEntry.isScheduledForDeletion()) { SVNCommitItem item = new SVNCommitItem(currentFile, SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(), SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, false, true, false, false, false, false); String dirPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor())); item.setPath(SVNPathUtil.append(dirPath, currentEntry.getName())); commitables.put(currentFile, item); continue; } else if (currentType != SVNFileType.NONE) { // directory is not missing, but obstructed, // or no special params are specified. SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile); SVNErrorManager.error(err); } else { ISVNCommitParameters.Action action = params != null ? params.onMissingDirectory(dir.getFile(currentEntry.getName())) : ISVNCommitParameters.ERROR; if (action == ISVNCommitParameters.DELETE) { SVNCommitItem item = new SVNCommitItem(currentFile, SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(), SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, false, true, false, false, false, false); String dirPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor())); item.setPath(SVNPathUtil.append(dirPath, currentEntry.getName())); commitables.put(currentFile, item); currentEntry.scheduleForDeletion(); entries.saveEntries(false); continue; } else if (action != ISVNCommitParameters.SKIP) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile); SVNErrorManager.error(err); } } } } harvestCommitables(commitables, dir, currentFile, entry, currentEntry, currentURL, currentCFURL, copyMode, addsOnly, justLocked, lockTokens, true, forcedRecursion, params); } } if (lockTokens != null && entry.getKind() == SVNNodeKind.DIR && commitDeletion) { // harvest lock tokens for deleted items. collectLocks(dir, lockTokens); } } private static void collectLocks(SVNAdminArea adminArea, Map lockTokens) throws SVNException { for (Iterator ents = adminArea.entries(false); ents.hasNext();) { SVNEntry entry = (SVNEntry) ents.next(); if (entry.getURL() != null && entry.getLockToken() != null) { lockTokens.put(entry.getURL(), entry.getLockToken()); } if (!adminArea.getThisDirName().equals(entry.getName()) && entry.isDirectory()) { SVNAdminArea child; try { child = adminArea.getWCAccess().retrieve(adminArea.getFile(entry.getName())); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) { child = null; } else { throw e; } } if (child != null) { collectLocks(child, lockTokens); } } } adminArea.closeEntries(); } private static void removeRedundantPaths(Collection dirsToLockRecursively, Collection dirsToLock) { for (Iterator paths = dirsToLock.iterator(); paths.hasNext();) { String path = (String) paths.next(); if (dirsToLockRecursively.contains(path)) { paths.remove(); } else { for (Iterator recPaths = dirsToLockRecursively.iterator(); recPaths.hasNext();) { String existingPath = (String) recPaths.next(); if (path.startsWith(existingPath + "/")) { paths.remove(); break; } } } } } private static File adjustRelativePaths(File rootFile, Collection relativePaths) throws SVNException { if (relativePaths.contains("")) { String targetName = getTargetName(rootFile); if (!"".equals(targetName) && rootFile.getParentFile() != null) { // there is a versioned parent. rootFile = rootFile.getParentFile(); List result = new ArrayList(); for (Iterator paths = relativePaths.iterator(); paths.hasNext();) { String path = (String) paths.next(); path = "".equals(path) ? targetName : SVNPathUtil.append(targetName, path); if (!result.contains(path)) { result.add(path); } } relativePaths.clear(); Collections.sort(result); relativePaths.addAll(result); } } return rootFile; } private static String getTargetName(File file) throws SVNException { SVNWCAccess wcAccess = SVNWCAccess.newInstance(null); try { wcAccess.probeOpen(file, false, 0); SVNFileType fileType = SVNFileType.getType(file); if ((fileType == SVNFileType.FILE || fileType == SVNFileType.SYMLINK) || !wcAccess.isWCRoot(file)) { return file.getName(); } } finally { wcAccess.close(); } return ""; } private static boolean isRecursiveCommitForced(File directory) throws SVNException { SVNWCAccess wcAccess = SVNWCAccess.newInstance(null); try { wcAccess.open(directory, false, 0); SVNEntry targetEntry = wcAccess.getEntry(directory, false); if (targetEntry != null) { return targetEntry.isCopied() || targetEntry.isScheduledForDeletion() || targetEntry.isScheduledForReplacement(); } } finally { wcAccess.close(); } return false; } }
false
true
public static void harvestCommitables(Map commitables, SVNAdminArea dir, File path, SVNEntry parentEntry, SVNEntry entry, String url, String copyFromURL, boolean copyMode, boolean addsOnly, boolean justLocked, Map lockTokens, boolean recursive, boolean forcedRecursion, ISVNCommitParameters params) throws SVNException { if (commitables.containsKey(path)) { return; } if (dir != null && dir.getWCAccess() != null) { dir.getWCAccess().checkCancelled(); } long cfRevision = entry.getCopyFromRevision(); String cfURL = null; if (entry.getKind() != SVNNodeKind.DIR && entry.getKind() != SVNNodeKind.FILE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknown entry kind for ''{0}''", path); SVNErrorManager.error(err); } SVNFileType fileType = SVNFileType.getType(path); if (fileType == SVNFileType.UNKNOWN) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknown entry kind for ''{0}''", path); SVNErrorManager.error(err); } String specialPropertyValue = dir.getProperties(entry.getName()).getPropertyValue(SVNProperty.SPECIAL); boolean specialFile = fileType == SVNFileType.SYMLINK; if (SVNFileType.isSymlinkSupportEnabled()) { if (((specialPropertyValue == null && specialFile) || (!SVNFileUtil.isWindows && specialPropertyValue != null && !specialFile)) && fileType != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNEXPECTED_KIND, "Entry ''{0}'' has unexpectedly changed special status", path); SVNErrorManager.error(err); } } boolean propConflicts; boolean textConflicts = false; SVNAdminArea entries = null; if (entry.getKind() == SVNNodeKind.DIR) { SVNAdminArea childDir = null; try { childDir = dir.getWCAccess().retrieve(dir.getFile(entry.getName())); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) { childDir = null; } else { throw e; } } if (childDir != null && childDir.entries(true) != null) { entries = childDir; if (entries.getEntry("", false) != null) { entry = entries.getEntry("", false); dir = childDir; } } propConflicts = entries.hasPropConflict(entry.getName()); } else { propConflicts = entries.hasPropConflict(entry.getName()); textConflicts = entries.hasTextConflict(entry.getName()); } if (propConflicts || textConflicts) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT, "Aborting commit: ''{0}'' remains in conflict", path); SVNErrorManager.error(err); } if (entry.getURL() != null && !copyMode) { url = entry.getURL(); } boolean commitDeletion = !addsOnly && ((entry.isDeleted() && entry.getSchedule() == null) || entry.isScheduledForDeletion() || entry.isScheduledForReplacement()); if (!addsOnly && !commitDeletion && fileType == SVNFileType.NONE && params != null) { ISVNCommitParameters.Action action = entry.getKind() == SVNNodeKind.DIR ? params.onMissingDirectory(path) : params.onMissingFile(path); if (action == ISVNCommitParameters.ERROR) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy file ''{0}'' is missing", path); SVNErrorManager.error(err); } else if (action == ISVNCommitParameters.DELETE) { commitDeletion = true; entry.scheduleForDeletion(); dir.saveEntries(false); } } boolean commitAddition = false; boolean commitCopy = false; if (entry.isScheduledForAddition() || entry.isScheduledForReplacement()) { commitAddition = true; if (entry.getCopyFromURL() != null) { cfURL = entry.getCopyFromURL(); addsOnly = false; commitCopy = true; } else { addsOnly = true; } } if ((entry.isCopied() || copyMode) && !entry.isDeleted() && entry.getSchedule() == null) { long parentRevision = entry.getRevision() - 1; if (!dir.getWCAccess().isWCRoot(path)) { if (parentEntry != null) { parentRevision = parentEntry.getRevision(); } } else if (!copyMode) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Did not expect ''{0}'' to be a working copy root", path); SVNErrorManager.error(err); } if (parentRevision != entry.getRevision()) { commitAddition = true; commitCopy = true; addsOnly = false; cfRevision = entry.getRevision(); if (copyMode) { cfURL = entry.getURL(); } else if (copyFromURL != null) { cfURL = copyFromURL; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", path); SVNErrorManager.error(err); } } } boolean textModified = false; boolean propsModified = false; boolean commitLock; if (commitAddition) { SVNVersionedProperties props = dir.getProperties(entry.getName()); SVNVersionedProperties baseProps = dir.getBaseProperties(entry.getName()); Map propDiff = null; if (entry.isScheduledForReplacement()) { propDiff = props.asMap(); } else { propDiff = baseProps.compareTo(props).asMap(); } boolean eolChanged = textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); if (entry.getKind() == SVNNodeKind.FILE) { if (commitCopy) { textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); if (!textModified) { textModified = dir.hasTextModifications(entry.getName(), eolChanged); } } else { textModified = true; } } propsModified = propDiff != null && !propDiff.isEmpty(); } else if (!commitDeletion) { SVNVersionedProperties props = dir.getProperties(entry.getName()); SVNVersionedProperties baseProps = dir.getBaseProperties(entry.getName()); Map propDiff = baseProps.compareTo(props).asMap(); boolean eolChanged = textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); propsModified = propDiff != null && !propDiff.isEmpty(); if (entry.getKind() == SVNNodeKind.FILE) { textModified = dir.hasTextModifications(entry.getName(), eolChanged); } } commitLock = entry.getLockToken() != null && (justLocked || textModified || propsModified || commitDeletion || commitAddition || commitCopy); if (commitAddition || commitDeletion || textModified || propsModified || commitCopy || commitLock) { SVNCommitItem item = new SVNCommitItem(path, SVNURL.parseURIEncoded(url), cfURL != null ? SVNURL.parseURIEncoded(cfURL) : null, entry.getKind(), SVNRevision.create(entry.getRevision()), SVNRevision.create(cfRevision), commitAddition, commitDeletion, propsModified, textModified, commitCopy, commitLock); String itemPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor())); if ("".equals(itemPath)) { itemPath += entry.getName(); } else if (!"".equals(entry.getName())) { itemPath += "/" + entry.getName(); } item.setPath(itemPath); commitables.put(path, item); if (lockTokens != null && entry.getLockToken() != null) { lockTokens.put(url, entry.getLockToken()); } } if (entries != null && recursive && (commitAddition || !commitDeletion)) { // recurse. for (Iterator ents = entries.entries(copyMode); ents.hasNext();) { if (dir != null && dir.getWCAccess() != null) { dir.getWCAccess().checkCancelled(); } SVNEntry currentEntry = (SVNEntry) ents.next(); if ("".equals(currentEntry.getName())) { continue; } // if recursion is forced and entry is explicitly copied, skip it. if (forcedRecursion && currentEntry.isCopied() && currentEntry.getCopyFromURL() != null) { continue; } String currentCFURL = cfURL != null ? cfURL : copyFromURL; if (currentCFURL != null) { currentCFURL = SVNPathUtil.append(currentCFURL, SVNEncodingUtil.uriEncode(currentEntry.getName())); } String currentURL = currentEntry.getURL(); if (copyMode || entry.getURL() == null) { currentURL = SVNPathUtil.append(url, SVNEncodingUtil.uriEncode(currentEntry.getName())); } File currentFile = dir.getFile(currentEntry.getName()); SVNAdminArea childDir; if (currentEntry.getKind() == SVNNodeKind.DIR) { try { childDir = dir.getWCAccess().retrieve(dir.getFile(currentEntry.getName())); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) { childDir = null; } else { throw e; } } if (childDir == null) { SVNFileType currentType = SVNFileType.getType(currentFile); if (currentType == SVNFileType.NONE && currentEntry.isScheduledForDeletion()) { SVNCommitItem item = new SVNCommitItem(currentFile, SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(), SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, false, true, false, false, false, false); String dirPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor())); item.setPath(SVNPathUtil.append(dirPath, currentEntry.getName())); commitables.put(currentFile, item); continue; } else if (currentType != SVNFileType.NONE) { // directory is not missing, but obstructed, // or no special params are specified. SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile); SVNErrorManager.error(err); } else { ISVNCommitParameters.Action action = params != null ? params.onMissingDirectory(dir.getFile(currentEntry.getName())) : ISVNCommitParameters.ERROR; if (action == ISVNCommitParameters.DELETE) { SVNCommitItem item = new SVNCommitItem(currentFile, SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(), SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, false, true, false, false, false, false); String dirPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor())); item.setPath(SVNPathUtil.append(dirPath, currentEntry.getName())); commitables.put(currentFile, item); currentEntry.scheduleForDeletion(); entries.saveEntries(false); continue; } else if (action != ISVNCommitParameters.SKIP) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile); SVNErrorManager.error(err); } } } } harvestCommitables(commitables, dir, currentFile, entry, currentEntry, currentURL, currentCFURL, copyMode, addsOnly, justLocked, lockTokens, true, forcedRecursion, params); } } if (lockTokens != null && entry.getKind() == SVNNodeKind.DIR && commitDeletion) { // harvest lock tokens for deleted items. collectLocks(dir, lockTokens); } }
public static void harvestCommitables(Map commitables, SVNAdminArea dir, File path, SVNEntry parentEntry, SVNEntry entry, String url, String copyFromURL, boolean copyMode, boolean addsOnly, boolean justLocked, Map lockTokens, boolean recursive, boolean forcedRecursion, ISVNCommitParameters params) throws SVNException { if (commitables.containsKey(path)) { return; } if (dir != null && dir.getWCAccess() != null) { dir.getWCAccess().checkCancelled(); } long cfRevision = entry.getCopyFromRevision(); String cfURL = null; if (entry.getKind() != SVNNodeKind.DIR && entry.getKind() != SVNNodeKind.FILE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknown entry kind for ''{0}''", path); SVNErrorManager.error(err); } SVNFileType fileType = SVNFileType.getType(path); if (fileType == SVNFileType.UNKNOWN) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknown entry kind for ''{0}''", path); SVNErrorManager.error(err); } String specialPropertyValue = dir.getProperties(entry.getName()).getPropertyValue(SVNProperty.SPECIAL); boolean specialFile = fileType == SVNFileType.SYMLINK; if (SVNFileType.isSymlinkSupportEnabled()) { if (((specialPropertyValue == null && specialFile) || (!SVNFileUtil.isWindows && specialPropertyValue != null && !specialFile)) && fileType != SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNEXPECTED_KIND, "Entry ''{0}'' has unexpectedly changed special status", path); SVNErrorManager.error(err); } } boolean propConflicts; boolean textConflicts = false; SVNAdminArea entries = null; if (entry.getKind() == SVNNodeKind.DIR) { SVNAdminArea childDir = null; try { childDir = dir.getWCAccess().retrieve(dir.getFile(entry.getName())); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) { childDir = null; } else { throw e; } } if (childDir != null && childDir.entries(true) != null) { entries = childDir; if (entries.getEntry("", false) != null) { entry = entries.getEntry("", false); dir = childDir; } } propConflicts = dir.hasPropConflict(entry.getName()); } else { propConflicts = dir.hasPropConflict(entry.getName()); textConflicts = dir.hasTextConflict(entry.getName()); } if (propConflicts || textConflicts) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT, "Aborting commit: ''{0}'' remains in conflict", path); SVNErrorManager.error(err); } if (entry.getURL() != null && !copyMode) { url = entry.getURL(); } boolean commitDeletion = !addsOnly && ((entry.isDeleted() && entry.getSchedule() == null) || entry.isScheduledForDeletion() || entry.isScheduledForReplacement()); if (!addsOnly && !commitDeletion && fileType == SVNFileType.NONE && params != null) { ISVNCommitParameters.Action action = entry.getKind() == SVNNodeKind.DIR ? params.onMissingDirectory(path) : params.onMissingFile(path); if (action == ISVNCommitParameters.ERROR) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy file ''{0}'' is missing", path); SVNErrorManager.error(err); } else if (action == ISVNCommitParameters.DELETE) { commitDeletion = true; entry.scheduleForDeletion(); dir.saveEntries(false); } } boolean commitAddition = false; boolean commitCopy = false; if (entry.isScheduledForAddition() || entry.isScheduledForReplacement()) { commitAddition = true; if (entry.getCopyFromURL() != null) { cfURL = entry.getCopyFromURL(); addsOnly = false; commitCopy = true; } else { addsOnly = true; } } if ((entry.isCopied() || copyMode) && !entry.isDeleted() && entry.getSchedule() == null) { long parentRevision = entry.getRevision() - 1; if (!dir.getWCAccess().isWCRoot(path)) { if (parentEntry != null) { parentRevision = parentEntry.getRevision(); } } else if (!copyMode) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Did not expect ''{0}'' to be a working copy root", path); SVNErrorManager.error(err); } if (parentRevision != entry.getRevision()) { commitAddition = true; commitCopy = true; addsOnly = false; cfRevision = entry.getRevision(); if (copyMode) { cfURL = entry.getURL(); } else if (copyFromURL != null) { cfURL = copyFromURL; } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", path); SVNErrorManager.error(err); } } } boolean textModified = false; boolean propsModified = false; boolean commitLock; if (commitAddition) { SVNVersionedProperties props = dir.getProperties(entry.getName()); SVNVersionedProperties baseProps = dir.getBaseProperties(entry.getName()); Map propDiff = null; if (entry.isScheduledForReplacement()) { propDiff = props.asMap(); } else { propDiff = baseProps.compareTo(props).asMap(); } boolean eolChanged = textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); if (entry.getKind() == SVNNodeKind.FILE) { if (commitCopy) { textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); if (!textModified) { textModified = dir.hasTextModifications(entry.getName(), eolChanged); } } else { textModified = true; } } propsModified = propDiff != null && !propDiff.isEmpty(); } else if (!commitDeletion) { SVNVersionedProperties props = dir.getProperties(entry.getName()); SVNVersionedProperties baseProps = dir.getBaseProperties(entry.getName()); Map propDiff = baseProps.compareTo(props).asMap(); boolean eolChanged = textModified = propDiff != null && propDiff.containsKey(SVNProperty.EOL_STYLE); propsModified = propDiff != null && !propDiff.isEmpty(); if (entry.getKind() == SVNNodeKind.FILE) { textModified = dir.hasTextModifications(entry.getName(), eolChanged); } } commitLock = entry.getLockToken() != null && (justLocked || textModified || propsModified || commitDeletion || commitAddition || commitCopy); if (commitAddition || commitDeletion || textModified || propsModified || commitCopy || commitLock) { SVNCommitItem item = new SVNCommitItem(path, SVNURL.parseURIEncoded(url), cfURL != null ? SVNURL.parseURIEncoded(cfURL) : null, entry.getKind(), SVNRevision.create(entry.getRevision()), SVNRevision.create(cfRevision), commitAddition, commitDeletion, propsModified, textModified, commitCopy, commitLock); String itemPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor())); if ("".equals(itemPath)) { itemPath += entry.getName(); } else if (!"".equals(entry.getName())) { itemPath += "/" + entry.getName(); } item.setPath(itemPath); commitables.put(path, item); if (lockTokens != null && entry.getLockToken() != null) { lockTokens.put(url, entry.getLockToken()); } } if (entries != null && recursive && (commitAddition || !commitDeletion)) { // recurse. for (Iterator ents = entries.entries(copyMode); ents.hasNext();) { if (dir != null && dir.getWCAccess() != null) { dir.getWCAccess().checkCancelled(); } SVNEntry currentEntry = (SVNEntry) ents.next(); if ("".equals(currentEntry.getName())) { continue; } // if recursion is forced and entry is explicitly copied, skip it. if (forcedRecursion && currentEntry.isCopied() && currentEntry.getCopyFromURL() != null) { continue; } String currentCFURL = cfURL != null ? cfURL : copyFromURL; if (currentCFURL != null) { currentCFURL = SVNPathUtil.append(currentCFURL, SVNEncodingUtil.uriEncode(currentEntry.getName())); } String currentURL = currentEntry.getURL(); if (copyMode || entry.getURL() == null) { currentURL = SVNPathUtil.append(url, SVNEncodingUtil.uriEncode(currentEntry.getName())); } File currentFile = dir.getFile(currentEntry.getName()); SVNAdminArea childDir; if (currentEntry.getKind() == SVNNodeKind.DIR) { try { childDir = dir.getWCAccess().retrieve(dir.getFile(currentEntry.getName())); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) { childDir = null; } else { throw e; } } if (childDir == null) { SVNFileType currentType = SVNFileType.getType(currentFile); if (currentType == SVNFileType.NONE && currentEntry.isScheduledForDeletion()) { SVNCommitItem item = new SVNCommitItem(currentFile, SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(), SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, false, true, false, false, false, false); String dirPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor())); item.setPath(SVNPathUtil.append(dirPath, currentEntry.getName())); commitables.put(currentFile, item); continue; } else if (currentType != SVNFileType.NONE) { // directory is not missing, but obstructed, // or no special params are specified. SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile); SVNErrorManager.error(err); } else { ISVNCommitParameters.Action action = params != null ? params.onMissingDirectory(dir.getFile(currentEntry.getName())) : ISVNCommitParameters.ERROR; if (action == ISVNCommitParameters.DELETE) { SVNCommitItem item = new SVNCommitItem(currentFile, SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(), SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, false, true, false, false, false, false); String dirPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor())); item.setPath(SVNPathUtil.append(dirPath, currentEntry.getName())); commitables.put(currentFile, item); currentEntry.scheduleForDeletion(); entries.saveEntries(false); continue; } else if (action != ISVNCommitParameters.SKIP) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile); SVNErrorManager.error(err); } } } } harvestCommitables(commitables, dir, currentFile, entry, currentEntry, currentURL, currentCFURL, copyMode, addsOnly, justLocked, lockTokens, true, forcedRecursion, params); } } if (lockTokens != null && entry.getKind() == SVNNodeKind.DIR && commitDeletion) { // harvest lock tokens for deleted items. collectLocks(dir, lockTokens); } }
diff --git a/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/AbstractComponentAttributes.java b/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/AbstractComponentAttributes.java index 79305a51..722fa96d 100644 --- a/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/AbstractComponentAttributes.java +++ b/ftest-source/src/main/java/org/richfaces/tests/metamer/ftest/AbstractComponentAttributes.java @@ -1,148 +1,148 @@ /******************************************************************************* * JBoss, Home of Professional Open Source * Copyright 2010-2011, Red Hat, Inc. 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.richfaces.tests.metamer.ftest; import static org.jboss.test.selenium.guard.request.RequestTypeGuardFactory.guard; import static org.jboss.test.selenium.locator.LocatorFactory.jq; import static org.jboss.test.selenium.locator.reference.ReferencedLocator.referenceInferred; import static org.richfaces.tests.metamer.ftest.AbstractMetamerTest.pjq; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.WordUtils; import org.jboss.test.selenium.dom.Event; import org.jboss.test.selenium.framework.AjaxSelenium; import org.jboss.test.selenium.framework.AjaxSeleniumProxy; import org.jboss.test.selenium.locator.Attribute; import org.jboss.test.selenium.locator.AttributeLocator; import org.jboss.test.selenium.locator.ElementLocator; import org.jboss.test.selenium.locator.ExtendedLocator; import org.jboss.test.selenium.locator.JQueryLocator; import org.jboss.test.selenium.locator.option.OptionValueLocator; import org.jboss.test.selenium.locator.reference.LocatorReference; import org.jboss.test.selenium.locator.reference.ReferencedLocator; import org.jboss.test.selenium.request.RequestType; /** * @author <a href="mailto:[email protected]">Lukas Fryc</a> * @version $Revision$ */ public class AbstractComponentAttributes { protected AjaxSelenium selenium = AjaxSeleniumProxy.getInstance(); LocatorReference<ExtendedLocator<JQueryLocator>> root = new LocatorReference<ExtendedLocator<JQueryLocator>>( pjq("")); ReferencedLocator<JQueryLocator> propertyLocator = referenceInferred(root, "*[id*={0}Input]{1}"); RequestType requestType = RequestType.HTTP; public AbstractComponentAttributes() { } public <T extends ExtendedLocator<JQueryLocator>> AbstractComponentAttributes(T root) { this.root.setLocator(root); } protected String getProperty(String propertyName) { final ElementLocator<?> locator = propertyLocator.format(propertyName, ""); return selenium.getValue(locator); } protected void setProperty(String propertyName, Object value) { ExtendedLocator<JQueryLocator> locator = propertyLocator.format(propertyName); - final AttributeLocator<?> typeLocator = locator.getAttribute(Attribute.TYPE); + final AttributeLocator<?> typeLocator = locator.format("").getAttribute(Attribute.TYPE); final ExtendedLocator<JQueryLocator> optionLocator = locator.getChild(jq("option")); String inputType = null; if (selenium.getCount(propertyLocator.format(propertyName)) > 1) { inputType = "radio"; } else if (selenium.getCount(optionLocator) > 1) { inputType = "select"; } else { inputType = selenium.getAttribute(typeLocator); } if (value == null) { value = ""; } String valueAsString = value.toString(); if (value.getClass().isEnum()) { if ("select".equals(inputType) && !selenium.getSelectOptions(locator).contains(valueAsString)) { valueAsString = valueAsString.toLowerCase(); valueAsString = WordUtils.capitalizeFully(valueAsString, new char[] { '_' }); valueAsString = valueAsString.replace("_", ""); valueAsString = StringUtils.uncapitalize(valueAsString); } } if ("text".equals(inputType)) { applyText(locator, valueAsString); } else if ("checkbox".equals(inputType)) { boolean checked = Boolean.valueOf(valueAsString); applyCheckbox(locator, checked); } else if ("radio".equals(inputType)) { locator = propertyLocator.format(propertyName, "[value=" + ("".equals(valueAsString) ? "null" : valueAsString) + "]"); if (!selenium.isChecked(locator)) { applyRadio(locator); } } else if ("select".equals(inputType)) { String curValue = selenium.getValue(locator); if (valueAsString.equals(curValue)) { return; } applySelect(locator, valueAsString); } } public void setRequestType(RequestType requestType) { this.requestType = requestType; } public RequestType getRequestType() { return requestType; } protected void applyText(ElementLocator<?> locator, String value) { guard(selenium, requestType).type(locator, value); } protected void applyCheckbox(ElementLocator<?> locator, boolean checked) { selenium.check(locator, checked); guard(selenium, requestType).fireEvent(locator, Event.CHANGE); } protected void applyRadio(ElementLocator<?> locator) { guard(selenium, requestType).click(locator); } protected void applySelect(ElementLocator<?> locator, String value) { OptionValueLocator optionLocator = new OptionValueLocator(value); guard(selenium, requestType).select(locator, optionLocator); } public void setOncomplete(String oncomplete) { setProperty("oncomplete", oncomplete); } }
true
true
protected void setProperty(String propertyName, Object value) { ExtendedLocator<JQueryLocator> locator = propertyLocator.format(propertyName); final AttributeLocator<?> typeLocator = locator.getAttribute(Attribute.TYPE); final ExtendedLocator<JQueryLocator> optionLocator = locator.getChild(jq("option")); String inputType = null; if (selenium.getCount(propertyLocator.format(propertyName)) > 1) { inputType = "radio"; } else if (selenium.getCount(optionLocator) > 1) { inputType = "select"; } else { inputType = selenium.getAttribute(typeLocator); } if (value == null) { value = ""; } String valueAsString = value.toString(); if (value.getClass().isEnum()) { if ("select".equals(inputType) && !selenium.getSelectOptions(locator).contains(valueAsString)) { valueAsString = valueAsString.toLowerCase(); valueAsString = WordUtils.capitalizeFully(valueAsString, new char[] { '_' }); valueAsString = valueAsString.replace("_", ""); valueAsString = StringUtils.uncapitalize(valueAsString); } } if ("text".equals(inputType)) { applyText(locator, valueAsString); } else if ("checkbox".equals(inputType)) { boolean checked = Boolean.valueOf(valueAsString); applyCheckbox(locator, checked); } else if ("radio".equals(inputType)) { locator = propertyLocator.format(propertyName, "[value=" + ("".equals(valueAsString) ? "null" : valueAsString) + "]"); if (!selenium.isChecked(locator)) { applyRadio(locator); } } else if ("select".equals(inputType)) { String curValue = selenium.getValue(locator); if (valueAsString.equals(curValue)) { return; } applySelect(locator, valueAsString); } }
protected void setProperty(String propertyName, Object value) { ExtendedLocator<JQueryLocator> locator = propertyLocator.format(propertyName); final AttributeLocator<?> typeLocator = locator.format("").getAttribute(Attribute.TYPE); final ExtendedLocator<JQueryLocator> optionLocator = locator.getChild(jq("option")); String inputType = null; if (selenium.getCount(propertyLocator.format(propertyName)) > 1) { inputType = "radio"; } else if (selenium.getCount(optionLocator) > 1) { inputType = "select"; } else { inputType = selenium.getAttribute(typeLocator); } if (value == null) { value = ""; } String valueAsString = value.toString(); if (value.getClass().isEnum()) { if ("select".equals(inputType) && !selenium.getSelectOptions(locator).contains(valueAsString)) { valueAsString = valueAsString.toLowerCase(); valueAsString = WordUtils.capitalizeFully(valueAsString, new char[] { '_' }); valueAsString = valueAsString.replace("_", ""); valueAsString = StringUtils.uncapitalize(valueAsString); } } if ("text".equals(inputType)) { applyText(locator, valueAsString); } else if ("checkbox".equals(inputType)) { boolean checked = Boolean.valueOf(valueAsString); applyCheckbox(locator, checked); } else if ("radio".equals(inputType)) { locator = propertyLocator.format(propertyName, "[value=" + ("".equals(valueAsString) ? "null" : valueAsString) + "]"); if (!selenium.isChecked(locator)) { applyRadio(locator); } } else if ("select".equals(inputType)) { String curValue = selenium.getValue(locator); if (valueAsString.equals(curValue)) { return; } applySelect(locator, valueAsString); } }
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/permission/SqlHelper.java b/src/FE_SRC_COMMON/com/ForgeEssentials/permission/SqlHelper.java index 7d70a8d04..81022137d 100644 --- a/src/FE_SRC_COMMON/com/ForgeEssentials/permission/SqlHelper.java +++ b/src/FE_SRC_COMMON/com/ForgeEssentials/permission/SqlHelper.java @@ -1,2377 +1,2377 @@ package com.ForgeEssentials.permission; import com.ForgeEssentials.api.permissions.Group; import com.ForgeEssentials.api.permissions.PermissionsAPI; import com.ForgeEssentials.api.permissions.RegGroup; import com.ForgeEssentials.api.permissions.ZoneManager; import com.ForgeEssentials.api.permissions.query.PermQuery.PermResult; import com.ForgeEssentials.util.DBConnector; import com.ForgeEssentials.util.EnumDBType; import com.ForgeEssentials.util.OutputHandler; import java.io.File; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.TreeSet; import com.google.common.base.Throwables; public class SqlHelper { private Connection db; private boolean generate = false; private static SqlHelper instance; private EnumDBType dbType; // tables private static final String TABLE_ZONE = "zones"; private static final String TABLE_GROUP = "groups"; private static final String TABLE_GROUP_CONNECTOR = "groupConnectors"; private static final String TABLE_LADDER = "ladders"; private static final String TABLE_LADDER_NAME = "ladderNames"; private static final String TABLE_PLAYER = "players"; private static final String TABLE_PERMISSION = "permissions"; // columns for the zone table private static final String COLUMN_ZONE_ZONEID = "zoneID"; private static final String COLUMN_ZONE_NAME = "zoneName"; // columns for the group table private static final String COLUMN_GROUP_GROUPID = "groupID"; private static final String COLUMN_GROUP_NAME = "groupName"; private static final String COLUMN_GROUP_PARENT = "parent"; private static final String COLUMN_GROUP_PREFIX = "prefix"; private static final String COLUMN_GROUP_SUFFIX = "suffix"; private static final String COLUMN_GROUP_PRIORITY = "priority"; private static final String COLUMN_GROUP_ZONE = "zone"; // group connector table. private static final String COLUMN_GROUP_CONNECTOR_GROUPID = "groupID"; private static final String COLUMN_GROUP_CONNECTOR_PLAYERID = "playerID"; private static final String COLUMN_GROUP_CONNECTOR_ZONEID = "zoneID"; // ladder table private static final String COLUMN_LADDER_LADDERID = "ladderID"; private static final String COLUMN_LADDER_GROUPID = "groupID"; private static final String COLUMN_LADDER_ZONEID = "zoneID"; private static final String COLUMN_LADDER_RANK = "rank"; // ladderName table private static final String COLUMN_LADDER_NAME_LADDERID = "ladderID"; private static final String COLUMN_LADDER_NAME_NAME = "ladderName"; // player table private static final String COLUMN_PLAYER_PLAYERID = "playerID"; private static final String COLUMN_PLAYER_USERNAME = "username"; // permissions table private static final String COLUMN_PERMISSION_TARGET = "target"; private static final String COLUMN_PERMISSION_ISGROUP = "isGroup"; private static final String COLUMN_PERMISSION_PERM = "perm"; private static final String COLUMN_PERMISSION_ALLOWED = "allowed"; private static final String COLUMN_PERMISSION_ZONEID = "zoneID"; // zones private final PreparedStatement statementGetZoneIDFromName; // zoneName >> zoneID private final PreparedStatement statementGetZoneNameFromID; // zoneID >> zoneName private final PreparedStatement statementPutZone; // $ ZoneName private final PreparedStatement statementDelZone; // X ZoneName // players private final PreparedStatement statementGetPlayerIDFromName; // playerName >> playerID private final PreparedStatement statementGetPlayerNameFromID; // playerID >> playerName private final PreparedStatement statementPutPlayer; // $ usernName private final PreparedStatement statementRemovePlayerGroups; private final PreparedStatement statementPutPlayerInGroup; private final PreparedStatement statementRemovePlayerGroup; // groups private final PreparedStatement statementGetGroupIDFromName; // groupName >> groupID private final PreparedStatement statementGetGroupNameFromID; // groupID >> groupName private final PreparedStatement statementGetGroupFromName; // groupName >> Group private final PreparedStatement statementGetGroupFromID; // groupID >> Group private final PreparedStatement statementGetGroupsForPlayer; // PlayerID, ZoneID >> Groups private final PreparedStatement statementGetGroupsInZone; // ZoneID private final PreparedStatement statementGetGroupIDsForEntryPlayer; // ZoneID >> GroupIDs private final PreparedStatement statementPutGroup; // $ name, prefix, suffix, parent, priority, zone private final PreparedStatement statementUpdateGroup; // $ name, prefix, suffix, parent, priority, zone private final PreparedStatement statementDeleteGroupInZone; // ladders private final PreparedStatement statementGetLadderIDFromName; // ladderName >> ladderID private final PreparedStatement statementGetLadderNameFromID; // LadderID >> ladderName private final PreparedStatement statementGetLadderIDFromGroup; // groupID, zoneID >> ladderID private final PreparedStatement statementGetLadderList; // LadderID, ZoneID >> groupName, rank private final PreparedStatement statementGetGroupsFromLadder; // PlayerID, LadderID >> group private final PreparedStatement statementGetGroupsFromLadderAndZone; // PlayerID, LadderID, ZoneID >> group private final PreparedStatement statementGetGroupsFromZone; // PlayerID, ZoneID >> group private final PreparedStatement statementGetGroupsFromPlayer; // PlayerID >> group private final PreparedStatement statementPutLadderName; // $ LadderName private final PreparedStatement statementPutLadder; // $ groupid, zoneID, rank, ladderID // permissions private final PreparedStatement statementGetPermission; // target, isgroup, perm, zone >> allowed private final PreparedStatement statementGetAllPermissions; private final PreparedStatement statementGetAll; // target, isgroup, zone >> allowed private final PreparedStatement statementGetPermissionForward; // target, isgroup, perm, zone >> allowed private final PreparedStatement statementPutPermission; // $ , allowed, target, isgroup, perm, zone private final PreparedStatement statementUpdatePermission; // $ allowed, target, isgroup, perm, zone private final PreparedStatement statementDeletePermission; // dump statements... replace ALL ids with names... private final PreparedStatement statementDumpGroups; private final PreparedStatement statementDumpPlayers; private final PreparedStatement statementDumpGroupPermissions; private final PreparedStatement statementDumpPlayerPermissions; private final PreparedStatement statementDumpGroupConnector; private final PreparedStatement statementDumpLadders; // zone deletion statements private final PreparedStatement statementDelPermFromZone; private final PreparedStatement statementDelLadderFromZone; private final PreparedStatement statementDelGroupFromZone; private final PreparedStatement statementDelGroupConnectorsFromZone; public SqlHelper(ConfigPermissions config) { instance = this; connect(config.connector); if (generate) generate(); try { // statementGetLadderList StringBuilder query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_LADDER).append(".").append(COLUMN_LADDER_RANK) .append(" FROM ").append(TABLE_LADDER) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" WHERE ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_LADDERID).append("=").append("?") .append(" AND ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_ZONEID).append("=").append("?") .append(" ORDER BY ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_RANK); statementGetLadderList = instance.db.prepareStatement(query.toString()); // statementGetGroupsFromLadder query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_LADDER) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_GROUPID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?") .append(" AND ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_LADDERID).append("=").append("?"); statementGetGroupsFromLadder = instance.db.prepareStatement(query.toString()); // statementGetGroupsFromLadderAndZone query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_LADDER) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_GROUPID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?") .append(" AND ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_LADDERID).append("=").append("?") .append(" AND ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementGetGroupsFromLadderAndZone = instance.db.prepareStatement(query.toString()); // statementGetGroupsFromZone query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?") .append(" AND ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementGetGroupsFromZone = instance.db.prepareStatement(query.toString()); // statementGetGroupsFromZone query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?"); statementGetGroupsFromPlayer = instance.db.prepareStatement(query.toString()); // statementGetGroupFromName query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PARENT).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME) .append(" FROM ").append(TABLE_GROUP) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_ZONE).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append("=").append("?"); statementGetGroupFromName = instance.db.prepareStatement(query.toString()); // statementGetGroupFromID query = new StringBuilder("SELECT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_GROUP).append(".") .append(COLUMN_GROUP_PRIORITY).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ").append(TABLE_GROUP) .append(".").append(COLUMN_GROUP_SUFFIX).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PARENT).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(" FROM ").append(TABLE_GROUP).append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_ZONE).append("=").append(TABLE_ZONE).append(".") .append(COLUMN_ZONE_ZONEID).append(" WHERE ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID).append("=").append("?"); statementGetGroupFromID = instance.db.prepareStatement(query.toString()); // statementGetGroupsForPlayer query = new StringBuilder("SELECT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_GROUP).append(".") .append(COLUMN_GROUP_PRIORITY).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ").append(TABLE_GROUP) .append(".").append(COLUMN_GROUP_SUFFIX).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PARENT).append(" FROM ") .append(TABLE_GROUP_CONNECTOR).append(" INNER JOIN ").append(TABLE_GROUP).append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".") .append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID).append(" WHERE ") .append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?").append(" AND ") .append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementGetGroupsForPlayer = instance.db.prepareStatement(query.toString()); // statementGetGroupsInZone query = new StringBuilder("SELECT * FROM ").append(TABLE_GROUP).append(" WHERE ").append(COLUMN_GROUP_ZONE).append("=").append("?"); statementGetGroupsInZone = instance.db.prepareStatement(query.toString()); // statementGetGroupIDsForEntryPlayer query = new StringBuilder("SELECT ").append(COLUMN_GROUP_CONNECTOR_GROUPID) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" WHERE ").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append(0) .append(" AND ").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementGetGroupIDsForEntryPlayer = instance.db.prepareStatement(query.toString()); // statementUpdateGroup query = new StringBuilder("UPDATE ").append(TABLE_GROUP).append(" SET ").append(COLUMN_GROUP_NAME).append("=").append("?, ") .append(COLUMN_GROUP_PREFIX).append("=").append("?, ").append(COLUMN_GROUP_SUFFIX).append("=").append("?, ").append(COLUMN_GROUP_PARENT) .append("=").append("?, ").append(COLUMN_GROUP_PRIORITY).append("=").append("?, ").append(COLUMN_GROUP_ZONE).append("=").append("?") .append(" WHERE ").append(COLUMN_GROUP_NAME).append("=").append("?") .append(" AND ").append(COLUMN_GROUP_ZONE).append("=").append("?"); statementUpdateGroup = db.prepareStatement(query.toString()); // statementGetPermission query = new StringBuilder("SELECT ").append(COLUMN_PERMISSION_ALLOWED).append(" FROM ").append(TABLE_PERMISSION).append(" WHERE ") .append(COLUMN_PERMISSION_TARGET).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_PERM).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ZONEID).append("=") .append("?"); statementGetPermission = db.prepareStatement(query.toString()); // statementGetAll query = new StringBuilder("SELECT ").append(COLUMN_PERMISSION_ALLOWED) .append(" FROM ").append(TABLE_PERMISSION) .append(" WHERE ").append(COLUMN_PERMISSION_TARGET).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_PERM).append("=").append("'" + Permission.ALL + "'") .append(" AND ").append(COLUMN_PERMISSION_ZONEID).append("=").append("?"); statementGetAll = db.prepareStatement(query.toString()); query = new StringBuilder("SELECT ").append(COLUMN_PERMISSION_ALLOWED).append(" FROM ").append(TABLE_PERMISSION).append(" WHERE ") .append(COLUMN_PERMISSION_TARGET).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_PERM).append(" LIKE ").append("?").append(" AND ").append(COLUMN_PERMISSION_ZONEID) .append("=").append("?"); statementGetPermissionForward = db.prepareStatement(query.toString()); // statementUpdatePermission query = new StringBuilder("UPDATE ").append(TABLE_PERMISSION).append(" SET ").append(COLUMN_PERMISSION_ALLOWED).append("=").append("?") .append(" WHERE ").append(COLUMN_PERMISSION_TARGET).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=") .append("?").append(" AND ").append(COLUMN_PERMISSION_PERM).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ZONEID) .append("=").append("?"); statementUpdatePermission = db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Helper Get Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // statementGetLadderFromID query = new StringBuilder("SELECT ").append(COLUMN_LADDER_NAME_NAME) .append(" FROM ").append(TABLE_LADDER_NAME) .append(" WHERE ").append(COLUMN_LADDER_NAME_LADDERID).append("=").append("?"); statementGetLadderNameFromID = db.prepareStatement(query.toString()); // statementGetLadderFromName query = new StringBuilder("SELECT ").append(COLUMN_LADDER_NAME_LADDERID) .append(" FROM ").append(TABLE_LADDER_NAME) .append(" WHERE ").append(COLUMN_LADDER_NAME_NAME).append("=").append("?"); statementGetLadderIDFromName = db.prepareStatement(query.toString()); // statementGetLadderFromGroup query = new StringBuilder("SELECT ").append(COLUMN_LADDER_LADDERID) .append(" FROM ").append(TABLE_LADDER) .append(" WHERE ").append(COLUMN_LADDER_GROUPID).append("=").append("?") .append(" AND ").append(COLUMN_LADDER_ZONEID).append("=").append("?"); statementGetLadderIDFromGroup = db.prepareStatement(query.toString()); // statementGetZoneFromID query = new StringBuilder("SELECT ").append(COLUMN_ZONE_NAME) .append(" FROM ").append(TABLE_ZONE) .append(" WHERE ").append(COLUMN_ZONE_ZONEID).append("=").append("?"); statementGetZoneNameFromID = db.prepareStatement(query.toString()); // statementGetZoneFromName query = new StringBuilder("SELECT ").append(COLUMN_ZONE_ZONEID) .append(" FROM ").append(TABLE_ZONE) .append(" WHERE ").append(COLUMN_ZONE_NAME).append("=").append("?"); statementGetZoneIDFromName = db.prepareStatement(query.toString()); // statementGetGroupFromID query = new StringBuilder("SELECT ").append(COLUMN_GROUP_NAME) .append(" FROM ").append(TABLE_GROUP) .append(" WHERE ").append(COLUMN_GROUP_GROUPID).append("=").append("?"); statementGetGroupNameFromID = db.prepareStatement(query.toString()); // statementGetGroupFromName query = new StringBuilder("SELECT *") // .append(COLUMN_GROUP_GROUPID) .append(" FROM ").append(TABLE_GROUP) .append(" WHERE ").append(COLUMN_GROUP_NAME).append("=").append("?"); statementGetGroupIDFromName = db.prepareStatement(query.toString()); // statementGetPlayerFromID query = new StringBuilder("SELECT ").append(COLUMN_PLAYER_USERNAME) .append(" FROM ").append(TABLE_PLAYER) .append(" WHERE ").append(COLUMN_PLAYER_PLAYERID).append("=").append("?"); statementGetPlayerNameFromID = db.prepareStatement(query.toString()); // statementGetPlayerFromName query = new StringBuilder("SELECT ").append(COLUMN_PLAYER_PLAYERID) .append(" FROM ").append(TABLE_PLAYER) .append(" WHERE ").append(COLUMN_PLAYER_USERNAME).append("=").append("?"); statementGetPlayerIDFromName = db.prepareStatement(query.toString()); // statementGetAllPermissions query = new StringBuilder("SELECT * FROM ").append(TABLE_PERMISSION) .append(" WHERE ").append(COLUMN_PERMISSION_TARGET).append("=").append("?") - .append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=").append("?") - .append(" AND ").append(COLUMN_PERMISSION_ZONEID).append("=").append("?"); + .append(" AND ").append(COLUMN_PERMISSION_ZONEID).append("=").append("?") + .append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=").append("?"); statementGetAllPermissions = db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Helper Put Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // statementPutZone query = new StringBuilder("INSERT INTO ").append(TABLE_ZONE).append(" (") .append(COLUMN_ZONE_NAME).append(") ") .append(" VALUES ").append(" (?) "); statementPutZone = db.prepareStatement(query.toString()); // statementPutPlayer query = new StringBuilder("INSERT INTO ").append(TABLE_PLAYER).append(" (") .append(COLUMN_PLAYER_USERNAME).append(") ") .append(" VALUES ").append(" (?) "); statementPutPlayer = db.prepareStatement(query.toString()); // statementPutLadderName query = new StringBuilder("INSERT INTO ").append(TABLE_LADDER_NAME).append(" (") .append(COLUMN_LADDER_NAME_NAME).append(") ") .append(" VALUES ").append(" (?) "); statementPutLadderName = db.prepareStatement(query.toString()); // statementPutLadder query = new StringBuilder("INSERT INTO ").append(TABLE_LADDER).append(" (") .append(COLUMN_LADDER_GROUPID).append(", ") .append(COLUMN_LADDER_ZONEID).append(", ") .append(COLUMN_LADDER_RANK).append(", ") .append(COLUMN_LADDER_LADDERID).append(") ") .append(" VALUES ").append(" (?, ?, ?, ?) "); statementPutLadder = db.prepareStatement(query.toString()); // statementPutGroup query = new StringBuilder("INSERT INTO ").append(TABLE_GROUP).append(" (").append(COLUMN_GROUP_NAME).append(", ").append(COLUMN_GROUP_PREFIX) .append(", ").append(COLUMN_GROUP_SUFFIX).append(", ").append(COLUMN_GROUP_PARENT).append(", ").append(COLUMN_GROUP_PRIORITY).append(", ") .append(COLUMN_GROUP_ZONE).append(") ").append(" VALUES ").append(" (?, ?, ?, ?, ?, ?) "); statementPutGroup = db.prepareStatement(query.toString()); // statementPutPermission query = new StringBuilder("INSERT INTO ").append(TABLE_PERMISSION).append(" (").append(COLUMN_PERMISSION_ALLOWED).append(", ") .append(COLUMN_PERMISSION_TARGET).append(", ").append(COLUMN_PERMISSION_ISGROUP).append(", ").append(COLUMN_PERMISSION_PERM).append(", ") .append(COLUMN_PERMISSION_ZONEID).append(") ").append(" VALUES ").append(" (?, ?, ?, ?, ?) "); statementPutPermission = db.prepareStatement(query.toString()); // statementPutPlayerInGroup query = new StringBuilder("INSERT INTO ").append(TABLE_GROUP_CONNECTOR).append(" (") .append(COLUMN_GROUP_CONNECTOR_GROUPID).append(", ") .append(COLUMN_GROUP_CONNECTOR_PLAYERID).append(", ") .append(COLUMN_GROUP_CONNECTOR_ZONEID).append(") ") .append(" VALUES ").append(" (?, ?, ?)"); statementPutPlayerInGroup = db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Helper Delete Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // statementDeletePermission query = new StringBuilder("DELETE FROM ").append(TABLE_PERMISSION).append(" WHERE ") .append(COLUMN_PERMISSION_TARGET).append("=").append("?").append(" AND ") .append(COLUMN_PERMISSION_ISGROUP).append("=").append("?").append(" AND ") .append(COLUMN_PERMISSION_PERM).append("=").append("?").append(" AND ") .append(COLUMN_PERMISSION_ZONEID).append("=").append("?"); statementDeletePermission = db.prepareStatement(query.toString()); // statementDeleteGroupInZone query = new StringBuilder("DELETE FROM ").append(TABLE_GROUP) .append(" WHERE ").append(COLUMN_GROUP_NAME).append("=").append("?").append(" AND ") .append(COLUMN_GROUP_ZONE).append("=").append("?"); statementDeleteGroupInZone = db.prepareStatement(query.toString()); // statementDelZone query = new StringBuilder("DELETE FROM ").append(TABLE_ZONE).append(" WHERE ") .append(COLUMN_ZONE_NAME).append("=").append("?"); statementDelZone = db.prepareStatement(query.toString()); // remove player from all groups in specified zone. used in /p user <player> group set query = new StringBuilder("DELETE FROM ").append(TABLE_GROUP_CONNECTOR).append(" WHERE ") .append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID) .append("=").append("?").append(" AND ").append(TABLE_GROUP_CONNECTOR).append(".") .append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementRemovePlayerGroups = instance.db.prepareStatement(query.toString()); // remove player from specified group in specified zone. used in /p user <player> group add query = new StringBuilder("DELETE FROM ").append(TABLE_GROUP_CONNECTOR) .append(" WHERE ").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?") .append(" AND ").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?") .append(" AND ").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append("?"); statementRemovePlayerGroup = instance.db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Helper ZONE Delete Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // delete groups from zone query = new StringBuilder("DELETE FROM ").append(TABLE_GROUP) .append(" WHERE ").append(COLUMN_GROUP_ZONE).append("=").append("?"); statementDelGroupFromZone = db.prepareStatement(query.toString()); // delete ladder from zone query = new StringBuilder("DELETE FROM ").append(TABLE_LADDER) .append(" WHERE ").append(COLUMN_LADDER_ZONEID).append("=").append("?"); statementDelLadderFromZone = db.prepareStatement(query.toString()); // delete group connectorsw from zone query = new StringBuilder("DELETE FROM ").append(TABLE_LADDER) .append(" WHERE ").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementDelGroupConnectorsFromZone = db.prepareStatement(query.toString()); // statementDeleteGroupInZone query = new StringBuilder("DELETE FROM ").append(TABLE_PERMISSION) .append(" WHERE ").append(COLUMN_PERMISSION_ZONEID).append("=").append("?"); statementDelPermFromZone = db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Dump Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // statementGetGroupFromID query = new StringBuilder("SELECT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_GROUP).append(".") .append(COLUMN_GROUP_PRIORITY).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ").append(TABLE_GROUP) .append(".").append(COLUMN_GROUP_SUFFIX).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PARENT).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(" FROM ").append(TABLE_GROUP).append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_ZONE).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID); statementDumpGroups = instance.db.prepareStatement(query.toString()); query = new StringBuilder("SELECT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_PERMISSION).append(".") .append(COLUMN_PERMISSION_PERM).append(", ").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ").append(TABLE_PERMISSION) .append(".").append(COLUMN_PERMISSION_ALLOWED).append(" FROM ").append(TABLE_PERMISSION).append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_PERMISSION).append(".").append(COLUMN_PERMISSION_TARGET).append("=").append(TABLE_GROUP).append(".") .append(COLUMN_GROUP_GROUPID).append(" INNER JOIN ").append(TABLE_ZONE).append(" ON ").append(TABLE_PERMISSION).append(".") .append(COLUMN_PERMISSION_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID); statementDumpGroupPermissions = instance.db.prepareStatement(query.toString()); query = (new StringBuilder("SELECT ")).append(TABLE_PLAYER).append(".").append(COLUMN_PLAYER_USERNAME).append(", ").append(TABLE_PERMISSION) .append(".").append(COLUMN_PERMISSION_PERM).append(", ").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_PERMISSION).append(".").append(COLUMN_PERMISSION_ALLOWED).append(" FROM ").append(TABLE_PERMISSION).append(" INNER JOIN ") .append(TABLE_PLAYER).append(" ON ").append(TABLE_PERMISSION).append(".").append(COLUMN_PERMISSION_TARGET).append("=").append(TABLE_PLAYER) .append(".").append(COLUMN_PLAYER_PLAYERID).append(" INNER JOIN ").append(TABLE_ZONE).append(" ON ").append(TABLE_PERMISSION).append(".") .append(COLUMN_PERMISSION_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID); statementDumpPlayerPermissions = instance.db.prepareStatement(query.toString()); query = new StringBuilder("SELECT ").append(COLUMN_PLAYER_USERNAME).append(" FROM ").append(TABLE_PLAYER); statementDumpPlayers = instance.db.prepareStatement(query.toString()); query = new StringBuilder("SELECT DISTINCT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_PLAYER) .append(".").append(COLUMN_PLAYER_USERNAME).append(", ").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(" FROM ") .append(TABLE_GROUP_CONNECTOR).append(" INNER JOIN ").append(TABLE_GROUP).append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".") .append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID).append(" INNER JOIN ") .append(TABLE_PLAYER).append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=") .append(TABLE_PLAYER).append(".").append(COLUMN_PLAYER_PLAYERID).append(" INNER JOIN ").append(TABLE_ZONE).append(" ON ") .append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".") .append(COLUMN_ZONE_ZONEID); statementDumpGroupConnector = instance.db.prepareStatement(query.toString()); query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_LADDER_NAME).append(".").append(COLUMN_LADDER_NAME_NAME).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME) .append(" FROM ").append(TABLE_LADDER) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_LADDER_NAME) .append(" ON ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_LADDERID).append("=").append(TABLE_LADDER_NAME).append(".").append(COLUMN_LADDER_NAME_LADDERID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID); statementDumpLadders = instance.db.prepareStatement(query.toString()); // remove specified group query = new StringBuilder(""); } catch (Exception e) { e.printStackTrace(); Throwables.propagate(e); // it may not get to this.. hopefully... throw new RuntimeException(e.getMessage()); } OutputHandler.SOP("Statement preparation successful"); } // --------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------- // ---------------------------------------INIT ---- METHODS ------------------------------------------ // --------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------- private void connect(DBConnector connector) { try { dbType = connector.getChosenType(); db = connector.getChosenConnection(); DatabaseMetaData meta = db.getMetaData(); ResultSet set = meta.getTables(null, null, null, new String[] { "TABLE" }); generate = true; while (set.next()) { if (set.getString("TABLE_NAME").equalsIgnoreCase(TABLE_PERMISSION)) { generate = false; continue; } } } catch (SQLException e) { OutputHandler.SOP("Unable to connect to the database!"); Throwables.propagate(e); } } // create tables. private void generate() { try { String zoneTable, groupTable, ladderTable, ladderNameTable, playerTable, groupConnectorTable, permissionTable; // ------------------ // H2 & MYSQL // ------------------ zoneTable = (new StringBuilder("CREATE TABLE IF NOT EXISTS ")).append(TABLE_ZONE).append("(") .append(COLUMN_ZONE_ZONEID).append(" INTEGER AUTO_INCREMENT, ") .append(COLUMN_ZONE_NAME).append(" VARCHAR(40) NOT NULL UNIQUE, ") .append("PRIMARY KEY (").append(COLUMN_ZONE_ZONEID).append(") ") .append(")").toString(); groupTable = (new StringBuilder("CREATE TABLE IF NOT EXISTS ")).append(TABLE_GROUP).append("(") .append(COLUMN_GROUP_GROUPID).append(" INTEGER AUTO_INCREMENT, ") .append(COLUMN_GROUP_NAME).append(" VARCHAR(40) NOT NULL UNIQUE, ") .append(COLUMN_GROUP_PARENT).append(" INTEGER, ") .append(COLUMN_GROUP_PRIORITY).append(" SMALLINT NOT NULL, ") .append(COLUMN_GROUP_ZONE).append(" INTEGER NOT NULL, ") .append(COLUMN_GROUP_PREFIX).append(" VARCHAR(20) DEFAULT '', ") .append(COLUMN_GROUP_SUFFIX).append(" VARCHAR(20) DEFAULT '', ") .append("PRIMARY KEY (").append(COLUMN_GROUP_GROUPID).append(") ") .append(") ").toString(); ladderTable = (new StringBuilder("CREATE TABLE IF NOT EXISTS ")).append(TABLE_LADDER).append("(") .append(COLUMN_LADDER_LADDERID).append(" INTEGER NOT NULL, ") .append(COLUMN_LADDER_GROUPID).append(" INTEGER NOT NULL, ") .append(COLUMN_LADDER_ZONEID).append(" INTEGER NOT NULL, ") .append(COLUMN_LADDER_RANK).append(" SMALLINT NOT NULL") .append(") ").toString(); ladderNameTable = (new StringBuilder("CREATE TABLE IF NOT EXISTS ")).append(TABLE_LADDER_NAME).append("(") .append(COLUMN_LADDER_NAME_LADDERID).append(" INTEGER AUTO_INCREMENT, ") .append(COLUMN_LADDER_NAME_NAME).append(" VARCHAR(40) NOT NULL UNIQUE, ") .append("PRIMARY KEY (").append(COLUMN_LADDER_NAME_LADDERID).append(") ") .append(")").toString(); playerTable = (new StringBuilder("CREATE TABLE IF NOT EXISTS ")).append(TABLE_PLAYER).append("(") .append(COLUMN_PLAYER_PLAYERID).append(" INTEGER AUTO_INCREMENT, ") .append(COLUMN_PLAYER_USERNAME).append(" VARCHAR(20) NOT NULL UNIQUE, ") .append("PRIMARY KEY (").append(COLUMN_PLAYER_PLAYERID).append(") ") .append(")").toString(); groupConnectorTable = (new StringBuilder("CREATE TABLE IF NOT EXISTS ")).append(TABLE_GROUP_CONNECTOR).append("(") .append(COLUMN_GROUP_CONNECTOR_GROUPID).append(" INTEGER NOT NULL, ") .append(COLUMN_GROUP_CONNECTOR_PLAYERID).append(" INTEGER NOT NULL, ") .append(COLUMN_GROUP_CONNECTOR_ZONEID).append(" INTEGER NOT NULL") .append(")").toString(); permissionTable = (new StringBuilder("CREATE TABLE IF NOT EXISTS ")).append(TABLE_PERMISSION).append("(") .append(COLUMN_PERMISSION_TARGET).append(" INTEGER NOT NULL, ") .append(COLUMN_PERMISSION_ISGROUP).append(" TINYINT(1) NOT NULL, ") .append(COLUMN_PERMISSION_PERM).append(" TEXT NOT NULL, ") .append(COLUMN_PERMISSION_ALLOWED).append(" TINYINT(1) NOT NULL, ") .append(COLUMN_PERMISSION_ZONEID).append(" INTEGER NOT NULL") .append(")").toString(); // create the tables. db.createStatement().executeUpdate(zoneTable); db.createStatement().executeUpdate(groupTable); db.createStatement().executeUpdate(ladderTable); db.createStatement().executeUpdate(ladderNameTable); db.createStatement().executeUpdate(playerTable); db.createStatement().executeUpdate(groupConnectorTable); db.createStatement().executeUpdate(permissionTable); // DEFAULT group StringBuilder query = new StringBuilder("INSERT INTO ").append(TABLE_GROUP).append(" (") .append(COLUMN_GROUP_GROUPID).append(", ") .append(COLUMN_GROUP_NAME).append(", ") .append(COLUMN_GROUP_PRIORITY).append(", ") .append(COLUMN_GROUP_ZONE).append(") ") .append(" VALUES ").append(" (") .append("-1, ") // groupID .append("'").append(PermissionsAPI.getDEFAULT().name).append("', ") .append("0, 0)"); // priority, zone db.createStatement().executeUpdate(query.toString()); // zones arent touched when importing... // GLOBAL zone query = new StringBuilder("INSERT INTO ").append(TABLE_ZONE).append(" (") .append(COLUMN_ZONE_NAME).append(", ") .append(COLUMN_ZONE_ZONEID).append(") ") .append(" VALUES ").append(" ('") .append(ZoneManager.getGLOBAL().getZoneName()).append("', 0) "); db.createStatement().executeUpdate(query.toString()); // SUPER zone query = new StringBuilder("INSERT INTO ").append(TABLE_ZONE).append(" (") .append(COLUMN_ZONE_NAME).append(", ") .append(COLUMN_ZONE_ZONEID).append(") ") .append(" VALUES ").append(" ('") .append(ZoneManager.getSUPER().getZoneName()).append("', -1) "); db.createStatement().executeUpdate(query.toString()); // Entry player... query = new StringBuilder("INSERT INTO ").append(TABLE_PLAYER).append(" (") .append(COLUMN_PLAYER_USERNAME).append(", ") .append(COLUMN_PLAYER_PLAYERID).append(") ") .append(" VALUES ").append(" ('") .append(PermissionsAPI.getEntryPlayer()).append("', 0) "); db.createStatement().executeUpdate(query.toString()); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } /** * If generation is enabled, puts the provided Registered permissions into the DB. * * @param map */ protected synchronized void putRegistrationperms(HashMap<RegGroup, HashSet<Permission>> map) { if (!generate) { return; } try { OutputHandler.SOP(" Inserting registration permissions into Permissions DB"); // make a statement to be used later.. just easier... PreparedStatement s; // create default groups... StringBuilder query = new StringBuilder("INSERT INTO ").append(TABLE_PERMISSION).append(" (").append(COLUMN_PERMISSION_TARGET).append(", ") .append(COLUMN_PERMISSION_ALLOWED).append(", ").append(COLUMN_PERMISSION_PERM).append(", ").append(COLUMN_PERMISSION_ISGROUP).append(", ") .append(COLUMN_PERMISSION_ZONEID).append(") ").append(" VALUES ").append(" (?, ?, ?, 1, 0) "); PreparedStatement statement = db.prepareStatement(query.toString()); // create groups... HashMap<RegGroup, Integer> groups = new HashMap<RegGroup, Integer>(); int NUM; for (RegGroup group : RegGroup.values()) { if (group.equals(RegGroup.ZONE)) { groups.put(group, -1); continue; } createGroup(group.getGroup()); NUM = getGroupIDFromGroupName(group.toString()); groups.put(group, NUM); } // register permissions for (Entry<RegGroup, HashSet<Permission>> entry : map.entrySet()) { statement.setInt(1, groups.get(entry.getKey())); for (Permission perm : entry.getValue()) { statement.setInt(2, perm.allowed ? 1 : 0); statement.setString(3, perm.name); statement.executeUpdate(); } } // put the EntryPlayer to GUESTS for the GLOBAL zone s = this.statementPutPlayerInGroup; s.setInt(1, groups.get(RegGroup.GUESTS)); s.setInt(2, 0); s.setInt(3, 0); s.executeUpdate(); s.clearParameters(); // make default ladder s = this.statementPutLadderName; s.setString(1, RegGroup.LADDER); s.executeUpdate(); s.clearParameters(); // add groups to ladder s = this.statementPutLadder; s.setInt(2, 0); // zone s.setInt(4, 1); // the ladderID { // Owner s.setInt(1, groups.get(RegGroup.OWNERS)); s.setInt(3, 1); s.executeUpdate(); // ZoneAdmin s.setInt(1, groups.get(RegGroup.ZONE_ADMINS)); s.setInt(3, 2); s.executeUpdate(); // Member s.setInt(1, groups.get(RegGroup.MEMBERS)); s.setInt(3, 3); s.executeUpdate(); // Guest s.setInt(1, groups.get(RegGroup.GUESTS)); s.setInt(3, 4); s.executeUpdate(); } s.clearParameters(); OutputHandler.SOP(" Registration permissions successfully inserted"); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } /** * "players" >> arraylist<String> DONE * "groups" >> arrayList<Group> DONE * "playerPerms" >> arrayList<permHolder> DONE * "groupPerms" >> arrayList<permHolder> DONE * "groupConnectors" >> HashMap<String, HashMap<String, String[]>> DONE * "ladders" >> arraylist<PromotionLadder> DONE */ protected void importPerms(String importDir) { try { File file = new File(ModulePermissions.permsFolder, importDir); OutputHandler.SOP("[PermSQL] Importing permissions from " + importDir); FlatFileGroups g = new FlatFileGroups(file); HashMap<String, Object> map = g.load(); FlatFilePlayers p = new FlatFilePlayers(file); map.put("players", p.load()); FlatFilePermissions pm = new FlatFilePermissions(file); map.putAll(pm.load()); OutputHandler.SOP("[PermSQL] Loaded Configs into ram"); // KILL ALL DE DATA!!!! db.createStatement().executeUpdate("TRUNCATE TABLE " + TABLE_PERMISSION); db.createStatement().executeUpdate("TRUNCATE TABLE " + TABLE_GROUP); db.createStatement().executeUpdate("TRUNCATE TABLE " + TABLE_PLAYER); db.createStatement().executeUpdate("TRUNCATE TABLE " + TABLE_LADDER); db.createStatement().executeUpdate("TRUNCATE TABLE " + TABLE_LADDER_NAME); db.createStatement().executeUpdate("TRUNCATE TABLE " + TABLE_GROUP_CONNECTOR); OutputHandler.SOP("[PermSQL] Cleaned tables of existing data"); // call generate to remake the stuff that should be there { // recreate EntryPlayer player this.statementPutPlayer.setString(1, PermissionsAPI.getEntryPlayer()); this.statementPutPlayer.executeUpdate(); this.statementPutPlayer.clearParameters(); // recreate DEFAULT group StringBuilder query = new StringBuilder("INSERT INTO ").append(TABLE_GROUP).append(" (") .append(COLUMN_GROUP_GROUPID).append(", ") .append(COLUMN_GROUP_NAME).append(", ") .append(COLUMN_GROUP_PRIORITY).append(", ") .append(COLUMN_GROUP_ZONE).append(") ") .append(" VALUES ").append(" (") .append("-1, ") // groupID .append("'").append(PermissionsAPI.getDEFAULT().name).append("', ") .append("0, 0)"); // priority, zone db.createStatement().executeUpdate(query.toString()); } // create players... PreparedStatement s = this.statementPutPlayer; for (String player : (ArrayList<String>) map.get("players")) { s.setString(1, player); s.executeUpdate(); } s.clearParameters(); OutputHandler.SOP("[PermSQL] Imported players"); // create groups s = instance.statementPutPlayerInGroup; HashMap<String, HashMap<String, String[]>> playerMap = (HashMap<String, HashMap<String, String[]>>) map.get("connector"); HashMap<String, String[]> temp; String[] list; for (Group group : (ArrayList<Group>) map.get("groups")) { if (group.name.equals(PermissionsAPI.getDEFAULT().name)) continue; createGroup(group); s.setInt(1, getGroupIDFromGroupName(group.name)); s.setInt(3, getZoneIDFromZoneName(group.zoneName)); temp = playerMap.get(group.zoneName); if (temp == null) continue; list = temp.get(group.name); if (list == null) continue; // add the players to the groups as well. for (String player : list) { s.setInt(2, getPlayerIDFromPlayerName(player)); s.executeUpdate(); } } OutputHandler.SOP("[PermSQL] Imported groups"); // add groups to ladders and stuff s = this.statementPutLadderName; PreparedStatement s2 = this.statementPutLadder; // groupID, zoneID, rank, ladderID for (PromotionLadder ladder : (ArrayList<PromotionLadder>) map.get("ladders")) { s.setString(1, ladder.name); s.executeUpdate(); s2.setInt(4, getLadderIDFromLadderName(ladder.name)); s2.setInt(2, getZoneIDFromZoneName(ladder.zoneID)); list = ladder.getListGroup(); for (int i = 0; i < list.length; i++) { s2.setInt(3, i); s2.setInt(1, getGroupIDFromGroupName(list[i])); s2.executeUpdate(); } } OutputHandler.SOP("[PermSQL] Imported ladders"); // now the permissions ArrayList<PermissionHolder> perms = (ArrayList<PermissionHolder>) map.get("playerPerms"); for (PermissionHolder perm : perms) setPermission(perm.target, false, perm, perm.zone); perms = (ArrayList<PermissionHolder>) map.get("groupPerms"); for (PermissionHolder perm : perms) setPermission(perm.target, true, perm, perm.zone); OutputHandler.SOP("[PermSQL] Imported permissions"); OutputHandler.SOP("[PermSQL] Import successful!"); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } // --------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------- // -------------------------------MAJOR ---- USAGE ---- METHODS -------------------------------------- // --------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------- /** * @param groupName * @param zoneName * @return NULL if no ladder in existence. */ protected static synchronized PromotionLadder getLadderForGroup(String group, String zone) { try { // get other vars int groupID = getGroupIDFromGroupName(group); int zoneID = getZoneIDFromZoneName(zone); int ladderID = getLadderIdFromGroup(groupID, zoneID); String ladderName = getLadderNameFromLadderID(ladderID); // setup query for List instance.statementGetLadderList.setInt(1, ladderID); instance.statementGetLadderList.setInt(2, zoneID); ResultSet set = instance.statementGetLadderList.executeQuery(); instance.statementGetLadderList.clearParameters(); ArrayList<String> list = new ArrayList<String>(); while (set.next()) { list.add(set.getString(0)); } PromotionLadder ladder = new PromotionLadder(ladderName, zone, list); return ladder; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * @param ladderName may be null * @param zoneName may be null * @param username may NOT be null * @return at worst an EmptySet */ public static TreeSet<Group> getGroupsForChat(String ladderName, String zoneName, String username) { TreeSet<Group> end = new TreeSet<Group>(); try { int lID, zID, pID; pID = getPlayerIDFromPlayerName(username); // for variations.. if (zoneName == null && ladderName == null) { lID = zID = -3; } else if (zoneName == null && ladderName != null) { lID = getLadderIDFromLadderName(ladderName); zID = -3; } else if (zoneName != null && ladderName == null) { lID = -3; zID = getZoneIDFromZoneName(zoneName); } else { lID = getLadderIDFromLadderName(ladderName); zID = getZoneIDFromZoneName(zoneName); } if (lID < -4 || zID < -4 || pID < -4) { OutputHandler.SOP("Ladder, Player, or Zone does not exist!"); return end; } ResultSet set; PreparedStatement s; if (lID == zID && lID == -3) s = instance.statementGetGroupsFromPlayer; else if (lID == -3) { s = instance.statementGetGroupsFromZone; s.setInt(2, zID); } else if (zID == -3) { s = instance.statementGetGroupsFromLadder; s.setInt(2, pID); } else { s = instance.statementGetGroupsFromLadderAndZone; s.setInt(2, lID); s.setInt(3, zID); } s.setInt(1, pID); set = s.executeQuery(); Group g; String prefix, suffix, name, zone; int priority; while (set.next()) { name = set.getString(1); prefix = set.getString(2); suffix = set.getString(3); zone = set.getString(4); priority = set.getInt(5); g = new Group(name, prefix, suffix, null, zone, priority); end.add(g); } } catch (SQLException e) { e.printStackTrace(); } return end; } /** * @param groupName * @return NULL if no group in existence. or an SQL error happened. */ protected static synchronized Group getGroupForName(String group) { try { if (group == null) return null; // setup query for List instance.statementGetGroupFromName.setString(1, group); ResultSet set = instance.statementGetGroupFromName.executeQuery(); instance.statementGetGroupFromName.clearParameters(); if (!set.next()) { return null; } int priority = set.getInt(COLUMN_GROUP_PRIORITY); String parent = getGroupNameFromGroupID(set.getInt(COLUMN_GROUP_PARENT)); String prefix = set.getString(COLUMN_GROUP_PREFIX); String suffix = set.getString(COLUMN_GROUP_SUFFIX); String zone = set.getString(COLUMN_ZONE_NAME); return new Group(group, prefix, suffix, parent, zone, priority); } catch (SQLException e) { e.printStackTrace(); } return null; } /** * @param groupID * @return NULL if no group in existence, or an SQL erorr happenend. TDOD: remove?? its unused... */ protected static synchronized Group getGroupForID(int group) { try { // setup query for List instance.statementGetGroupFromID.setInt(1, group); ResultSet set = instance.statementGetGroupFromID.executeQuery(); instance.statementGetGroupFromID.clearParameters(); if (!set.next()) { return null; } int priority = set.getInt(COLUMN_GROUP_PRIORITY); String name = set.getString(COLUMN_GROUP_NAME); String parent = getGroupNameFromGroupID(set.getInt(COLUMN_GROUP_PARENT)); String prefix = set.getString(COLUMN_GROUP_PREFIX); String suffix = set.getString(COLUMN_GROUP_SUFFIX); String zone = set.getString(COLUMN_ZONE_NAME); return new Group(name, prefix, suffix, parent, zone, priority); } catch (SQLException e) { e.printStackTrace(); } return null; } /** * groups are in order of priority. * * @param username * @param zone * @return NULL if SQL exception. Empty if in no groups. */ protected static synchronized ArrayList<Group> getGroupsForPlayer(String username, String zone) { try { TreeSet<Group> set = new TreeSet<Group>(); int pID = getPlayerIDFromPlayerName(username); int zID = getZoneIDFromZoneName(zone); instance.statementGetGroupsForPlayer.setInt(1, pID); instance.statementGetGroupsForPlayer.setInt(2, zID); ResultSet result = instance.statementGetGroupsForPlayer.executeQuery(); instance.statementGetGroupsForPlayer.clearParameters(); int priority; String name, parent, prefix, suffix; Group g; while (result.next()) { priority = result.getInt(COLUMN_GROUP_PRIORITY); name = result.getString(COLUMN_GROUP_NAME); parent = getGroupNameFromGroupID(result.getInt(COLUMN_GROUP_PARENT)); prefix = result.getString(COLUMN_GROUP_PREFIX); suffix = result.getString(COLUMN_GROUP_SUFFIX); g = new Group(name, prefix, suffix, parent, zone, priority); set.add(g); } ArrayList<Group> list = new ArrayList<Group>(); list.addAll(set); return list; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * @param g * @return FALSE if the group already exists, parent doesn't exist, zone doesn't exist, or if the INSERT failed. */ protected static synchronized boolean createGroup(Group g) { try { // check if group exists? if (getGroupIDFromGroupName(g.name) >= 0) { return false; // group exists } int parent = -5; int zone = getZoneIDFromZoneName(g.zoneName); if (g.parent != null) { parent = getGroupIDFromGroupName(g.parent); if (parent == -5) { return false; } } if (zone < -4) { return false; } // my query // $ name, prefix, suffix, parent, priority, zone instance.statementPutGroup.setString(1, g.name); instance.statementPutGroup.setString(2, g.prefix); instance.statementPutGroup.setString(3, g.suffix); if (parent == -5) { instance.statementPutGroup.setNull(4, java.sql.Types.INTEGER); } else { instance.statementPutGroup.setInt(4, parent); } instance.statementPutGroup.setInt(5, g.priority); instance.statementPutGroup.setInt(6, zone); instance.statementPutGroup.executeUpdate(); instance.statementPutGroup.clearParameters(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } /** * @param g * @return FALSE if the group already exists, parent doesn't exist, zone doesn't exist, or if the UPDATE failed. */ protected static synchronized boolean updateGroup(Group g) { try { // check if group exists? if (getGroupIDFromGroupName(g.name) < 0) { return false; // group doesn't exist } int parent = -5; int zone = getZoneIDFromZoneName(g.zoneName); if (g.parent != null) { parent = getGroupIDFromGroupName(g.parent); if (parent == -5) { return false; } } if (zone < -4) { return false; } // my query instance.statementUpdateGroup.setString(1, g.name); instance.statementUpdateGroup.setString(2, g.prefix); instance.statementUpdateGroup.setString(3, g.suffix); if (parent == -5) { instance.statementUpdateGroup.setNull(4, java.sql.Types.INTEGER); } else { instance.statementUpdateGroup.setInt(4, parent); } instance.statementUpdateGroup.setInt(5, g.priority); instance.statementUpdateGroup.setInt(6, zone); instance.statementUpdateGroup.setString(7, g.name); instance.statementUpdateGroup.setInt(8, zone); instance.statementUpdateGroup.executeUpdate(); instance.statementUpdateGroup.clearParameters(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } /** * @param target (username or groupname) * @param isGroup * @param perm * @return ALLOW/DENY if the permission is allowed/denied. UNKNOWN if its not found. */ protected static synchronized PermResult getAllResult(String target, boolean isGroup, String zone, boolean checkForward) { try { int tID; int zID = getZoneIDFromZoneName(zone); int isG = isGroup ? 1 : 0; int allowed = -1; PreparedStatement statement = instance.statementGetAll; ResultSet set; if (isGroup) tID = getGroupIDFromGroupName(target); else tID = getPlayerIDFromPlayerName(target); if (zID < -4 || tID < -4) return PermResult.UNKNOWN; // initial check. statement.setInt(1, tID); statement.setInt(2, isG); statement.setInt(3, zID); set = statement.executeQuery(); statement.clearParameters(); if (set.next()) return set.getBoolean(1) ? PermResult.ALLOW : PermResult.ALLOW; else return PermResult.UNKNOWN; } catch (SQLException e) { e.printStackTrace(); } return PermResult.UNKNOWN; } /** * @param target * (username or groupname) * @param isGroup * @param perm * @return ALLOW/DENY if the permission or a parent is allowed/denied. UNKNOWN if nor it or any parents were not found. UNKNOWN also if the target or the * zone do not exist. */ protected static synchronized PermResult getPermissionResult(String target, boolean isGroup, PermissionChecker perm, String zone, boolean checkForward) { try { int tID; int zID = getZoneIDFromZoneName(zone); int isG = isGroup ? 1 : 0; int allowed = -1; PreparedStatement statement = instance.statementGetPermission; ResultSet set; if (isGroup) { tID = getGroupIDFromGroupName(target); } else { tID = getPlayerIDFromPlayerName(target); } if (zID < -4 || tID < -4) { return PermResult.UNKNOWN; } // initial check. statement.setInt(1, tID); statement.setInt(2, isG); statement.setString(3, perm.name); statement.setInt(4, zID); set = statement.executeQuery(); statement.clearParameters(); PermResult initial = PermResult.UNKNOWN; if (set.next()) { return set.getInt(1) > 0 ? PermResult.ALLOW : PermResult.DENY; } // if the stuff is FORWARD! // TODO: fix. /* * if (checkForward) * { * statement = instance.statementGetPermissionForward; * // target, isgroup, perm, zone >> allowed * statement.setInt(1, tID); * statement.setInt(2, isG); * statement.setString(3, perm.name + ".%"); * statement.setInt(4, zID); * set = statement.executeQuery(); * statement.clearParameters(); * boolean allow = false; * boolean deny = false; * switch (initial) * { * case ALLOW: * allow = true; * break; * case DENY: * deny = true; * break; * } * while (set.next()) * { * allowed = set.getInt(1); // allowed.. only 1 column. * if (allowed == 0) * { * deny = true; * } * else * { * allow = true; * } * if (allow && deny) * { * instance.statementGetPermission.clearParameters(); * return PermResult.PARTIAL; * } * } * if (allowed > -1) * { * instance.statementGetPermission.clearParameters(); * if (allow && !deny) * { * return PermResult.DENY; * } * } * statement = instance.statementGetPermission; * } */ if (!initial.equals(PermResult.UNKNOWN)) { instance.statementGetPermission.clearParameters(); return initial; } // normal checking of the parents now while (perm != null) { // params still set from initial statement.setInt(1, tID); statement.setInt(2, isG); statement.setString(3, perm.name); statement.setInt(4, zID); set = statement.executeQuery(); statement.clearParameters(); if (set.next()) { allowed = set.getInt(1); // allowed.. only 1 column. return allowed > 0 ? PermResult.ALLOW : PermResult.DENY; } if (!perm.hasParent()) { perm = null; } else { perm = new PermissionChecker(perm.getAllParent()); } } } catch (SQLException e) { e.printStackTrace(); } return PermResult.UNKNOWN; } /** * Creates the permission if it doesn't exist.. updates it if it does. * * @param target * @param isGroup * @param perm * @param zone * @return FALSE if the group, or zone do not exist. */ protected static synchronized boolean setPermission(String target, boolean isGroup, Permission perm, String zone) { try { int tID; int zID = getZoneIDFromZoneName(zone); int isG = isGroup ? 1 : 0; int allowed = perm.allowed ? 1 : 0; if (isGroup) { tID = getGroupIDFromGroupName(target); } else { tID = getPlayerIDFromPlayerName(target); } if (zID < -4 || tID < -4) { return false; } PreparedStatement use; // check permission existence... instance.statementGetPermission.setInt(1, tID); instance.statementGetPermission.setInt(2, isG); instance.statementGetPermission.setString(3, perm.name); instance.statementGetPermission.setInt(4, zID); ResultSet set = instance.statementGetPermission.executeQuery(); instance.statementGetPermission.clearParameters(); // allowed, target, isgroup, perm, zone if (set.next()) { use = instance.statementUpdatePermission; // exists } else { use = instance.statementPutPermission; // does not exist. } use.setInt(1, allowed); use.setInt(2, tID); use.setInt(3, isG); use.setString(4, perm.name); use.setInt(5, zID); use.executeUpdate(); use.clearParameters(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } protected static synchronized boolean delZone(String name) { try { int zid = getZoneIDFromZoneName(name); if (zid == -5) return false; instance.statementDelZone.setString(1, name); instance.statementDelZone.executeUpdate(); instance.statementDelZone.clearParameters(); instance.statementDelGroupFromZone.setInt(1, zid); instance.statementDelGroupFromZone.executeUpdate(); instance.statementDelGroupFromZone.clearParameters(); instance.statementDelGroupConnectorsFromZone.setInt(1, zid); instance.statementDelGroupConnectorsFromZone.executeUpdate(); instance.statementDelGroupConnectorsFromZone.clearParameters(); instance.statementDelLadderFromZone.setInt(1, zid); instance.statementDelLadderFromZone.executeUpdate(); instance.statementDelLadderFromZone.clearParameters(); instance.statementDelPermFromZone.setInt(1, zid); instance.statementDelPermFromZone.executeUpdate(); instance.statementDelPermFromZone.clearParameters(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } protected static synchronized boolean createZone(String name) { try { instance.statementPutZone.setString(1, name); instance.statementPutZone.executeUpdate(); instance.statementPutZone.clearParameters(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } protected static synchronized boolean doesZoneExist(String name) { try { int ID = getZoneIDFromZoneName(name); return ID > 0; } catch (SQLException e) { e.printStackTrace(); return false; } } /** * queries the entire DB and make it into nonDB format.. * * @return * "players" >> arraylist<String> DONE * "groups" >> arrayList<Group> DONE * "playerPerms" >> arrayList<permHolder> DONE * "groupPerms" >> arrayList<permHolder> DONE * "groupConnectors" >> HashMap<String, HashMap<String, ArrayList<String>>> DONE * "ladders" >> arraylist<PromotionLadder> DONE */ protected static synchronized HashMap<String, Object> dump() { HashMap<String, Object> map = new HashMap<String, Object>(); ResultSet set; ArrayList list; // DUMP PLAYERS! --------------------------------- try { set = instance.statementDumpPlayers.executeQuery(); list = new ArrayList<String>(); while (set.next()) { list.add(set.getString(1)); } map.put("players", list); } catch (SQLException e) { OutputHandler.SOP("[PermSQL] Player dump for export failed!"); e.printStackTrace(); list = null; } // DUMP GROUPS! ------------------------------------- try { set = instance.statementDumpGroups.executeQuery(); list = new ArrayList<Group>(); int priority; String parent, prefix, suffix, zone, name; int parentID; Group g; while (set.next()) { priority = set.getInt(COLUMN_GROUP_PRIORITY); name = set.getString(COLUMN_GROUP_NAME); parentID = set.getInt(COLUMN_GROUP_PARENT); prefix = set.getString(COLUMN_GROUP_PREFIX); suffix = set.getString(COLUMN_GROUP_SUFFIX); zone = set.getString(COLUMN_ZONE_NAME); parent = getGroupNameFromGroupID(parentID); g = new Group(name, prefix, suffix, parent, zone, priority); list.add(g); } map.put("groups", list); } catch (SQLException e) { OutputHandler.SOP("[PermSQL] Group dump for export failed!"); e.printStackTrace(); list = null; } // DUMP PLAYER PERMISSIONS! ------------------------------ try { set = instance.statementDumpPlayerPermissions.executeQuery(); list = new ArrayList<PermissionHolder>(); boolean allowed; String target, zone, perm; PermissionHolder holder; while (set.next()) { target = set.getString(COLUMN_PLAYER_USERNAME); zone = set.getString(COLUMN_ZONE_NAME); perm = set.getString(COLUMN_PERMISSION_PERM); allowed = set.getBoolean(COLUMN_PERMISSION_ALLOWED); holder = new PermissionHolder(target, perm, allowed, zone); list.add(holder); } map.put("playerPerms", list); } catch (SQLException e) { OutputHandler.SOP("[PermSQL] Player Permission dump for export failed!"); e.printStackTrace(); list = null; } // DUMP GROUP PERMISSIONS! ------------------------------ try { set = instance.statementDumpGroupPermissions.executeQuery(); list = new ArrayList<PermissionHolder>(); boolean allowed; String target, zone, perm; PermissionHolder holder; while (set.next()) { target = set.getString(COLUMN_GROUP_NAME); zone = set.getString(COLUMN_ZONE_NAME); perm = set.getString(COLUMN_PERMISSION_PERM); allowed = set.getBoolean(COLUMN_PERMISSION_ALLOWED); holder = new PermissionHolder(target, perm, allowed, zone); list.add(holder); } map.put("groupPerms", list); } catch (SQLException e) { OutputHandler.SOP("[PermSQL] Group Permission dump for export failed!"); e.printStackTrace(); list = null; } // DUMP GROUP CONNECTORS! ------------------------------ try { set = instance.statementDumpGroupConnector.executeQuery(); HashMap<String, HashMap<String, ArrayList<String>>> uberMap = new HashMap<String, HashMap<String, ArrayList<String>>>(); String group, zone, player; HashMap<String, ArrayList<String>> gMap; while (set.next()) { group = set.getString(COLUMN_GROUP_NAME); zone = set.getString(COLUMN_ZONE_NAME); player = set.getString(COLUMN_PLAYER_USERNAME); gMap = uberMap.get(zone); if (gMap == null) { gMap = new HashMap<String, ArrayList<String>>(); uberMap.put(zone, gMap); } list = gMap.get(group); if (list == null) { list = new ArrayList<String>(); gMap.put(group, list); } list.add(player); } map.put("groupConnectors", uberMap); } catch (SQLException e) { OutputHandler.SOP("[PermSQL] Group Connection dump for export failed!"); e.printStackTrace(); list = null; } // DUMP LADDERS! ------------------------------ try { set = instance.statementDumpLadders.executeQuery(); // zone, ladder, groupnames HashMap<String, HashMap<String, ArrayList<String>>> uberMap = new HashMap<String, HashMap<String, ArrayList<String>>>(); String ladder, zone, group; HashMap<String, ArrayList<String>> gMap; while (set.next()) { ladder = set.getString(COLUMN_LADDER_NAME_NAME); zone = set.getString(COLUMN_ZONE_NAME); group = set.getString(COLUMN_GROUP_NAME); gMap = uberMap.get(zone); if (gMap == null) { gMap = new HashMap<String, ArrayList<String>>(); uberMap.put(zone, gMap); } list = gMap.get(ladder); if (list == null) { list = new ArrayList<String>(); gMap.put(ladder, list); } list.add(group); } list = new ArrayList<PromotionLadder>(); PromotionLadder lad; String[] holder = new String[] {}; for (Entry<String, HashMap<String, ArrayList<String>>> entry1 : uberMap.entrySet()) { for (Entry<String, ArrayList<String>> entry2 : entry1.getValue().entrySet()) { if (entry2.getValue().isEmpty()) { continue; } lad = new PromotionLadder(entry2.getKey(), entry1.getKey(), entry2.getValue().toArray(holder)); list.add(lad); } } map.put("ladders", list); } catch (SQLException e) { OutputHandler.SOP("[PermSQL] Ladder dump for export failed!"); e.printStackTrace(); list = null; } return map; } /** * @param username * @return FALSE if player was not generated or SQL error. */ public static synchronized boolean generatePlayer(String username) { try { boolean generate = false; int pid = getPlayerIDFromPlayerName(username); if (pid == -5) { // generate players generate = true; instance.statementPutPlayer.setString(1, username); instance.statementPutPlayer.executeUpdate(); instance.statementPutPlayer.clearParameters(); pid = getPlayerIDFromPlayerName(username); } if (generate) { // get groups list... ArrayList<Integer> groups = new ArrayList<Integer>(); ResultSet set; instance.statementGetGroupIDsForEntryPlayer.setInt(1, 0); // global set = instance.statementGetGroupIDsForEntryPlayer.executeQuery(); instance.statementGetGroupIDsForEntryPlayer.clearParameters(); while (set.next()) groups.add(set.getInt(1)); instance.statementPutPlayerInGroup.setInt(2, pid); // player instance.statementPutPlayerInGroup.setInt(3, 0); // zone for (int num : groups) { instance.statementPutPlayerInGroup.setInt(1, num); instance.statementPutPlayerInGroup.executeUpdate(); } instance.statementPutPlayerInGroup.clearParameters(); return true; } } catch (SQLException e) { e.printStackTrace(); return false; } return false; } // --------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------- // -------------------------------ID <<>> NAME METHODS ----------------------------------------------- // --------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------- /** * @param zone * @return -5 if the Zone does not exist. * @throws SQLException */ private static synchronized int getZoneIDFromZoneName(String zone) throws SQLException { if (zone.equalsIgnoreCase(ZoneManager.getGLOBAL().getZoneName())) return 0; instance.statementGetZoneIDFromName.setString(1, zone); ResultSet set = instance.statementGetZoneIDFromName.executeQuery(); instance.statementGetZoneIDFromName.clearParameters(); if (!set.next()) { return -5; } return set.getInt(1); } /** * @param zoneID * @return null if the Zone does not exist. * @throws SQLException */ private static synchronized String getZoneNameFromZoneID(int zoneID) throws SQLException { instance.statementGetZoneNameFromID.setInt(1, zoneID); ResultSet set = instance.statementGetZoneNameFromID.executeQuery(); instance.statementGetZoneNameFromID.clearParameters(); if (!set.next()) { return null; } return set.getString(1); } /** * @param ladder * @return -5 if the Ladder does not exist. * @throws SQLException */ private static synchronized int getLadderIDFromLadderName(String ladder) throws SQLException { instance.statementGetLadderIDFromName.setString(1, ladder); ResultSet set = instance.statementGetLadderIDFromName.executeQuery(); instance.statementGetLadderIDFromName.clearParameters(); if (!set.next()) { return -5; } return set.getInt(1); } /** * @param ladderID * @return null if the Ladder does not exist. * @throws SQLException */ private static synchronized String getLadderNameFromLadderID(int ladderID) throws SQLException { instance.statementGetLadderNameFromID.setInt(1, ladderID); ResultSet set = instance.statementGetLadderNameFromID.executeQuery(); instance.statementGetLadderNameFromID.clearParameters(); if (!set.next()) { return null; } return set.getString(1); } /** * @param ladderID * @return null if the Ladder does not exist. * @throws SQLException */ private static synchronized int getLadderIdFromGroup(int groupID, int zoneID) throws SQLException { instance.statementGetLadderIDFromGroup.setInt(1, groupID); instance.statementGetLadderIDFromGroup.setInt(2, zoneID); ResultSet set = instance.statementGetLadderIDFromGroup.executeQuery(); instance.statementGetLadderIDFromGroup.clearParameters(); if (!set.next()) { return -5; } return set.getInt(1); } /** * @param group * @return -5 if the Group does not exist. * @throws SQLException */ private static synchronized int getGroupIDFromGroupName(String group) throws SQLException { if (group.equals(PermissionsAPI.getDEFAULT().name)) return -1; instance.statementGetGroupIDFromName.setString(1, group); ResultSet set = instance.statementGetGroupIDFromName.executeQuery(); instance.statementGetGroupIDFromName.clearParameters(); if (!set.next()) { return -5; } return set.getInt(1); } /** * @param groupID * @return null if the Group does not exist. * @throws SQLException */ private static synchronized String getGroupNameFromGroupID(int groupID) throws SQLException { instance.statementGetGroupNameFromID.setInt(1, groupID); ResultSet set = instance.statementGetGroupNameFromID.executeQuery(); instance.statementGetGroupNameFromID.clearParameters(); if (!set.next()) { return null; } return set.getString(1); } /** * @param player * @return returns -5 if the player doesn't exist. * @throws SQLException */ private static synchronized int getPlayerIDFromPlayerName(String player) throws SQLException { instance.statementGetPlayerIDFromName.setString(1, player); ResultSet set = instance.statementGetPlayerIDFromName.executeQuery(); instance.statementGetPlayerIDFromName.clearParameters(); if (!set.next()) return -5; return set.getInt(1); } /** * @param playerID * @return null if the Player does not exist. * @throws SQLException */ private static synchronized String getPlayerNameFromPlayerID(int playerID) throws SQLException { instance.statementGetPlayerNameFromID.setInt(1, playerID); ResultSet set = instance.statementGetPlayerNameFromID.executeQuery(); instance.statementGetPlayerNameFromID.clearParameters(); if (!set.next()) { return null; } return set.getString(1); } private static synchronized void clearPlayerGroupsInZone(int playerID, int zoneID) throws SQLException { instance.statementRemovePlayerGroups.setInt(1, playerID); instance.statementRemovePlayerGroups.setInt(2, zoneID); instance.statementRemovePlayerGroups.executeUpdate(); instance.statementRemovePlayerGroups.clearParameters(); } public static synchronized String setPlayerGroup(String group, String player, String zone) { try { int playerID = instance.getPlayerIDFromPlayerName(player); int groupID = instance.getGroupIDFromGroupName(group); int zoneID = instance.getZoneIDFromZoneName(zone); clearPlayerGroupsInZone(playerID, zoneID); return addPlayerGroup(groupID, playerID, zoneID); } catch (SQLException e) { e.printStackTrace(); } return "Player group not set."; } public static synchronized String addPlayerGroup(String group, String player, String zone) { try { int playerID = getPlayerIDFromPlayerName(player); int groupID = getGroupIDFromGroupName(group); int zoneID = getZoneIDFromZoneName(zone); return addPlayerGroup(groupID, playerID, zoneID); } catch (SQLException e) { e.printStackTrace(); } return "Player not added to group."; } private static synchronized String addPlayerGroup(int groupID, int playerID, int zoneID) throws SQLException { instance.statementPutPlayerInGroup.setInt(1, groupID); instance.statementPutPlayerInGroup.setInt(2, playerID); instance.statementPutPlayerInGroup.setInt(3, zoneID); int result = instance.statementPutPlayerInGroup.executeUpdate(); instance.statementPutPlayerInGroup.clearParameters(); if (result == 0) { return "Row not inserted."; } return null; } public static synchronized String removePlayerGroup(String group, String player, String zone) { try { int playerID = getPlayerIDFromPlayerName(player); int groupID = getGroupIDFromGroupName(group); int zoneID = getZoneIDFromZoneName(zone); return removePlayerGroup(groupID, playerID, zoneID); } catch (SQLException e) { e.printStackTrace(); } return "Player not added to group"; } private static synchronized String removePlayerGroup(int groupID, int playerID, int zoneID) throws SQLException { instance.statementRemovePlayerGroup.setInt(1, playerID); instance.statementRemovePlayerGroup.setInt(2, zoneID); instance.statementRemovePlayerGroup.setInt(3, groupID); int result = instance.statementRemovePlayerGroup.executeUpdate(); instance.statementRemovePlayerGroup.clearParameters(); if (result == 0) { return "Player not removed from group."; } return null; } public static synchronized String removePermission(String target, boolean isGroup, String node, String zone) { try { int playerID = instance.getPlayerIDFromPlayerName(target); int zoneID = instance.getZoneIDFromZoneName(zone); return removePermission(playerID, isGroup, node, zoneID); } catch (SQLException e) { e.printStackTrace(); } return "Player group not set."; } public static synchronized String removePermission(int playerID, boolean isGroup, String node, int zoneID) throws SQLException { instance.statementDeletePermission.setInt(1, playerID); instance.statementDeletePermission.setBoolean(2, isGroup); instance.statementDeletePermission.setString(3, node); instance.statementDeletePermission.setInt(4, zoneID); instance.statementDeletePermission.executeUpdate(); instance.statementDeletePermission.clearParameters(); return null; } public static synchronized void deleteGroupInZone(String group, String zone) { try { int zoneID = getZoneIDFromZoneName(zone); instance.statementDeleteGroupInZone.setString(1, group); instance.statementDeleteGroupInZone.setInt(2, zoneID); instance.statementDeleteGroupInZone.executeUpdate(); instance.statementDeleteGroupInZone.clearParameters(); } catch (SQLException e) { e.printStackTrace(); } } public static synchronized ArrayList getGroupsInZone(String zoneName) { try { TreeSet<Group> set = new TreeSet<Group>(); int zID = getZoneIDFromZoneName(zoneName); instance.statementGetGroupsInZone.setInt(1, zID); ResultSet result = instance.statementGetGroupsInZone.executeQuery(); instance.statementGetGroupsInZone.clearParameters(); int priority; String name, parent, prefix, suffix; Group g; while (result.next()) { priority = result.getInt(COLUMN_GROUP_PRIORITY); name = result.getString(COLUMN_GROUP_NAME); parent = result.getString(COLUMN_GROUP_PARENT); prefix = result.getString(COLUMN_GROUP_PREFIX); suffix = result.getString(COLUMN_GROUP_SUFFIX); g = new Group(name, prefix, suffix, parent, zoneName, priority); set.add(g); } ArrayList<Group> list = new ArrayList<Group>(); list.addAll(set); return list; } catch (SQLException e) { e.printStackTrace(); } return null; } public static String getPermission(String target, boolean isGroup, String perm, String zone) { try { int tID; int zID = getZoneIDFromZoneName(zone); int isG = isGroup ? 1 : 0; int allowed = -1; PreparedStatement statement = instance.statementGetPermission; ResultSet set; if (isGroup) { tID = getGroupIDFromGroupName(target); } else { tID = getPlayerIDFromPlayerName(target); } if (zID < -4 || tID < -4) { return "Zone or target invalid."; } // initial check. statement.setInt(1, tID); statement.setInt(2, isG); statement.setString(3, perm); statement.setInt(4, zID); set = statement.executeQuery(); statement.clearParameters(); PermResult initial = PermResult.UNKNOWN; if (set.next()) { return set.getInt(COLUMN_PERMISSION_ALLOWED) == 1 ? "allowed" : "denied"; } } catch (SQLException e) { e.printStackTrace(); } return null; } public static ArrayList getAllPermissions(String target, String zone, int isGroup) { ArrayList list = new ArrayList(); PreparedStatement statement = instance.statementGetAllPermissions; try { int targetID = (isGroup == 1 ? getGroupIDFromGroupName(target) : getPlayerIDFromPlayerName(target)); if(targetID == -5) { list.add("ERROR"); list.add((isGroup == 1 ? "Group " : "Player ") + target + " does not exist."); return list; } int zoneID = getZoneIDFromZoneName(zone); if(zoneID == -5) { list.add("ERROR"); list.add("Zone " + zone + " does not exist."); return list; } ResultSet set; statement.setInt(1, targetID); statement.setInt(2, zoneID); statement.setInt(3, isGroup); set = statement.executeQuery(); statement.clearParameters(); while(set.next()) { list.add(set.getString(COLUMN_PERMISSION_PERM) + ":" + (set.getInt(COLUMN_PERMISSION_ALLOWED) == 1 ? "ALLOW" : "DENY")); } if(list.isEmpty()) { list.add(target + " has no individual permissions."); } return list; } catch (SQLException e) { e.printStackTrace(); } return null; } }
true
true
public SqlHelper(ConfigPermissions config) { instance = this; connect(config.connector); if (generate) generate(); try { // statementGetLadderList StringBuilder query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_LADDER).append(".").append(COLUMN_LADDER_RANK) .append(" FROM ").append(TABLE_LADDER) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" WHERE ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_LADDERID).append("=").append("?") .append(" AND ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_ZONEID).append("=").append("?") .append(" ORDER BY ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_RANK); statementGetLadderList = instance.db.prepareStatement(query.toString()); // statementGetGroupsFromLadder query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_LADDER) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_GROUPID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?") .append(" AND ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_LADDERID).append("=").append("?"); statementGetGroupsFromLadder = instance.db.prepareStatement(query.toString()); // statementGetGroupsFromLadderAndZone query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_LADDER) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_GROUPID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?") .append(" AND ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_LADDERID).append("=").append("?") .append(" AND ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementGetGroupsFromLadderAndZone = instance.db.prepareStatement(query.toString()); // statementGetGroupsFromZone query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?") .append(" AND ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementGetGroupsFromZone = instance.db.prepareStatement(query.toString()); // statementGetGroupsFromZone query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?"); statementGetGroupsFromPlayer = instance.db.prepareStatement(query.toString()); // statementGetGroupFromName query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PARENT).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME) .append(" FROM ").append(TABLE_GROUP) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_ZONE).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append("=").append("?"); statementGetGroupFromName = instance.db.prepareStatement(query.toString()); // statementGetGroupFromID query = new StringBuilder("SELECT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_GROUP).append(".") .append(COLUMN_GROUP_PRIORITY).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ").append(TABLE_GROUP) .append(".").append(COLUMN_GROUP_SUFFIX).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PARENT).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(" FROM ").append(TABLE_GROUP).append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_ZONE).append("=").append(TABLE_ZONE).append(".") .append(COLUMN_ZONE_ZONEID).append(" WHERE ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID).append("=").append("?"); statementGetGroupFromID = instance.db.prepareStatement(query.toString()); // statementGetGroupsForPlayer query = new StringBuilder("SELECT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_GROUP).append(".") .append(COLUMN_GROUP_PRIORITY).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ").append(TABLE_GROUP) .append(".").append(COLUMN_GROUP_SUFFIX).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PARENT).append(" FROM ") .append(TABLE_GROUP_CONNECTOR).append(" INNER JOIN ").append(TABLE_GROUP).append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".") .append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID).append(" WHERE ") .append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?").append(" AND ") .append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementGetGroupsForPlayer = instance.db.prepareStatement(query.toString()); // statementGetGroupsInZone query = new StringBuilder("SELECT * FROM ").append(TABLE_GROUP).append(" WHERE ").append(COLUMN_GROUP_ZONE).append("=").append("?"); statementGetGroupsInZone = instance.db.prepareStatement(query.toString()); // statementGetGroupIDsForEntryPlayer query = new StringBuilder("SELECT ").append(COLUMN_GROUP_CONNECTOR_GROUPID) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" WHERE ").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append(0) .append(" AND ").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementGetGroupIDsForEntryPlayer = instance.db.prepareStatement(query.toString()); // statementUpdateGroup query = new StringBuilder("UPDATE ").append(TABLE_GROUP).append(" SET ").append(COLUMN_GROUP_NAME).append("=").append("?, ") .append(COLUMN_GROUP_PREFIX).append("=").append("?, ").append(COLUMN_GROUP_SUFFIX).append("=").append("?, ").append(COLUMN_GROUP_PARENT) .append("=").append("?, ").append(COLUMN_GROUP_PRIORITY).append("=").append("?, ").append(COLUMN_GROUP_ZONE).append("=").append("?") .append(" WHERE ").append(COLUMN_GROUP_NAME).append("=").append("?") .append(" AND ").append(COLUMN_GROUP_ZONE).append("=").append("?"); statementUpdateGroup = db.prepareStatement(query.toString()); // statementGetPermission query = new StringBuilder("SELECT ").append(COLUMN_PERMISSION_ALLOWED).append(" FROM ").append(TABLE_PERMISSION).append(" WHERE ") .append(COLUMN_PERMISSION_TARGET).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_PERM).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ZONEID).append("=") .append("?"); statementGetPermission = db.prepareStatement(query.toString()); // statementGetAll query = new StringBuilder("SELECT ").append(COLUMN_PERMISSION_ALLOWED) .append(" FROM ").append(TABLE_PERMISSION) .append(" WHERE ").append(COLUMN_PERMISSION_TARGET).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_PERM).append("=").append("'" + Permission.ALL + "'") .append(" AND ").append(COLUMN_PERMISSION_ZONEID).append("=").append("?"); statementGetAll = db.prepareStatement(query.toString()); query = new StringBuilder("SELECT ").append(COLUMN_PERMISSION_ALLOWED).append(" FROM ").append(TABLE_PERMISSION).append(" WHERE ") .append(COLUMN_PERMISSION_TARGET).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_PERM).append(" LIKE ").append("?").append(" AND ").append(COLUMN_PERMISSION_ZONEID) .append("=").append("?"); statementGetPermissionForward = db.prepareStatement(query.toString()); // statementUpdatePermission query = new StringBuilder("UPDATE ").append(TABLE_PERMISSION).append(" SET ").append(COLUMN_PERMISSION_ALLOWED).append("=").append("?") .append(" WHERE ").append(COLUMN_PERMISSION_TARGET).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=") .append("?").append(" AND ").append(COLUMN_PERMISSION_PERM).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ZONEID) .append("=").append("?"); statementUpdatePermission = db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Helper Get Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // statementGetLadderFromID query = new StringBuilder("SELECT ").append(COLUMN_LADDER_NAME_NAME) .append(" FROM ").append(TABLE_LADDER_NAME) .append(" WHERE ").append(COLUMN_LADDER_NAME_LADDERID).append("=").append("?"); statementGetLadderNameFromID = db.prepareStatement(query.toString()); // statementGetLadderFromName query = new StringBuilder("SELECT ").append(COLUMN_LADDER_NAME_LADDERID) .append(" FROM ").append(TABLE_LADDER_NAME) .append(" WHERE ").append(COLUMN_LADDER_NAME_NAME).append("=").append("?"); statementGetLadderIDFromName = db.prepareStatement(query.toString()); // statementGetLadderFromGroup query = new StringBuilder("SELECT ").append(COLUMN_LADDER_LADDERID) .append(" FROM ").append(TABLE_LADDER) .append(" WHERE ").append(COLUMN_LADDER_GROUPID).append("=").append("?") .append(" AND ").append(COLUMN_LADDER_ZONEID).append("=").append("?"); statementGetLadderIDFromGroup = db.prepareStatement(query.toString()); // statementGetZoneFromID query = new StringBuilder("SELECT ").append(COLUMN_ZONE_NAME) .append(" FROM ").append(TABLE_ZONE) .append(" WHERE ").append(COLUMN_ZONE_ZONEID).append("=").append("?"); statementGetZoneNameFromID = db.prepareStatement(query.toString()); // statementGetZoneFromName query = new StringBuilder("SELECT ").append(COLUMN_ZONE_ZONEID) .append(" FROM ").append(TABLE_ZONE) .append(" WHERE ").append(COLUMN_ZONE_NAME).append("=").append("?"); statementGetZoneIDFromName = db.prepareStatement(query.toString()); // statementGetGroupFromID query = new StringBuilder("SELECT ").append(COLUMN_GROUP_NAME) .append(" FROM ").append(TABLE_GROUP) .append(" WHERE ").append(COLUMN_GROUP_GROUPID).append("=").append("?"); statementGetGroupNameFromID = db.prepareStatement(query.toString()); // statementGetGroupFromName query = new StringBuilder("SELECT *") // .append(COLUMN_GROUP_GROUPID) .append(" FROM ").append(TABLE_GROUP) .append(" WHERE ").append(COLUMN_GROUP_NAME).append("=").append("?"); statementGetGroupIDFromName = db.prepareStatement(query.toString()); // statementGetPlayerFromID query = new StringBuilder("SELECT ").append(COLUMN_PLAYER_USERNAME) .append(" FROM ").append(TABLE_PLAYER) .append(" WHERE ").append(COLUMN_PLAYER_PLAYERID).append("=").append("?"); statementGetPlayerNameFromID = db.prepareStatement(query.toString()); // statementGetPlayerFromName query = new StringBuilder("SELECT ").append(COLUMN_PLAYER_PLAYERID) .append(" FROM ").append(TABLE_PLAYER) .append(" WHERE ").append(COLUMN_PLAYER_USERNAME).append("=").append("?"); statementGetPlayerIDFromName = db.prepareStatement(query.toString()); // statementGetAllPermissions query = new StringBuilder("SELECT * FROM ").append(TABLE_PERMISSION) .append(" WHERE ").append(COLUMN_PERMISSION_TARGET).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_ZONEID).append("=").append("?"); statementGetAllPermissions = db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Helper Put Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // statementPutZone query = new StringBuilder("INSERT INTO ").append(TABLE_ZONE).append(" (") .append(COLUMN_ZONE_NAME).append(") ") .append(" VALUES ").append(" (?) "); statementPutZone = db.prepareStatement(query.toString()); // statementPutPlayer query = new StringBuilder("INSERT INTO ").append(TABLE_PLAYER).append(" (") .append(COLUMN_PLAYER_USERNAME).append(") ") .append(" VALUES ").append(" (?) "); statementPutPlayer = db.prepareStatement(query.toString()); // statementPutLadderName query = new StringBuilder("INSERT INTO ").append(TABLE_LADDER_NAME).append(" (") .append(COLUMN_LADDER_NAME_NAME).append(") ") .append(" VALUES ").append(" (?) "); statementPutLadderName = db.prepareStatement(query.toString()); // statementPutLadder query = new StringBuilder("INSERT INTO ").append(TABLE_LADDER).append(" (") .append(COLUMN_LADDER_GROUPID).append(", ") .append(COLUMN_LADDER_ZONEID).append(", ") .append(COLUMN_LADDER_RANK).append(", ") .append(COLUMN_LADDER_LADDERID).append(") ") .append(" VALUES ").append(" (?, ?, ?, ?) "); statementPutLadder = db.prepareStatement(query.toString()); // statementPutGroup query = new StringBuilder("INSERT INTO ").append(TABLE_GROUP).append(" (").append(COLUMN_GROUP_NAME).append(", ").append(COLUMN_GROUP_PREFIX) .append(", ").append(COLUMN_GROUP_SUFFIX).append(", ").append(COLUMN_GROUP_PARENT).append(", ").append(COLUMN_GROUP_PRIORITY).append(", ") .append(COLUMN_GROUP_ZONE).append(") ").append(" VALUES ").append(" (?, ?, ?, ?, ?, ?) "); statementPutGroup = db.prepareStatement(query.toString()); // statementPutPermission query = new StringBuilder("INSERT INTO ").append(TABLE_PERMISSION).append(" (").append(COLUMN_PERMISSION_ALLOWED).append(", ") .append(COLUMN_PERMISSION_TARGET).append(", ").append(COLUMN_PERMISSION_ISGROUP).append(", ").append(COLUMN_PERMISSION_PERM).append(", ") .append(COLUMN_PERMISSION_ZONEID).append(") ").append(" VALUES ").append(" (?, ?, ?, ?, ?) "); statementPutPermission = db.prepareStatement(query.toString()); // statementPutPlayerInGroup query = new StringBuilder("INSERT INTO ").append(TABLE_GROUP_CONNECTOR).append(" (") .append(COLUMN_GROUP_CONNECTOR_GROUPID).append(", ") .append(COLUMN_GROUP_CONNECTOR_PLAYERID).append(", ") .append(COLUMN_GROUP_CONNECTOR_ZONEID).append(") ") .append(" VALUES ").append(" (?, ?, ?)"); statementPutPlayerInGroup = db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Helper Delete Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // statementDeletePermission query = new StringBuilder("DELETE FROM ").append(TABLE_PERMISSION).append(" WHERE ") .append(COLUMN_PERMISSION_TARGET).append("=").append("?").append(" AND ") .append(COLUMN_PERMISSION_ISGROUP).append("=").append("?").append(" AND ") .append(COLUMN_PERMISSION_PERM).append("=").append("?").append(" AND ") .append(COLUMN_PERMISSION_ZONEID).append("=").append("?"); statementDeletePermission = db.prepareStatement(query.toString()); // statementDeleteGroupInZone query = new StringBuilder("DELETE FROM ").append(TABLE_GROUP) .append(" WHERE ").append(COLUMN_GROUP_NAME).append("=").append("?").append(" AND ") .append(COLUMN_GROUP_ZONE).append("=").append("?"); statementDeleteGroupInZone = db.prepareStatement(query.toString()); // statementDelZone query = new StringBuilder("DELETE FROM ").append(TABLE_ZONE).append(" WHERE ") .append(COLUMN_ZONE_NAME).append("=").append("?"); statementDelZone = db.prepareStatement(query.toString()); // remove player from all groups in specified zone. used in /p user <player> group set query = new StringBuilder("DELETE FROM ").append(TABLE_GROUP_CONNECTOR).append(" WHERE ") .append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID) .append("=").append("?").append(" AND ").append(TABLE_GROUP_CONNECTOR).append(".") .append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementRemovePlayerGroups = instance.db.prepareStatement(query.toString()); // remove player from specified group in specified zone. used in /p user <player> group add query = new StringBuilder("DELETE FROM ").append(TABLE_GROUP_CONNECTOR) .append(" WHERE ").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?") .append(" AND ").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?") .append(" AND ").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append("?"); statementRemovePlayerGroup = instance.db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Helper ZONE Delete Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // delete groups from zone query = new StringBuilder("DELETE FROM ").append(TABLE_GROUP) .append(" WHERE ").append(COLUMN_GROUP_ZONE).append("=").append("?"); statementDelGroupFromZone = db.prepareStatement(query.toString()); // delete ladder from zone query = new StringBuilder("DELETE FROM ").append(TABLE_LADDER) .append(" WHERE ").append(COLUMN_LADDER_ZONEID).append("=").append("?"); statementDelLadderFromZone = db.prepareStatement(query.toString()); // delete group connectorsw from zone query = new StringBuilder("DELETE FROM ").append(TABLE_LADDER) .append(" WHERE ").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementDelGroupConnectorsFromZone = db.prepareStatement(query.toString()); // statementDeleteGroupInZone query = new StringBuilder("DELETE FROM ").append(TABLE_PERMISSION) .append(" WHERE ").append(COLUMN_PERMISSION_ZONEID).append("=").append("?"); statementDelPermFromZone = db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Dump Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // statementGetGroupFromID query = new StringBuilder("SELECT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_GROUP).append(".") .append(COLUMN_GROUP_PRIORITY).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ").append(TABLE_GROUP) .append(".").append(COLUMN_GROUP_SUFFIX).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PARENT).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(" FROM ").append(TABLE_GROUP).append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_ZONE).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID); statementDumpGroups = instance.db.prepareStatement(query.toString()); query = new StringBuilder("SELECT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_PERMISSION).append(".") .append(COLUMN_PERMISSION_PERM).append(", ").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ").append(TABLE_PERMISSION) .append(".").append(COLUMN_PERMISSION_ALLOWED).append(" FROM ").append(TABLE_PERMISSION).append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_PERMISSION).append(".").append(COLUMN_PERMISSION_TARGET).append("=").append(TABLE_GROUP).append(".") .append(COLUMN_GROUP_GROUPID).append(" INNER JOIN ").append(TABLE_ZONE).append(" ON ").append(TABLE_PERMISSION).append(".") .append(COLUMN_PERMISSION_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID); statementDumpGroupPermissions = instance.db.prepareStatement(query.toString()); query = (new StringBuilder("SELECT ")).append(TABLE_PLAYER).append(".").append(COLUMN_PLAYER_USERNAME).append(", ").append(TABLE_PERMISSION) .append(".").append(COLUMN_PERMISSION_PERM).append(", ").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_PERMISSION).append(".").append(COLUMN_PERMISSION_ALLOWED).append(" FROM ").append(TABLE_PERMISSION).append(" INNER JOIN ") .append(TABLE_PLAYER).append(" ON ").append(TABLE_PERMISSION).append(".").append(COLUMN_PERMISSION_TARGET).append("=").append(TABLE_PLAYER) .append(".").append(COLUMN_PLAYER_PLAYERID).append(" INNER JOIN ").append(TABLE_ZONE).append(" ON ").append(TABLE_PERMISSION).append(".") .append(COLUMN_PERMISSION_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID); statementDumpPlayerPermissions = instance.db.prepareStatement(query.toString()); query = new StringBuilder("SELECT ").append(COLUMN_PLAYER_USERNAME).append(" FROM ").append(TABLE_PLAYER); statementDumpPlayers = instance.db.prepareStatement(query.toString()); query = new StringBuilder("SELECT DISTINCT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_PLAYER) .append(".").append(COLUMN_PLAYER_USERNAME).append(", ").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(" FROM ") .append(TABLE_GROUP_CONNECTOR).append(" INNER JOIN ").append(TABLE_GROUP).append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".") .append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID).append(" INNER JOIN ") .append(TABLE_PLAYER).append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=") .append(TABLE_PLAYER).append(".").append(COLUMN_PLAYER_PLAYERID).append(" INNER JOIN ").append(TABLE_ZONE).append(" ON ") .append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".") .append(COLUMN_ZONE_ZONEID); statementDumpGroupConnector = instance.db.prepareStatement(query.toString()); query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_LADDER_NAME).append(".").append(COLUMN_LADDER_NAME_NAME).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME) .append(" FROM ").append(TABLE_LADDER) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_LADDER_NAME) .append(" ON ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_LADDERID).append("=").append(TABLE_LADDER_NAME).append(".").append(COLUMN_LADDER_NAME_LADDERID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID); statementDumpLadders = instance.db.prepareStatement(query.toString()); // remove specified group query = new StringBuilder(""); } catch (Exception e) { e.printStackTrace(); Throwables.propagate(e); // it may not get to this.. hopefully... throw new RuntimeException(e.getMessage()); } OutputHandler.SOP("Statement preparation successful"); }
public SqlHelper(ConfigPermissions config) { instance = this; connect(config.connector); if (generate) generate(); try { // statementGetLadderList StringBuilder query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_LADDER).append(".").append(COLUMN_LADDER_RANK) .append(" FROM ").append(TABLE_LADDER) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" WHERE ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_LADDERID).append("=").append("?") .append(" AND ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_ZONEID).append("=").append("?") .append(" ORDER BY ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_RANK); statementGetLadderList = instance.db.prepareStatement(query.toString()); // statementGetGroupsFromLadder query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_LADDER) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_GROUPID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?") .append(" AND ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_LADDERID).append("=").append("?"); statementGetGroupsFromLadder = instance.db.prepareStatement(query.toString()); // statementGetGroupsFromLadderAndZone query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_LADDER) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_GROUPID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?") .append(" AND ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_LADDERID).append("=").append("?") .append(" AND ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementGetGroupsFromLadderAndZone = instance.db.prepareStatement(query.toString()); // statementGetGroupsFromZone query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?") .append(" AND ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementGetGroupsFromZone = instance.db.prepareStatement(query.toString()); // statementGetGroupsFromZone query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?"); statementGetGroupsFromPlayer = instance.db.prepareStatement(query.toString()); // statementGetGroupFromName query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PRIORITY).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_SUFFIX).append(", ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PARENT).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME) .append(" FROM ").append(TABLE_GROUP) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_ZONE).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID) .append(" WHERE ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append("=").append("?"); statementGetGroupFromName = instance.db.prepareStatement(query.toString()); // statementGetGroupFromID query = new StringBuilder("SELECT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_GROUP).append(".") .append(COLUMN_GROUP_PRIORITY).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ").append(TABLE_GROUP) .append(".").append(COLUMN_GROUP_SUFFIX).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PARENT).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(" FROM ").append(TABLE_GROUP).append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_ZONE).append("=").append(TABLE_ZONE).append(".") .append(COLUMN_ZONE_ZONEID).append(" WHERE ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID).append("=").append("?"); statementGetGroupFromID = instance.db.prepareStatement(query.toString()); // statementGetGroupsForPlayer query = new StringBuilder("SELECT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_GROUP).append(".") .append(COLUMN_GROUP_PRIORITY).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ").append(TABLE_GROUP) .append(".").append(COLUMN_GROUP_SUFFIX).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PARENT).append(" FROM ") .append(TABLE_GROUP_CONNECTOR).append(" INNER JOIN ").append(TABLE_GROUP).append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".") .append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID).append(" WHERE ") .append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?").append(" AND ") .append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementGetGroupsForPlayer = instance.db.prepareStatement(query.toString()); // statementGetGroupsInZone query = new StringBuilder("SELECT * FROM ").append(TABLE_GROUP).append(" WHERE ").append(COLUMN_GROUP_ZONE).append("=").append("?"); statementGetGroupsInZone = instance.db.prepareStatement(query.toString()); // statementGetGroupIDsForEntryPlayer query = new StringBuilder("SELECT ").append(COLUMN_GROUP_CONNECTOR_GROUPID) .append(" FROM ").append(TABLE_GROUP_CONNECTOR) .append(" WHERE ").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append(0) .append(" AND ").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementGetGroupIDsForEntryPlayer = instance.db.prepareStatement(query.toString()); // statementUpdateGroup query = new StringBuilder("UPDATE ").append(TABLE_GROUP).append(" SET ").append(COLUMN_GROUP_NAME).append("=").append("?, ") .append(COLUMN_GROUP_PREFIX).append("=").append("?, ").append(COLUMN_GROUP_SUFFIX).append("=").append("?, ").append(COLUMN_GROUP_PARENT) .append("=").append("?, ").append(COLUMN_GROUP_PRIORITY).append("=").append("?, ").append(COLUMN_GROUP_ZONE).append("=").append("?") .append(" WHERE ").append(COLUMN_GROUP_NAME).append("=").append("?") .append(" AND ").append(COLUMN_GROUP_ZONE).append("=").append("?"); statementUpdateGroup = db.prepareStatement(query.toString()); // statementGetPermission query = new StringBuilder("SELECT ").append(COLUMN_PERMISSION_ALLOWED).append(" FROM ").append(TABLE_PERMISSION).append(" WHERE ") .append(COLUMN_PERMISSION_TARGET).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_PERM).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ZONEID).append("=") .append("?"); statementGetPermission = db.prepareStatement(query.toString()); // statementGetAll query = new StringBuilder("SELECT ").append(COLUMN_PERMISSION_ALLOWED) .append(" FROM ").append(TABLE_PERMISSION) .append(" WHERE ").append(COLUMN_PERMISSION_TARGET).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_PERM).append("=").append("'" + Permission.ALL + "'") .append(" AND ").append(COLUMN_PERMISSION_ZONEID).append("=").append("?"); statementGetAll = db.prepareStatement(query.toString()); query = new StringBuilder("SELECT ").append(COLUMN_PERMISSION_ALLOWED).append(" FROM ").append(TABLE_PERMISSION).append(" WHERE ") .append(COLUMN_PERMISSION_TARGET).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_PERM).append(" LIKE ").append("?").append(" AND ").append(COLUMN_PERMISSION_ZONEID) .append("=").append("?"); statementGetPermissionForward = db.prepareStatement(query.toString()); // statementUpdatePermission query = new StringBuilder("UPDATE ").append(TABLE_PERMISSION).append(" SET ").append(COLUMN_PERMISSION_ALLOWED).append("=").append("?") .append(" WHERE ").append(COLUMN_PERMISSION_TARGET).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=") .append("?").append(" AND ").append(COLUMN_PERMISSION_PERM).append("=").append("?").append(" AND ").append(COLUMN_PERMISSION_ZONEID) .append("=").append("?"); statementUpdatePermission = db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Helper Get Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // statementGetLadderFromID query = new StringBuilder("SELECT ").append(COLUMN_LADDER_NAME_NAME) .append(" FROM ").append(TABLE_LADDER_NAME) .append(" WHERE ").append(COLUMN_LADDER_NAME_LADDERID).append("=").append("?"); statementGetLadderNameFromID = db.prepareStatement(query.toString()); // statementGetLadderFromName query = new StringBuilder("SELECT ").append(COLUMN_LADDER_NAME_LADDERID) .append(" FROM ").append(TABLE_LADDER_NAME) .append(" WHERE ").append(COLUMN_LADDER_NAME_NAME).append("=").append("?"); statementGetLadderIDFromName = db.prepareStatement(query.toString()); // statementGetLadderFromGroup query = new StringBuilder("SELECT ").append(COLUMN_LADDER_LADDERID) .append(" FROM ").append(TABLE_LADDER) .append(" WHERE ").append(COLUMN_LADDER_GROUPID).append("=").append("?") .append(" AND ").append(COLUMN_LADDER_ZONEID).append("=").append("?"); statementGetLadderIDFromGroup = db.prepareStatement(query.toString()); // statementGetZoneFromID query = new StringBuilder("SELECT ").append(COLUMN_ZONE_NAME) .append(" FROM ").append(TABLE_ZONE) .append(" WHERE ").append(COLUMN_ZONE_ZONEID).append("=").append("?"); statementGetZoneNameFromID = db.prepareStatement(query.toString()); // statementGetZoneFromName query = new StringBuilder("SELECT ").append(COLUMN_ZONE_ZONEID) .append(" FROM ").append(TABLE_ZONE) .append(" WHERE ").append(COLUMN_ZONE_NAME).append("=").append("?"); statementGetZoneIDFromName = db.prepareStatement(query.toString()); // statementGetGroupFromID query = new StringBuilder("SELECT ").append(COLUMN_GROUP_NAME) .append(" FROM ").append(TABLE_GROUP) .append(" WHERE ").append(COLUMN_GROUP_GROUPID).append("=").append("?"); statementGetGroupNameFromID = db.prepareStatement(query.toString()); // statementGetGroupFromName query = new StringBuilder("SELECT *") // .append(COLUMN_GROUP_GROUPID) .append(" FROM ").append(TABLE_GROUP) .append(" WHERE ").append(COLUMN_GROUP_NAME).append("=").append("?"); statementGetGroupIDFromName = db.prepareStatement(query.toString()); // statementGetPlayerFromID query = new StringBuilder("SELECT ").append(COLUMN_PLAYER_USERNAME) .append(" FROM ").append(TABLE_PLAYER) .append(" WHERE ").append(COLUMN_PLAYER_PLAYERID).append("=").append("?"); statementGetPlayerNameFromID = db.prepareStatement(query.toString()); // statementGetPlayerFromName query = new StringBuilder("SELECT ").append(COLUMN_PLAYER_PLAYERID) .append(" FROM ").append(TABLE_PLAYER) .append(" WHERE ").append(COLUMN_PLAYER_USERNAME).append("=").append("?"); statementGetPlayerIDFromName = db.prepareStatement(query.toString()); // statementGetAllPermissions query = new StringBuilder("SELECT * FROM ").append(TABLE_PERMISSION) .append(" WHERE ").append(COLUMN_PERMISSION_TARGET).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_ZONEID).append("=").append("?") .append(" AND ").append(COLUMN_PERMISSION_ISGROUP).append("=").append("?"); statementGetAllPermissions = db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Helper Put Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // statementPutZone query = new StringBuilder("INSERT INTO ").append(TABLE_ZONE).append(" (") .append(COLUMN_ZONE_NAME).append(") ") .append(" VALUES ").append(" (?) "); statementPutZone = db.prepareStatement(query.toString()); // statementPutPlayer query = new StringBuilder("INSERT INTO ").append(TABLE_PLAYER).append(" (") .append(COLUMN_PLAYER_USERNAME).append(") ") .append(" VALUES ").append(" (?) "); statementPutPlayer = db.prepareStatement(query.toString()); // statementPutLadderName query = new StringBuilder("INSERT INTO ").append(TABLE_LADDER_NAME).append(" (") .append(COLUMN_LADDER_NAME_NAME).append(") ") .append(" VALUES ").append(" (?) "); statementPutLadderName = db.prepareStatement(query.toString()); // statementPutLadder query = new StringBuilder("INSERT INTO ").append(TABLE_LADDER).append(" (") .append(COLUMN_LADDER_GROUPID).append(", ") .append(COLUMN_LADDER_ZONEID).append(", ") .append(COLUMN_LADDER_RANK).append(", ") .append(COLUMN_LADDER_LADDERID).append(") ") .append(" VALUES ").append(" (?, ?, ?, ?) "); statementPutLadder = db.prepareStatement(query.toString()); // statementPutGroup query = new StringBuilder("INSERT INTO ").append(TABLE_GROUP).append(" (").append(COLUMN_GROUP_NAME).append(", ").append(COLUMN_GROUP_PREFIX) .append(", ").append(COLUMN_GROUP_SUFFIX).append(", ").append(COLUMN_GROUP_PARENT).append(", ").append(COLUMN_GROUP_PRIORITY).append(", ") .append(COLUMN_GROUP_ZONE).append(") ").append(" VALUES ").append(" (?, ?, ?, ?, ?, ?) "); statementPutGroup = db.prepareStatement(query.toString()); // statementPutPermission query = new StringBuilder("INSERT INTO ").append(TABLE_PERMISSION).append(" (").append(COLUMN_PERMISSION_ALLOWED).append(", ") .append(COLUMN_PERMISSION_TARGET).append(", ").append(COLUMN_PERMISSION_ISGROUP).append(", ").append(COLUMN_PERMISSION_PERM).append(", ") .append(COLUMN_PERMISSION_ZONEID).append(") ").append(" VALUES ").append(" (?, ?, ?, ?, ?) "); statementPutPermission = db.prepareStatement(query.toString()); // statementPutPlayerInGroup query = new StringBuilder("INSERT INTO ").append(TABLE_GROUP_CONNECTOR).append(" (") .append(COLUMN_GROUP_CONNECTOR_GROUPID).append(", ") .append(COLUMN_GROUP_CONNECTOR_PLAYERID).append(", ") .append(COLUMN_GROUP_CONNECTOR_ZONEID).append(") ") .append(" VALUES ").append(" (?, ?, ?)"); statementPutPlayerInGroup = db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Helper Delete Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // statementDeletePermission query = new StringBuilder("DELETE FROM ").append(TABLE_PERMISSION).append(" WHERE ") .append(COLUMN_PERMISSION_TARGET).append("=").append("?").append(" AND ") .append(COLUMN_PERMISSION_ISGROUP).append("=").append("?").append(" AND ") .append(COLUMN_PERMISSION_PERM).append("=").append("?").append(" AND ") .append(COLUMN_PERMISSION_ZONEID).append("=").append("?"); statementDeletePermission = db.prepareStatement(query.toString()); // statementDeleteGroupInZone query = new StringBuilder("DELETE FROM ").append(TABLE_GROUP) .append(" WHERE ").append(COLUMN_GROUP_NAME).append("=").append("?").append(" AND ") .append(COLUMN_GROUP_ZONE).append("=").append("?"); statementDeleteGroupInZone = db.prepareStatement(query.toString()); // statementDelZone query = new StringBuilder("DELETE FROM ").append(TABLE_ZONE).append(" WHERE ") .append(COLUMN_ZONE_NAME).append("=").append("?"); statementDelZone = db.prepareStatement(query.toString()); // remove player from all groups in specified zone. used in /p user <player> group set query = new StringBuilder("DELETE FROM ").append(TABLE_GROUP_CONNECTOR).append(" WHERE ") .append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID) .append("=").append("?").append(" AND ").append(TABLE_GROUP_CONNECTOR).append(".") .append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementRemovePlayerGroups = instance.db.prepareStatement(query.toString()); // remove player from specified group in specified zone. used in /p user <player> group add query = new StringBuilder("DELETE FROM ").append(TABLE_GROUP_CONNECTOR) .append(" WHERE ").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=").append("?") .append(" AND ").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?") .append(" AND ").append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append("?"); statementRemovePlayerGroup = instance.db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Helper ZONE Delete Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // delete groups from zone query = new StringBuilder("DELETE FROM ").append(TABLE_GROUP) .append(" WHERE ").append(COLUMN_GROUP_ZONE).append("=").append("?"); statementDelGroupFromZone = db.prepareStatement(query.toString()); // delete ladder from zone query = new StringBuilder("DELETE FROM ").append(TABLE_LADDER) .append(" WHERE ").append(COLUMN_LADDER_ZONEID).append("=").append("?"); statementDelLadderFromZone = db.prepareStatement(query.toString()); // delete group connectorsw from zone query = new StringBuilder("DELETE FROM ").append(TABLE_LADDER) .append(" WHERE ").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append("?"); statementDelGroupConnectorsFromZone = db.prepareStatement(query.toString()); // statementDeleteGroupInZone query = new StringBuilder("DELETE FROM ").append(TABLE_PERMISSION) .append(" WHERE ").append(COLUMN_PERMISSION_ZONEID).append("=").append("?"); statementDelPermFromZone = db.prepareStatement(query.toString()); // >>>>>>>>>>>>>>>>>>>>>>>>>>> // Dump Statements // <<<<<<<<<<<<<<<<<<<<<<<<<< // statementGetGroupFromID query = new StringBuilder("SELECT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_GROUP).append(".") .append(COLUMN_GROUP_PRIORITY).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PREFIX).append(", ").append(TABLE_GROUP) .append(".").append(COLUMN_GROUP_SUFFIX).append(", ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_PARENT).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(" FROM ").append(TABLE_GROUP).append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_ZONE).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID); statementDumpGroups = instance.db.prepareStatement(query.toString()); query = new StringBuilder("SELECT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_PERMISSION).append(".") .append(COLUMN_PERMISSION_PERM).append(", ").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ").append(TABLE_PERMISSION) .append(".").append(COLUMN_PERMISSION_ALLOWED).append(" FROM ").append(TABLE_PERMISSION).append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_PERMISSION).append(".").append(COLUMN_PERMISSION_TARGET).append("=").append(TABLE_GROUP).append(".") .append(COLUMN_GROUP_GROUPID).append(" INNER JOIN ").append(TABLE_ZONE).append(" ON ").append(TABLE_PERMISSION).append(".") .append(COLUMN_PERMISSION_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID); statementDumpGroupPermissions = instance.db.prepareStatement(query.toString()); query = (new StringBuilder("SELECT ")).append(TABLE_PLAYER).append(".").append(COLUMN_PLAYER_USERNAME).append(", ").append(TABLE_PERMISSION) .append(".").append(COLUMN_PERMISSION_PERM).append(", ").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(", ") .append(TABLE_PERMISSION).append(".").append(COLUMN_PERMISSION_ALLOWED).append(" FROM ").append(TABLE_PERMISSION).append(" INNER JOIN ") .append(TABLE_PLAYER).append(" ON ").append(TABLE_PERMISSION).append(".").append(COLUMN_PERMISSION_TARGET).append("=").append(TABLE_PLAYER) .append(".").append(COLUMN_PLAYER_PLAYERID).append(" INNER JOIN ").append(TABLE_ZONE).append(" ON ").append(TABLE_PERMISSION).append(".") .append(COLUMN_PERMISSION_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID); statementDumpPlayerPermissions = instance.db.prepareStatement(query.toString()); query = new StringBuilder("SELECT ").append(COLUMN_PLAYER_USERNAME).append(" FROM ").append(TABLE_PLAYER); statementDumpPlayers = instance.db.prepareStatement(query.toString()); query = new StringBuilder("SELECT DISTINCT ").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ").append(TABLE_PLAYER) .append(".").append(COLUMN_PLAYER_USERNAME).append(", ").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME).append(" FROM ") .append(TABLE_GROUP_CONNECTOR).append(" INNER JOIN ").append(TABLE_GROUP).append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".") .append(COLUMN_GROUP_CONNECTOR_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID).append(" INNER JOIN ") .append(TABLE_PLAYER).append(" ON ").append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_PLAYERID).append("=") .append(TABLE_PLAYER).append(".").append(COLUMN_PLAYER_PLAYERID).append(" INNER JOIN ").append(TABLE_ZONE).append(" ON ") .append(TABLE_GROUP_CONNECTOR).append(".").append(COLUMN_GROUP_CONNECTOR_ZONEID).append("=").append(TABLE_ZONE).append(".") .append(COLUMN_ZONE_ZONEID); statementDumpGroupConnector = instance.db.prepareStatement(query.toString()); query = new StringBuilder("SELECT ") .append(TABLE_GROUP).append(".").append(COLUMN_GROUP_NAME).append(", ") .append(TABLE_LADDER_NAME).append(".").append(COLUMN_LADDER_NAME_NAME).append(", ") .append(TABLE_ZONE).append(".").append(COLUMN_ZONE_NAME) .append(" FROM ").append(TABLE_LADDER) .append(" INNER JOIN ").append(TABLE_GROUP) .append(" ON ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_GROUPID).append("=").append(TABLE_GROUP).append(".").append(COLUMN_GROUP_GROUPID) .append(" INNER JOIN ").append(TABLE_LADDER_NAME) .append(" ON ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_LADDERID).append("=").append(TABLE_LADDER_NAME).append(".").append(COLUMN_LADDER_NAME_LADDERID) .append(" INNER JOIN ").append(TABLE_ZONE) .append(" ON ").append(TABLE_LADDER).append(".").append(COLUMN_LADDER_ZONEID).append("=").append(TABLE_ZONE).append(".").append(COLUMN_ZONE_ZONEID); statementDumpLadders = instance.db.prepareStatement(query.toString()); // remove specified group query = new StringBuilder(""); } catch (Exception e) { e.printStackTrace(); Throwables.propagate(e); // it may not get to this.. hopefully... throw new RuntimeException(e.getMessage()); } OutputHandler.SOP("Statement preparation successful"); }
diff --git a/CSC340Project/src/matchingAlgorithm/gui/ButtonPanel.java b/CSC340Project/src/matchingAlgorithm/gui/ButtonPanel.java index d863fd4..408fa05 100644 --- a/CSC340Project/src/matchingAlgorithm/gui/ButtonPanel.java +++ b/CSC340Project/src/matchingAlgorithm/gui/ButtonPanel.java @@ -1,73 +1,73 @@ package matchingAlgorithm.gui; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.ItemListener; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JPanel; public class ButtonPanel extends JPanel { JButton findMatches; JCheckBox ethnicity, language, disability, distance, age, income; public ButtonPanel(ActionListener alistener, ItemListener ilistener){ super(); this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); findMatches = new JButton("Find Matches"); findMatches.setActionCommand("find matches"); findMatches.addActionListener(alistener); this.add(findMatches, this); ethnicity = new JCheckBox("Ethnicity"); this.add(ethnicity, this); ethnicity.addItemListener(ilistener); language = new JCheckBox("Language"); this.add(language, this); language.addItemListener(ilistener); disability = new JCheckBox("Disability"); this.add(disability, this); disability.addItemListener(ilistener); distance = new JCheckBox("Distance"); this.add(distance, this); distance.addItemListener(ilistener); age = new JCheckBox("Age"); this.add(age, this); age.addItemListener(ilistener); - income = new JCheckBox("Language"); + income = new JCheckBox("Income"); this.add(income, this); income.addItemListener(ilistener); } public JCheckBox getEthnicity() { return ethnicity; } public JCheckBox getLanguage() { return language; } public JCheckBox getDisability() { return disability; } public JCheckBox getDistance() { return distance; } public JCheckBox getAge() { return age; } public JCheckBox getIncome() { return income; } }
true
true
public ButtonPanel(ActionListener alistener, ItemListener ilistener){ super(); this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); findMatches = new JButton("Find Matches"); findMatches.setActionCommand("find matches"); findMatches.addActionListener(alistener); this.add(findMatches, this); ethnicity = new JCheckBox("Ethnicity"); this.add(ethnicity, this); ethnicity.addItemListener(ilistener); language = new JCheckBox("Language"); this.add(language, this); language.addItemListener(ilistener); disability = new JCheckBox("Disability"); this.add(disability, this); disability.addItemListener(ilistener); distance = new JCheckBox("Distance"); this.add(distance, this); distance.addItemListener(ilistener); age = new JCheckBox("Age"); this.add(age, this); age.addItemListener(ilistener); income = new JCheckBox("Language"); this.add(income, this); income.addItemListener(ilistener); }
public ButtonPanel(ActionListener alistener, ItemListener ilistener){ super(); this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); findMatches = new JButton("Find Matches"); findMatches.setActionCommand("find matches"); findMatches.addActionListener(alistener); this.add(findMatches, this); ethnicity = new JCheckBox("Ethnicity"); this.add(ethnicity, this); ethnicity.addItemListener(ilistener); language = new JCheckBox("Language"); this.add(language, this); language.addItemListener(ilistener); disability = new JCheckBox("Disability"); this.add(disability, this); disability.addItemListener(ilistener); distance = new JCheckBox("Distance"); this.add(distance, this); distance.addItemListener(ilistener); age = new JCheckBox("Age"); this.add(age, this); age.addItemListener(ilistener); income = new JCheckBox("Income"); this.add(income, this); income.addItemListener(ilistener); }
diff --git a/html/src/playn/html/HtmlQuadShader.java b/html/src/playn/html/HtmlQuadShader.java index 79607891..81e0b351 100644 --- a/html/src/playn/html/HtmlQuadShader.java +++ b/html/src/playn/html/HtmlQuadShader.java @@ -1,118 +1,118 @@ /** * Copyright 2012 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package playn.html; import com.google.gwt.typedarrays.client.Float32Array; import com.google.gwt.webgl.client.WebGLRenderingContext; import static com.google.gwt.webgl.client.WebGLRenderingContext.*; import playn.core.InternalTransform; import playn.core.gl.GLShader; abstract class HtmlQuadShader implements GLShader { static class Texture extends HtmlQuadShader implements GLShader.Texture { private HtmlShaderCore.Texture core; Texture(HtmlGLContext ctx) { core = new HtmlShaderCore.Texture(ctx); } @Override public void prepare(Object texObj, float alpha) { core.prepare(this, texObj, alpha); } @Override protected HtmlShaderCore core() { return core; } } static class Color extends HtmlQuadShader implements GLShader.Color { private HtmlShaderCore.Color core; Color(HtmlGLContext ctx) { core = new HtmlShaderCore.Color(ctx); } @Override public void prepare(int color, float alpha) { core.prepare(this, color, alpha); } @Override protected HtmlShaderCore core() { return core; } } private final Float32Array vertexData = Float32Array.create(HtmlShaderCore.VERTEX_SIZE * 4); private int vertexOffset; @Override public void addQuad(InternalTransform local, float x1, float y1, float sx1, float sy1, float x2, float y2, float sx2, float sy2, float x3, float y3, float sx3, float sy3, float x4, float y4, float sx4, float sy4) { HtmlInternalTransform xform = (HtmlInternalTransform) local; addVertex(xform, x1, y1, sx1, sy1); addVertex(xform, x2, y2, sx2, sy2); addVertex(xform, x3, y3, sx3, sy3); addVertex(xform, x4, y4, sx4, sy4); WebGLRenderingContext gl = core().flush(); gl.bufferData(ARRAY_BUFFER, vertexData, STREAM_DRAW); - gl.drawArrays(TRIANGLE_STRIP, 0, vertexOffset); + gl.drawArrays(TRIANGLE_STRIP, 0, vertexOffset/HtmlShaderCore.VERTEX_SIZE); vertexOffset = 0; } @Override public void addQuad(InternalTransform local, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { addQuad(local, x1, y1, 0, 0, x2, y2, 0, 0, x3, y3, 0, 0, x4, y4, 0, 0); } @Override public void addTriangles(InternalTransform local, float[] xys, float texWidth, float texHeight, int[] indices) { throw new UnsupportedOperationException("Should only be used for quads"); } @Override public void addTriangles(InternalTransform local, float[] xys, float[] sxys, int[] indices) { throw new UnsupportedOperationException("Should only be used for quads"); } @Override public void flush() { // noop! we flush immediately after every addQuad } protected void addVertex(HtmlInternalTransform xform, float dx, float dy, float sx, float sy) { vertexData.set(xform.matrix(), vertexOffset); vertexOffset += 6; vertexData.set(vertexOffset++, dx); vertexData.set(vertexOffset++, dy); vertexData.set(vertexOffset++, sx); vertexData.set(vertexOffset++, sy); } protected abstract HtmlShaderCore core(); }
true
true
public void addQuad(InternalTransform local, float x1, float y1, float sx1, float sy1, float x2, float y2, float sx2, float sy2, float x3, float y3, float sx3, float sy3, float x4, float y4, float sx4, float sy4) { HtmlInternalTransform xform = (HtmlInternalTransform) local; addVertex(xform, x1, y1, sx1, sy1); addVertex(xform, x2, y2, sx2, sy2); addVertex(xform, x3, y3, sx3, sy3); addVertex(xform, x4, y4, sx4, sy4); WebGLRenderingContext gl = core().flush(); gl.bufferData(ARRAY_BUFFER, vertexData, STREAM_DRAW); gl.drawArrays(TRIANGLE_STRIP, 0, vertexOffset); vertexOffset = 0; }
public void addQuad(InternalTransform local, float x1, float y1, float sx1, float sy1, float x2, float y2, float sx2, float sy2, float x3, float y3, float sx3, float sy3, float x4, float y4, float sx4, float sy4) { HtmlInternalTransform xform = (HtmlInternalTransform) local; addVertex(xform, x1, y1, sx1, sy1); addVertex(xform, x2, y2, sx2, sy2); addVertex(xform, x3, y3, sx3, sy3); addVertex(xform, x4, y4, sx4, sy4); WebGLRenderingContext gl = core().flush(); gl.bufferData(ARRAY_BUFFER, vertexData, STREAM_DRAW); gl.drawArrays(TRIANGLE_STRIP, 0, vertexOffset/HtmlShaderCore.VERTEX_SIZE); vertexOffset = 0; }
diff --git a/modules/dm4-accesscontrol/src/main/java/de/deepamehta/plugins/accesscontrol/model/Credentials.java b/modules/dm4-accesscontrol/src/main/java/de/deepamehta/plugins/accesscontrol/model/Credentials.java index 11b2cdb1e..3384ead54 100644 --- a/modules/dm4-accesscontrol/src/main/java/de/deepamehta/plugins/accesscontrol/model/Credentials.java +++ b/modules/dm4-accesscontrol/src/main/java/de/deepamehta/plugins/accesscontrol/model/Credentials.java @@ -1,49 +1,51 @@ package de.deepamehta.plugins.accesscontrol.model; import de.deepamehta.core.util.JavaUtils; import com.sun.jersey.core.util.Base64; public class Credentials { // ------------------------------------------------------------------------------------------------------- Constants private static final String ENCRYPTED_PASSWORD_PREFIX = "-SHA256-"; // ---------------------------------------------------------------------------------------------- Instance Variables public String username; public String password; // encrypted // ---------------------------------------------------------------------------------------------------- Constructors /** * @param password as plain text */ public Credentials(String username, String password) { this.username = username; this.password = encryptPassword(password); } public Credentials(String authHeader) { authHeader = authHeader.substring("Basic ".length()); String[] values = new String(Base64.base64Decode(authHeader)).split(":"); - this.username = values[0]; + // Note: values.length is 0 if neither a username nor a password is entered + // values.length is 1 if no password is entered + this.username = values.length > 0 ? values[0] : ""; this.password = encryptPassword(values.length > 1 ? values[1] : ""); // Note: credentials obtained through Basic authorization are always plain text } // -------------------------------------------------------------------------------------------------- Public Methods public String toString() { return "username=\"" + username + "\", password=\""+ password + "\""; } // ------------------------------------------------------------------------------------------------- Private Methods private String encryptPassword(String password) { return ENCRYPTED_PASSWORD_PREFIX + JavaUtils.encodeSHA256(password); } }
true
true
public Credentials(String authHeader) { authHeader = authHeader.substring("Basic ".length()); String[] values = new String(Base64.base64Decode(authHeader)).split(":"); this.username = values[0]; this.password = encryptPassword(values.length > 1 ? values[1] : ""); // Note: credentials obtained through Basic authorization are always plain text }
public Credentials(String authHeader) { authHeader = authHeader.substring("Basic ".length()); String[] values = new String(Base64.base64Decode(authHeader)).split(":"); // Note: values.length is 0 if neither a username nor a password is entered // values.length is 1 if no password is entered this.username = values.length > 0 ? values[0] : ""; this.password = encryptPassword(values.length > 1 ? values[1] : ""); // Note: credentials obtained through Basic authorization are always plain text }
diff --git a/src/hhu/propra_2013/gruppe_13/MISCNPC.java b/src/hhu/propra_2013/gruppe_13/MISCNPC.java index 926f11c..89e4518 100644 --- a/src/hhu/propra_2013/gruppe_13/MISCNPC.java +++ b/src/hhu/propra_2013/gruppe_13/MISCNPC.java @@ -1,177 +1,177 @@ package hhu.propra_2013.gruppe_13; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; public class MISCNPC extends CoreGameObjects{ //Variables taken from enemy - some are maybe Hyper-Fluid (sic) private boolean talk; private int hp; private double x, y; private double r; private double v_x, v_y; private double height, width; private int strength; private int type; private Figure figure; private String text; private int stage; //NPC should know which area he is in, so he can refer to the level Theme or something private String boss; //NPC should know what the area boss is, so he can say funny stuff about him private String stageone,stagetwo,stagethree; private long npcTalkTime; //Constructor for NPC - TODO Think what the NPC should be able to do, and implement the useful thoughts MISCNPC(double initX, double initY, double initHeight, double initWidth, Figure inFigure, String inBoss, int inStage){ x = initX; y = initY; v_x = 0; v_y = 0; height = initHeight; width = initWidth; r = Math.max(width, height)+v_x*v_x+v_y*v_y; hp = 1; //should not be harmed at all, but GameObjects wants it kinda badly strength = 1; //should harm anyone else either, but you never know when a NPC will snap... figure = inFigure; //Stuff to tell the NPC what he can talk about boss = inBoss; stage = inStage; text = " "; - stageone = "Wow you started the game, congratulations /sarcasm."+"The Boss on this level is a red circle"; - stagetwo = "ok, so you managed to defeat the red circle, maybe you are able to defeat the next red circle"; - stagethree = "I am kinda impressed now... maybe you are able to see the victory screen if you live after you fought the last red circle"; + stageone = "Wow you started the game, congratulations /sarcasm."+"The Boss on this level is a red circle."; + stagetwo = "Ok, so you managed to defeat the red circle, maybe you are able to defeat the next red circle."; + stagethree = "I am kinda impressed now... maybe you are able to see the victory screen if you live after you fought the last red circle."; } //Methods from GameObjects - we probably won't need all of them /*-----------------------------------------------------------------------------------------------------*/ //Getter @Override int getHP() { // TODO Auto-generated method stub return hp; } @Override double getPosX() { // TODO Auto-generated method stub return x; } @Override double getPosY() { // TODO Auto-generated method stub return y; } @Override double getRad() { // TODO Auto-generated method stub return r; } @Override double getVX() { // TODO Auto-generated method stub return v_x; } @Override double getVY() { // TODO Auto-generated method stub return v_y; } @Override double getWidth() { // TODO Auto-generated method stub return width; } @Override double getHeight() { // TODO Auto-generated method stub return height; } /*----------------------------------------------------------------------------------------------__*/ //Setter @Override void setPos(double inX, double inY) { // TODO Auto-generated method stub x = inX; y = inY; } @Override void setSpeed(double inVX, double inVY) { // TODO Auto-generated method stub v_x = inVX; v_y = inVY; } @Override void setRad(double inR) { // TODO Auto-generated method stub r = inR; } @Override void setHP(int inHP) { // TODO Auto-generated method stub hp = inHP; } /*-------------------------------------------------------------------------------------------*/ //Graphics @Override void draw(Graphics2D g, int xOffset, int yOffset, double step) { g.setColor(Color.green); g.fillOval(xOffset+(int)Math.round((x-width/2.)*step), yOffset+(int)Math.round((y-height/2.)*step), (int)Math.round(step*width), (int)Math.round(step*height)); if(talk){ Font font = new Font("Arial", Font.PLAIN, (int)step/2); g.setFont(font); g.setColor(Color.white); g.fillRect(xOffset-(int)step/2, yOffset+(int)(step*14), (int)(step*23), (int)step*3 ); g.setColor(Color.black); g.drawString(text, xOffset, yOffset+(int)(step*14+step/2)); this.talkTimer(); } } @Override void takeDamage(int type, int strength) { // TODO Auto-generated method stub } // from here it's actual new NPC Stuff (and Stuff) void talk(){ switch(stage){ case 1: text = stageone; break; case 2: text = stagetwo; break; case 3: text = stagethree; break; } talk = true; npcTalkTime = System.currentTimeMillis(); } private void talkTimer(){ //timer for how long the npc talks if(System.currentTimeMillis() >= npcTalkTime + 10000) talk = false; } }
true
true
MISCNPC(double initX, double initY, double initHeight, double initWidth, Figure inFigure, String inBoss, int inStage){ x = initX; y = initY; v_x = 0; v_y = 0; height = initHeight; width = initWidth; r = Math.max(width, height)+v_x*v_x+v_y*v_y; hp = 1; //should not be harmed at all, but GameObjects wants it kinda badly strength = 1; //should harm anyone else either, but you never know when a NPC will snap... figure = inFigure; //Stuff to tell the NPC what he can talk about boss = inBoss; stage = inStage; text = " "; stageone = "Wow you started the game, congratulations /sarcasm."+"The Boss on this level is a red circle"; stagetwo = "ok, so you managed to defeat the red circle, maybe you are able to defeat the next red circle"; stagethree = "I am kinda impressed now... maybe you are able to see the victory screen if you live after you fought the last red circle"; }
MISCNPC(double initX, double initY, double initHeight, double initWidth, Figure inFigure, String inBoss, int inStage){ x = initX; y = initY; v_x = 0; v_y = 0; height = initHeight; width = initWidth; r = Math.max(width, height)+v_x*v_x+v_y*v_y; hp = 1; //should not be harmed at all, but GameObjects wants it kinda badly strength = 1; //should harm anyone else either, but you never know when a NPC will snap... figure = inFigure; //Stuff to tell the NPC what he can talk about boss = inBoss; stage = inStage; text = " "; stageone = "Wow you started the game, congratulations /sarcasm."+"The Boss on this level is a red circle."; stagetwo = "Ok, so you managed to defeat the red circle, maybe you are able to defeat the next red circle."; stagethree = "I am kinda impressed now... maybe you are able to see the victory screen if you live after you fought the last red circle."; }
diff --git a/src/com/appspot/iclifeplanning/SuggestionServlet.java b/src/com/appspot/iclifeplanning/SuggestionServlet.java index 1d0ec2e..aa2fe3d 100644 --- a/src/com/appspot/iclifeplanning/SuggestionServlet.java +++ b/src/com/appspot/iclifeplanning/SuggestionServlet.java @@ -1,191 +1,191 @@ package com.appspot.iclifeplanning; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.appspot.analyser.Analyzer; import com.appspot.analyser.DeleteSuggestion; import com.appspot.analyser.IEvent; import com.appspot.analyser.Suggestion; import com.appspot.datastore.SphereName; import com.appspot.datastore.TokenStore; import com.appspot.iclifeplanning.authentication.CalendarUtils; import com.appspot.iclifeplanning.events.Event; import com.appspot.iclifeplanning.events.EventStore; import com.google.appengine.repackaged.org.json.JSONArray; import com.google.appengine.repackaged.org.json.JSONException; import com.google.appengine.repackaged.org.json.JSONObject; /** * Suggestion servlet. responsible for managing the "optimise button". * Initialises the EventStore and runs the analyser to create suggestions. * * @author Agnieszka Magda Madurska ([email protected]) * */ @SuppressWarnings("serial") public class SuggestionServlet extends HttpServlet { // This should NOT be stored like this. Reimplement to use memcache at some point. private static Map<String, List<List<Suggestion>>> suggestionMap = new HashMap<String, List<List<Suggestion>>>(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("Map size: " + suggestionMap.size()); String token = TokenStore.getToken(CalendarUtils.getCurrentUserId()); CalendarUtils.client.setAuthSubToken(token); EventStore eventStore = EventStore.getInstance(); eventStore.initizalize(); List<Event> events = eventStore.getEvents(); // ------------------- Dummy data Analyzer analyser = new Analyzer(); //List<List<Suggestion>> suggestions = analyser.getSuggestions(events, CalendarUtils.getCurrentUserId(), true); List<List<Suggestion>> suggestions = new ArrayList<List<Suggestion>>(); suggestions.add(new ArrayList<Suggestion>()); suggestions.add(new ArrayList<Suggestion>()); suggestions.add(new ArrayList<Suggestion>()); suggestionMap.put(CalendarUtils.getCurrentUserId(), suggestions); IEvent event1 = (IEvent)events.get(0); IEvent event2 = (IEvent)events.get(1); IEvent event3 = (IEvent)events.get(2); IEvent event4 = (IEvent)events.get(3); IEvent event5 = (IEvent)events.get(4); IEvent event6 = (IEvent)events.get(5); Suggestion sug = new DeleteSuggestion(event1); List<Suggestion> alternatives = new ArrayList<Suggestion>(); alternatives.add(new DeleteSuggestion(event4)); alternatives.add(new DeleteSuggestion(event5)); sug.setAlternativeSuggetions(alternatives); suggestions.get(0).add(sug); suggestions.get(0).add(new DeleteSuggestion(event3)); sug = new DeleteSuggestion(event2); alternatives = new ArrayList<Suggestion>(); alternatives.add(new DeleteSuggestion(event4)); alternatives.add(new DeleteSuggestion(event5)); sug.setAlternativeSuggetions(alternatives); suggestions.get(1).add(sug); suggestions.get(1).add(new DeleteSuggestion(event4)); sug = new DeleteSuggestion(event3); alternatives = new ArrayList<Suggestion>(); alternatives.add(new DeleteSuggestion(event4)); alternatives.add(new DeleteSuggestion(event5)); sug.setAlternativeSuggetions(alternatives); suggestions.get(2).add(sug); suggestions.get(2).add(new DeleteSuggestion(event5)); suggestions.get(2).add(new DeleteSuggestion(event6)); // ------------------- Dummy data JSONArray suggestionArray = new JSONArray(); List<Suggestion> s; for (int i = 0; i < suggestions.size(); i++) { - s = suggestions.get(0); + s = suggestions.get(i); suggestionArray.put(suggestionListToJSONArray(s)); } JSONObject result = new JSONObject(); try { result.put("userID", CalendarUtils.getCurrentUserId()); result.put("lists", suggestionArray); } catch (JSONException e) { e.printStackTrace(); } response.getWriter().print(result); } private JSONArray suggestionListToJSONArray(List<Suggestion> suggestionList) { Suggestion suggestion; JSONArray suggestionArray = new JSONArray(); for (int i = 0; i < suggestionList.size(); i++) { suggestion = suggestionList.get(i); suggestionArray.put(suggestionToJSONArray(suggestion)); } return suggestionArray; } private JSONArray suggestionToJSONArray(Suggestion suggestion) { JSONArray suggestionArray = new JSONArray(); Suggestion alternativeSuggestion; List<Suggestion> alternativeSuggestions = suggestion.getAlternativeSuggestions(); suggestionArray.put(suggestionToJSONObject(suggestion)); for (int j = 0; j < alternativeSuggestions.size(); j++) { alternativeSuggestion = alternativeSuggestions.get(j); suggestionArray.put(suggestionToJSONObject(alternativeSuggestion)); } return suggestionArray; } private JSONObject suggestionToJSONObject(Suggestion suggestion) { JSONObject suggestionObject = new JSONObject(); try { suggestionObject.put("title", suggestion.getTitle()); suggestionObject.put("description", suggestion.getDescription()); suggestionObject.put("repeating", ""); SimpleDateFormat date = new SimpleDateFormat("EEE, d MMM yyyy HH:mm"); suggestionObject.put("startDateTime", date.format(suggestion.getStartDate().getTime())); suggestionObject.put("endDateTime", date.format(suggestion.getEndDate().getTime())); suggestionObject.put("type", suggestion.getType()); List<String> spheres = new ArrayList<String>(); for (SphereName sphere : suggestion.getSpheres().keySet()) { if (suggestion.getSpheres().get(sphere) > 0) { spheres.add(sphere.name()); } } suggestionObject.put("spheres", spheres); } catch (JSONException e) { e.printStackTrace(); } return suggestionObject; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { JSONObject suggestionsJSON = null; try { suggestionsJSON = new JSONObject(request.getReader().toString()); String userID = suggestionsJSON.getString("userID"); int list = suggestionsJSON.getInt("listNumber"); JSONArray acceptedSuggestions = suggestionsJSON.getJSONArray("suggestions"); int lenght = acceptedSuggestions.length(); JSONObject suggestionJSON; int suggestion; int alternative; String key; List<List<Suggestion>> suggestions = suggestionMap.get(userID); for(int i = 0; i < lenght; i++) { suggestionJSON = acceptedSuggestions.getJSONObject(i); key = suggestionJSON.keys().toString(); suggestion = Integer.parseInt(key); alternative = suggestionJSON.getInt(key); suggestions.get(list).get(suggestion).makePersistent(alternative); } } catch (JSONException e) { System.out.println("Badly formatted JSON!"); e.printStackTrace(); } } }
true
true
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("Map size: " + suggestionMap.size()); String token = TokenStore.getToken(CalendarUtils.getCurrentUserId()); CalendarUtils.client.setAuthSubToken(token); EventStore eventStore = EventStore.getInstance(); eventStore.initizalize(); List<Event> events = eventStore.getEvents(); // ------------------- Dummy data Analyzer analyser = new Analyzer(); //List<List<Suggestion>> suggestions = analyser.getSuggestions(events, CalendarUtils.getCurrentUserId(), true); List<List<Suggestion>> suggestions = new ArrayList<List<Suggestion>>(); suggestions.add(new ArrayList<Suggestion>()); suggestions.add(new ArrayList<Suggestion>()); suggestions.add(new ArrayList<Suggestion>()); suggestionMap.put(CalendarUtils.getCurrentUserId(), suggestions); IEvent event1 = (IEvent)events.get(0); IEvent event2 = (IEvent)events.get(1); IEvent event3 = (IEvent)events.get(2); IEvent event4 = (IEvent)events.get(3); IEvent event5 = (IEvent)events.get(4); IEvent event6 = (IEvent)events.get(5); Suggestion sug = new DeleteSuggestion(event1); List<Suggestion> alternatives = new ArrayList<Suggestion>(); alternatives.add(new DeleteSuggestion(event4)); alternatives.add(new DeleteSuggestion(event5)); sug.setAlternativeSuggetions(alternatives); suggestions.get(0).add(sug); suggestions.get(0).add(new DeleteSuggestion(event3)); sug = new DeleteSuggestion(event2); alternatives = new ArrayList<Suggestion>(); alternatives.add(new DeleteSuggestion(event4)); alternatives.add(new DeleteSuggestion(event5)); sug.setAlternativeSuggetions(alternatives); suggestions.get(1).add(sug); suggestions.get(1).add(new DeleteSuggestion(event4)); sug = new DeleteSuggestion(event3); alternatives = new ArrayList<Suggestion>(); alternatives.add(new DeleteSuggestion(event4)); alternatives.add(new DeleteSuggestion(event5)); sug.setAlternativeSuggetions(alternatives); suggestions.get(2).add(sug); suggestions.get(2).add(new DeleteSuggestion(event5)); suggestions.get(2).add(new DeleteSuggestion(event6)); // ------------------- Dummy data JSONArray suggestionArray = new JSONArray(); List<Suggestion> s; for (int i = 0; i < suggestions.size(); i++) { s = suggestions.get(0); suggestionArray.put(suggestionListToJSONArray(s)); } JSONObject result = new JSONObject(); try { result.put("userID", CalendarUtils.getCurrentUserId()); result.put("lists", suggestionArray); } catch (JSONException e) { e.printStackTrace(); } response.getWriter().print(result); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("Map size: " + suggestionMap.size()); String token = TokenStore.getToken(CalendarUtils.getCurrentUserId()); CalendarUtils.client.setAuthSubToken(token); EventStore eventStore = EventStore.getInstance(); eventStore.initizalize(); List<Event> events = eventStore.getEvents(); // ------------------- Dummy data Analyzer analyser = new Analyzer(); //List<List<Suggestion>> suggestions = analyser.getSuggestions(events, CalendarUtils.getCurrentUserId(), true); List<List<Suggestion>> suggestions = new ArrayList<List<Suggestion>>(); suggestions.add(new ArrayList<Suggestion>()); suggestions.add(new ArrayList<Suggestion>()); suggestions.add(new ArrayList<Suggestion>()); suggestionMap.put(CalendarUtils.getCurrentUserId(), suggestions); IEvent event1 = (IEvent)events.get(0); IEvent event2 = (IEvent)events.get(1); IEvent event3 = (IEvent)events.get(2); IEvent event4 = (IEvent)events.get(3); IEvent event5 = (IEvent)events.get(4); IEvent event6 = (IEvent)events.get(5); Suggestion sug = new DeleteSuggestion(event1); List<Suggestion> alternatives = new ArrayList<Suggestion>(); alternatives.add(new DeleteSuggestion(event4)); alternatives.add(new DeleteSuggestion(event5)); sug.setAlternativeSuggetions(alternatives); suggestions.get(0).add(sug); suggestions.get(0).add(new DeleteSuggestion(event3)); sug = new DeleteSuggestion(event2); alternatives = new ArrayList<Suggestion>(); alternatives.add(new DeleteSuggestion(event4)); alternatives.add(new DeleteSuggestion(event5)); sug.setAlternativeSuggetions(alternatives); suggestions.get(1).add(sug); suggestions.get(1).add(new DeleteSuggestion(event4)); sug = new DeleteSuggestion(event3); alternatives = new ArrayList<Suggestion>(); alternatives.add(new DeleteSuggestion(event4)); alternatives.add(new DeleteSuggestion(event5)); sug.setAlternativeSuggetions(alternatives); suggestions.get(2).add(sug); suggestions.get(2).add(new DeleteSuggestion(event5)); suggestions.get(2).add(new DeleteSuggestion(event6)); // ------------------- Dummy data JSONArray suggestionArray = new JSONArray(); List<Suggestion> s; for (int i = 0; i < suggestions.size(); i++) { s = suggestions.get(i); suggestionArray.put(suggestionListToJSONArray(s)); } JSONObject result = new JSONObject(); try { result.put("userID", CalendarUtils.getCurrentUserId()); result.put("lists", suggestionArray); } catch (JSONException e) { e.printStackTrace(); } response.getWriter().print(result); }
diff --git a/app/src/com/meiste/greg/ptw/WidgetProvider.java b/app/src/com/meiste/greg/ptw/WidgetProvider.java index 362c063..ccdcb4c 100644 --- a/app/src/com/meiste/greg/ptw/WidgetProvider.java +++ b/app/src/com/meiste/greg/ptw/WidgetProvider.java @@ -1,287 +1,291 @@ /* * Copyright (C) 2013 Gregory S. Meiste <http://gregmeiste.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.meiste.greg.ptw; import java.io.InputStream; import java.net.URL; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.impl.client.DefaultHttpClient; import com.google.analytics.tracking.android.EasyTracker; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.SystemClock; import android.text.format.DateUtils; import android.widget.RemoteViews; public class WidgetProvider extends AppWidgetProvider { private static final int RESULT_SUCCESS = 0; private static final int RESULT_FAILURE = -1; private static final int RESULT_NO_RACE = 1; private static final long UPDATE_INTERVAL = DateUtils.MINUTE_IN_MILLIS; private static final long UPDATE_FUDGE = 50; /* milliseconds */ private static final long UPDATE_WARNING = (DateUtils.HOUR_IN_MILLIS * 2) + UPDATE_FUDGE; private static final int PI_REQ_CODE = 810647; private static final String WIDGET_STATE = "widget.enabled"; private static final String URL_PREFIX = GAE.PROD_URL + "/img/race/"; private static Race sRace; private static Bitmap sBitmap; @Override public void onReceive (final Context context, final Intent intent) { if (intent.hasExtra(Intent.EXTRA_ALARM_COUNT)) { Util.log("WidgetProvider.onReceive: Widget alarm"); new UpdateWidgetTask().execute(context); } else if (intent.getAction().equals(Intent.ACTION_TIME_CHANGED)) { Util.log("WidgetProvider.onReceive: Time change"); setAlarm(context); } else if (intent.getAction().equals(PTW.INTENT_ACTION_SCHEDULE)) { Util.log("WidgetProvider.onReceive: Schedule Updated"); final int[] appWidgetIds = getInstalledWidgets(context); if (appWidgetIds.length > 0) { /* Force full widget update */ sRace = null; sBitmap = null; onUpdate(context, AppWidgetManager.getInstance(context), appWidgetIds); } } else if (intent.getAction().equals(PTW.INTENT_ACTION_ANSWERS)) { Util.log("WidgetProvider.onReceive: Answers submitted"); final int[] appWidgetIds = getInstalledWidgets(context); if (appWidgetIds.length > 0) { new UpdateWidgetTask().execute(context); } } else super.onReceive(context, intent); } @Override public void onEnabled(final Context context) { final boolean prevEnabled = Util.getState(context).getBoolean(WIDGET_STATE, false); Util.log("WidgetProvider.onEnabled: prevEnabled=" + prevEnabled); /* onEnabled gets called on device power up, so prevent extra enables * from being tracked. */ if (!prevEnabled) { Util.getState(context).edit().putBoolean(WIDGET_STATE, true).apply(); EasyTracker.getTracker().sendEvent("Widget", "state", "enabled", (long) 0); } } @Override public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, final int[] appWidgetIds) { Util.log("WidgetProvider.onUpdate: num=" + appWidgetIds.length); final RemoteViews rViews = new RemoteViews(context.getPackageName(), R.layout.widget_loading); appWidgetManager.updateAppWidget(appWidgetIds, rViews); new UpdateWidgetTask().execute(context); /* Set alarm to update widget when device is awake. This should really * be done in onEnabled, but Android doesn't always call onEnabled. */ setAlarm(context); } @Override public void onDisabled(final Context context) { Util.log("WidgetProvider.onDisabled"); final AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); am.cancel(getAlarmIntent(context)); Util.getState(context).edit().putBoolean(WIDGET_STATE, false).apply(); EasyTracker.getTracker().sendEvent("Widget", "state", "disabled", (long) 0); } private void setAlarm(final Context context) { /* No point setting alarm if no widgets */ if (getInstalledWidgets(context).length == 0) return; /* Android relative time rounds down, so update needs to be early if anything */ final long trigger = UPDATE_INTERVAL - (System.currentTimeMillis() % UPDATE_INTERVAL) - UPDATE_FUDGE; final AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + trigger, UPDATE_INTERVAL, getAlarmIntent(context)); Util.log("Initial trigger is " + trigger + " milliseconds from now"); } private PendingIntent getAlarmIntent(final Context context) { final Intent intent = new Intent(context, WidgetProvider.class); return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } private int[] getInstalledWidgets(final Context context) { final ComponentName thisWidget = new ComponentName(context, WidgetProvider.class); final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); return appWidgetManager.getAppWidgetIds(thisWidget); } private class UpdateWidgetTask extends AsyncTask<Context, Integer, Integer> { private Context mContext; @Override protected Integer doInBackground(final Context... context) { mContext = context[0]; final Race race = Race.getNext(mContext, true, true); if (race == null) return RESULT_NO_RACE; if ((sRace != null) && (sBitmap != null)) { if (sRace.isRecent()) { try { /* Need to fudge the time the other way */ Thread.sleep(UPDATE_FUDGE * 2); } catch (final InterruptedException e) {} } if ((sRace.getId() == race.getId()) || (sRace.isRecent())) return RESULT_SUCCESS; } sRace = race; try { final URL url = new URL(URL_PREFIX + sRace.getId() + ".png"); final HttpGet httpRequest = new HttpGet(url.toURI()); final HttpClient httpclient = new DefaultHttpClient(); final HttpResponse resp = httpclient.execute(httpRequest); final int statusCode = resp.getStatusLine().getStatusCode(); switch(statusCode) { case HttpStatus.SC_OK: final HttpEntity entity = resp.getEntity(); final BufferedHttpEntity b_entity = new BufferedHttpEntity(entity); final InputStream input = b_entity.getContent(); sBitmap = BitmapFactory.decodeStream(input); break; default: Util.log("Get logo failed (statusCode = " + statusCode + ")"); return RESULT_FAILURE; } } catch (final Exception e) { Util.log("Get logo failed with exception " + e); return RESULT_FAILURE; } return RESULT_SUCCESS; } @Override protected void onPostExecute(final Integer result) { Util.log("UpdateWidgetTask.onPostExecute: result=" + result); RemoteViews rViews; switch (result) { case RESULT_SUCCESS: + if (sRace == null) { + // Schedule update received while downloading logo + return; + } final int str_id = sRace.isRecent() ? R.string.widget_current_race : R.string.widget_next_race; final String nextRace = mContext.getString(str_id, sRace.getStartRelative(mContext)); rViews = new RemoteViews(mContext.getPackageName(), R.layout.widget); rViews.setTextViewText(R.id.when, nextRace); rViews.setImageViewBitmap(R.id.race_logo, sBitmap); if (sRace.isExhibition()) { rViews.setInt(R.id.status, "setText", R.string.widget_exhibition); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_normal); } else if (sRace.isRecent()) { rViews.setInt(R.id.status, "setText", R.string.widget_no_results); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_normal); } else if (!sRace.inProgress()) { rViews.setInt(R.id.status, "setText", R.string.widget_no_questions); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_normal); } else { final SharedPreferences acache = mContext.getSharedPreferences(Questions.ACACHE, Activity.MODE_PRIVATE); if (acache.contains(Questions.CACHE_PREFIX + sRace.getId())) { rViews.setInt(R.id.status, "setText", R.string.widget_submitted); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_good); } else if ((sRace.getStartTimestamp() - System.currentTimeMillis()) <= UPDATE_WARNING) { rViews.setInt(R.id.status, "setText", R.string.widget_no_answers); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_warning); } else { rViews.setInt(R.id.status, "setText", R.string.widget_please_submit); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_normal); } } Intent intent = new Intent(mContext, MainActivity.class); intent.putExtra(MainActivity.INTENT_TAB, 1); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pi = PendingIntent.getActivity(mContext, PI_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); rViews.setOnClickPendingIntent(R.id.widget_text_layout, pi); intent = new Intent(mContext, RaceActivity.class); intent.putExtra(RaceActivity.INTENT_ID, sRace.getId()); intent.putExtra(RaceActivity.INTENT_ALARM, true); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pi = PendingIntent.getActivity(mContext, PI_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); rViews.setOnClickPendingIntent(R.id.race_logo, pi); break; case RESULT_NO_RACE: rViews = new RemoteViews(mContext.getPackageName(), R.layout.widget_no_race); intent = new Intent(mContext, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pi = PendingIntent.getActivity(mContext, PI_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); rViews.setOnClickPendingIntent(R.id.widget_full_layout, pi); break; case RESULT_FAILURE: default: rViews = new RemoteViews(mContext.getPackageName(), R.layout.widget_error); intent = new Intent(mContext, WidgetProvider.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, getInstalledWidgets(mContext)); pi = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); rViews.setOnClickPendingIntent(R.id.widget_error_layout, pi); break; } final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext); appWidgetManager.updateAppWidget(getInstalledWidgets(mContext), rViews); } } }
true
true
protected void onPostExecute(final Integer result) { Util.log("UpdateWidgetTask.onPostExecute: result=" + result); RemoteViews rViews; switch (result) { case RESULT_SUCCESS: final int str_id = sRace.isRecent() ? R.string.widget_current_race : R.string.widget_next_race; final String nextRace = mContext.getString(str_id, sRace.getStartRelative(mContext)); rViews = new RemoteViews(mContext.getPackageName(), R.layout.widget); rViews.setTextViewText(R.id.when, nextRace); rViews.setImageViewBitmap(R.id.race_logo, sBitmap); if (sRace.isExhibition()) { rViews.setInt(R.id.status, "setText", R.string.widget_exhibition); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_normal); } else if (sRace.isRecent()) { rViews.setInt(R.id.status, "setText", R.string.widget_no_results); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_normal); } else if (!sRace.inProgress()) { rViews.setInt(R.id.status, "setText", R.string.widget_no_questions); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_normal); } else { final SharedPreferences acache = mContext.getSharedPreferences(Questions.ACACHE, Activity.MODE_PRIVATE); if (acache.contains(Questions.CACHE_PREFIX + sRace.getId())) { rViews.setInt(R.id.status, "setText", R.string.widget_submitted); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_good); } else if ((sRace.getStartTimestamp() - System.currentTimeMillis()) <= UPDATE_WARNING) { rViews.setInt(R.id.status, "setText", R.string.widget_no_answers); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_warning); } else { rViews.setInt(R.id.status, "setText", R.string.widget_please_submit); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_normal); } } Intent intent = new Intent(mContext, MainActivity.class); intent.putExtra(MainActivity.INTENT_TAB, 1); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pi = PendingIntent.getActivity(mContext, PI_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); rViews.setOnClickPendingIntent(R.id.widget_text_layout, pi); intent = new Intent(mContext, RaceActivity.class); intent.putExtra(RaceActivity.INTENT_ID, sRace.getId()); intent.putExtra(RaceActivity.INTENT_ALARM, true); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pi = PendingIntent.getActivity(mContext, PI_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); rViews.setOnClickPendingIntent(R.id.race_logo, pi); break; case RESULT_NO_RACE: rViews = new RemoteViews(mContext.getPackageName(), R.layout.widget_no_race); intent = new Intent(mContext, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pi = PendingIntent.getActivity(mContext, PI_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); rViews.setOnClickPendingIntent(R.id.widget_full_layout, pi); break; case RESULT_FAILURE: default: rViews = new RemoteViews(mContext.getPackageName(), R.layout.widget_error); intent = new Intent(mContext, WidgetProvider.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, getInstalledWidgets(mContext)); pi = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); rViews.setOnClickPendingIntent(R.id.widget_error_layout, pi); break; } final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext); appWidgetManager.updateAppWidget(getInstalledWidgets(mContext), rViews); }
protected void onPostExecute(final Integer result) { Util.log("UpdateWidgetTask.onPostExecute: result=" + result); RemoteViews rViews; switch (result) { case RESULT_SUCCESS: if (sRace == null) { // Schedule update received while downloading logo return; } final int str_id = sRace.isRecent() ? R.string.widget_current_race : R.string.widget_next_race; final String nextRace = mContext.getString(str_id, sRace.getStartRelative(mContext)); rViews = new RemoteViews(mContext.getPackageName(), R.layout.widget); rViews.setTextViewText(R.id.when, nextRace); rViews.setImageViewBitmap(R.id.race_logo, sBitmap); if (sRace.isExhibition()) { rViews.setInt(R.id.status, "setText", R.string.widget_exhibition); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_normal); } else if (sRace.isRecent()) { rViews.setInt(R.id.status, "setText", R.string.widget_no_results); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_normal); } else if (!sRace.inProgress()) { rViews.setInt(R.id.status, "setText", R.string.widget_no_questions); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_normal); } else { final SharedPreferences acache = mContext.getSharedPreferences(Questions.ACACHE, Activity.MODE_PRIVATE); if (acache.contains(Questions.CACHE_PREFIX + sRace.getId())) { rViews.setInt(R.id.status, "setText", R.string.widget_submitted); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_good); } else if ((sRace.getStartTimestamp() - System.currentTimeMillis()) <= UPDATE_WARNING) { rViews.setInt(R.id.status, "setText", R.string.widget_no_answers); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_warning); } else { rViews.setInt(R.id.status, "setText", R.string.widget_please_submit); rViews.setInt(R.id.widget_text_layout, "setBackgroundResource", R.drawable.widget_normal); } } Intent intent = new Intent(mContext, MainActivity.class); intent.putExtra(MainActivity.INTENT_TAB, 1); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pi = PendingIntent.getActivity(mContext, PI_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); rViews.setOnClickPendingIntent(R.id.widget_text_layout, pi); intent = new Intent(mContext, RaceActivity.class); intent.putExtra(RaceActivity.INTENT_ID, sRace.getId()); intent.putExtra(RaceActivity.INTENT_ALARM, true); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pi = PendingIntent.getActivity(mContext, PI_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); rViews.setOnClickPendingIntent(R.id.race_logo, pi); break; case RESULT_NO_RACE: rViews = new RemoteViews(mContext.getPackageName(), R.layout.widget_no_race); intent = new Intent(mContext, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pi = PendingIntent.getActivity(mContext, PI_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); rViews.setOnClickPendingIntent(R.id.widget_full_layout, pi); break; case RESULT_FAILURE: default: rViews = new RemoteViews(mContext.getPackageName(), R.layout.widget_error); intent = new Intent(mContext, WidgetProvider.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, getInstalledWidgets(mContext)); pi = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); rViews.setOnClickPendingIntent(R.id.widget_error_layout, pi); break; } final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext); appWidgetManager.updateAppWidget(getInstalledWidgets(mContext), rViews); }
diff --git a/src/main/java/fr/inria/diversify/replace/RunMaven.java b/src/main/java/fr/inria/diversify/replace/RunMaven.java index bd89f30..22b59bc 100644 --- a/src/main/java/fr/inria/diversify/replace/RunMaven.java +++ b/src/main/java/fr/inria/diversify/replace/RunMaven.java @@ -1,73 +1,73 @@ package fr.inria.diversify.replace; import org.apache.maven.cli.MavenCli; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; /** * User: Simon * Date: 5/17/13 * Time: 11:34 AM */ public class RunMaven extends Thread { protected String directory; protected List<String> result; protected boolean compileError; protected boolean allTestRun; protected String lifeCycle; public RunMaven(String directory, String lifeCycle) { this.directory = directory; this.lifeCycle = lifeCycle; } public void run() { MavenCli cli = new MavenCli(); ByteArrayOutputStream os = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(os); try { cli.doMain(new String[]{lifeCycle}, directory, ps, ps); parseResult(os.toString()); } catch (OutOfMemoryError e) { e.printStackTrace(); } ps.close(); } protected void parseResult(String r) { result = new ArrayList<String>(); boolean start = false; for (String s : r.split("\n")) { - System.out.println(s); +// System.out.println(s); if (s.startsWith("[ERROR] COMPILATION ERROR")) compileError = true; if (s.startsWith("Tests in error:")) { start = true; allTestRun = true; } if (start && s.equals("")) start = false; if (!s.startsWith("Tests in error:") && start) result.add(s); } allTestRun = allTestRun || (result.isEmpty() && !compileError); } public List<String> getResult() { return result; } public boolean allTestRun() { return allTestRun; } public boolean getCompileError() { return compileError; } }
true
true
protected void parseResult(String r) { result = new ArrayList<String>(); boolean start = false; for (String s : r.split("\n")) { System.out.println(s); if (s.startsWith("[ERROR] COMPILATION ERROR")) compileError = true; if (s.startsWith("Tests in error:")) { start = true; allTestRun = true; } if (start && s.equals("")) start = false; if (!s.startsWith("Tests in error:") && start) result.add(s); } allTestRun = allTestRun || (result.isEmpty() && !compileError); }
protected void parseResult(String r) { result = new ArrayList<String>(); boolean start = false; for (String s : r.split("\n")) { // System.out.println(s); if (s.startsWith("[ERROR] COMPILATION ERROR")) compileError = true; if (s.startsWith("Tests in error:")) { start = true; allTestRun = true; } if (start && s.equals("")) start = false; if (!s.startsWith("Tests in error:") && start) result.add(s); } allTestRun = allTestRun || (result.isEmpty() && !compileError); }
diff --git a/src/org/eclipse/core/tests/resources/regression/IFileTest.java b/src/org/eclipse/core/tests/resources/regression/IFileTest.java index 23d6c11..71588f9 100644 --- a/src/org/eclipse/core/tests/resources/regression/IFileTest.java +++ b/src/org/eclipse/core/tests/resources/regression/IFileTest.java @@ -1,114 +1,114 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.core.tests.resources.regression; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.core.boot.BootLoader; import org.eclipse.core.internal.localstore.CoreFileSystemLibrary; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.tests.harness.EclipseWorkspaceTest; public class IFileTest extends EclipseWorkspaceTest { /** * Constructor for IFileTest. */ public IFileTest() { super(); } /** * Constructor for IFileTest. * @param name */ public IFileTest(String name) { super(name); } public static Test suite() { return new TestSuite(IFileTest.class); } /** * Bug states that the error code in the CoreException which is thrown when * you try to create a file in a read-only folder on Linux should be * FAILED_WRITE_LOCAL. */ public void testBug25658() { // This test is no longer valid since the error code is dependant on whether // or not the parent folder is marked as read-only. We need to write a different - // test to make the file.create file. + // test to make the file.create fail. if (true) return; // We need to know whether or not we can set the folder to be read-only // in order to perform this test. if (!CoreFileSystemLibrary.usingNatives()) return; // Don't test this on Windows if (BootLoader.getOS().equals(BootLoader.OS_WIN32)) return; IProject project = getWorkspace().getRoot().getProject("MyProject"); IFolder folder = project.getFolder("folder"); ensureExistsInWorkspace(new IResource[] {project, folder}, true); IFile file = folder.getFile("file.txt"); try { folder.setReadOnly(true); assertTrue("0.0", folder.isReadOnly()); try { file.create(getRandomContents(), true, getMonitor()); fail("0.1"); } catch (CoreException e) { assertEquals("0.2", IResourceStatus.FAILED_WRITE_LOCAL, e.getStatus().getCode()); } } finally { folder.setReadOnly(false); } } /** * Bug requests that if a failed file write occurs on Linux that we check the immediate * parent to see if it is read-only so we can return a better error code and message * to the user. */ public void testBug25662() { // We need to know whether or not we can set the folder to be read-only // in order to perform this test. if (!CoreFileSystemLibrary.usingNatives()) return; // Only run this test on Linux for now since Windows lets you create // a file within a read-only folder. if (!BootLoader.getOS().equals(BootLoader.OS_LINUX)) return; IProject project = getWorkspace().getRoot().getProject("MyProject"); IFolder folder = project.getFolder("folder"); ensureExistsInWorkspace(new IResource[] {project, folder}, true); IFile file = folder.getFile("file.txt"); try { folder.setReadOnly(true); assertTrue("0.0", folder.isReadOnly()); try { file.create(getRandomContents(), true, getMonitor()); fail("0.1"); } catch (CoreException e) { assertEquals("0.2", IResourceStatus.PARENT_READ_ONLY, e.getStatus().getCode()); } } finally { folder.setReadOnly(false); } } }
true
true
public void testBug25658() { // This test is no longer valid since the error code is dependant on whether // or not the parent folder is marked as read-only. We need to write a different // test to make the file.create file. if (true) return; // We need to know whether or not we can set the folder to be read-only // in order to perform this test. if (!CoreFileSystemLibrary.usingNatives()) return; // Don't test this on Windows if (BootLoader.getOS().equals(BootLoader.OS_WIN32)) return; IProject project = getWorkspace().getRoot().getProject("MyProject"); IFolder folder = project.getFolder("folder"); ensureExistsInWorkspace(new IResource[] {project, folder}, true); IFile file = folder.getFile("file.txt"); try { folder.setReadOnly(true); assertTrue("0.0", folder.isReadOnly()); try { file.create(getRandomContents(), true, getMonitor()); fail("0.1"); } catch (CoreException e) { assertEquals("0.2", IResourceStatus.FAILED_WRITE_LOCAL, e.getStatus().getCode()); } } finally { folder.setReadOnly(false); } }
public void testBug25658() { // This test is no longer valid since the error code is dependant on whether // or not the parent folder is marked as read-only. We need to write a different // test to make the file.create fail. if (true) return; // We need to know whether or not we can set the folder to be read-only // in order to perform this test. if (!CoreFileSystemLibrary.usingNatives()) return; // Don't test this on Windows if (BootLoader.getOS().equals(BootLoader.OS_WIN32)) return; IProject project = getWorkspace().getRoot().getProject("MyProject"); IFolder folder = project.getFolder("folder"); ensureExistsInWorkspace(new IResource[] {project, folder}, true); IFile file = folder.getFile("file.txt"); try { folder.setReadOnly(true); assertTrue("0.0", folder.isReadOnly()); try { file.create(getRandomContents(), true, getMonitor()); fail("0.1"); } catch (CoreException e) { assertEquals("0.2", IResourceStatus.FAILED_WRITE_LOCAL, e.getStatus().getCode()); } } finally { folder.setReadOnly(false); } }
diff --git a/PhonelabServices/src/edu/buffalo/cse/phonelab/statusmonitor/StatusMonitorLocation.java b/PhonelabServices/src/edu/buffalo/cse/phonelab/statusmonitor/StatusMonitorLocation.java index 1860da7..b3a3778 100644 --- a/PhonelabServices/src/edu/buffalo/cse/phonelab/statusmonitor/StatusMonitorLocation.java +++ b/PhonelabServices/src/edu/buffalo/cse/phonelab/statusmonitor/StatusMonitorLocation.java @@ -1,86 +1,93 @@ /** * @author fatih & Sean * * [email protected] */ package edu.buffalo.cse.phonelab.statusmonitor; import java.util.Timer; import java.util.TimerTask; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import edu.buffalo.cse.phonelab.utilities.Locks; public class StatusMonitorLocation extends Service { Timer timer; LocationManager locationManager; LocationListener locationListener; @Override public IBinder onBind(Intent intent) { return null; } public int onStartCommand(Intent intent, int flags, int startId) { Log.i("PhoneLab-" + getClass().getSimpleName(), "Learning Location"); Locks.acquireWakeLock(this); timer = new Timer(); timer.schedule(new TimerTask() { public void run() { locationManager.removeUpdates(locationListener); Log.i("PhoneLab-" + "StatusMonitorLocation", "Couldn't learn location"); Locks.releaseWakeLock(); StatusMonitorLocation.this.stopSelf(); } }, 60000*1); locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { public void onLocationChanged(Location location) { makeUseOfNewLocation(location); } private void makeUseOfNewLocation(Location location) { if (location.getAccuracy() < 3000 && location.getTime() > System.currentTimeMillis() - 20000) { locationManager.removeUpdates(this); timer.cancel(); Log.i("PhoneLab-" + "StatusMonitorLocation", "Location_Latitude: " + location.getLatitude() + " Longitude: " + location.getLongitude() + " Accuracy: " + location.getAccuracy()); Locks.releaseWakeLock(); StatusMonitorLocation.this.stopSelf(); } } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) { locationManager.removeUpdates(this); timer.cancel(); StatusMonitorLocation.this.stopSelf(); } }; // Register the listener with the Location Manager to receive location updates - locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); + try { + locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); + } catch (Exception e) { + Log.e("PhoneLab-" + "StatusMonitorLocation", "Network Location Provider is not available"); + timer.cancel(); + Locks.releaseWakeLock(); + stopSelf(); + } return START_STICKY; } }
true
true
public int onStartCommand(Intent intent, int flags, int startId) { Log.i("PhoneLab-" + getClass().getSimpleName(), "Learning Location"); Locks.acquireWakeLock(this); timer = new Timer(); timer.schedule(new TimerTask() { public void run() { locationManager.removeUpdates(locationListener); Log.i("PhoneLab-" + "StatusMonitorLocation", "Couldn't learn location"); Locks.releaseWakeLock(); StatusMonitorLocation.this.stopSelf(); } }, 60000*1); locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { public void onLocationChanged(Location location) { makeUseOfNewLocation(location); } private void makeUseOfNewLocation(Location location) { if (location.getAccuracy() < 3000 && location.getTime() > System.currentTimeMillis() - 20000) { locationManager.removeUpdates(this); timer.cancel(); Log.i("PhoneLab-" + "StatusMonitorLocation", "Location_Latitude: " + location.getLatitude() + " Longitude: " + location.getLongitude() + " Accuracy: " + location.getAccuracy()); Locks.releaseWakeLock(); StatusMonitorLocation.this.stopSelf(); } } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) { locationManager.removeUpdates(this); timer.cancel(); StatusMonitorLocation.this.stopSelf(); } }; // Register the listener with the Location Manager to receive location updates locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); return START_STICKY; }
public int onStartCommand(Intent intent, int flags, int startId) { Log.i("PhoneLab-" + getClass().getSimpleName(), "Learning Location"); Locks.acquireWakeLock(this); timer = new Timer(); timer.schedule(new TimerTask() { public void run() { locationManager.removeUpdates(locationListener); Log.i("PhoneLab-" + "StatusMonitorLocation", "Couldn't learn location"); Locks.releaseWakeLock(); StatusMonitorLocation.this.stopSelf(); } }, 60000*1); locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { public void onLocationChanged(Location location) { makeUseOfNewLocation(location); } private void makeUseOfNewLocation(Location location) { if (location.getAccuracy() < 3000 && location.getTime() > System.currentTimeMillis() - 20000) { locationManager.removeUpdates(this); timer.cancel(); Log.i("PhoneLab-" + "StatusMonitorLocation", "Location_Latitude: " + location.getLatitude() + " Longitude: " + location.getLongitude() + " Accuracy: " + location.getAccuracy()); Locks.releaseWakeLock(); StatusMonitorLocation.this.stopSelf(); } } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) { locationManager.removeUpdates(this); timer.cancel(); StatusMonitorLocation.this.stopSelf(); } }; // Register the listener with the Location Manager to receive location updates try { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } catch (Exception e) { Log.e("PhoneLab-" + "StatusMonitorLocation", "Network Location Provider is not available"); timer.cancel(); Locks.releaseWakeLock(); stopSelf(); } return START_STICKY; }
diff --git a/src/ibis/ipl/impl/Ibis.java b/src/ibis/ipl/impl/Ibis.java index 9fb26f57..e9aeeb54 100644 --- a/src/ibis/ipl/impl/Ibis.java +++ b/src/ibis/ipl/impl/Ibis.java @@ -1,827 +1,833 @@ /* $Id$ */ package ibis.ipl.impl; import ibis.io.IbisIOException; import ibis.ipl.Credentials; import ibis.ipl.IbisCapabilities; import ibis.ipl.IbisConfigurationException; import ibis.ipl.IbisCreationFailedException; import ibis.ipl.IbisFactory; import ibis.ipl.IbisProperties; import ibis.ipl.IbisStarter; import ibis.ipl.MessageUpcall; import ibis.ipl.NoSuchPropertyException; import ibis.ipl.PortType; import ibis.ipl.ReceivePortConnectUpcall; import ibis.ipl.RegistryEventHandler; import ibis.ipl.SendPortDisconnectUpcall; import ibis.ipl.registry.Registry; import ibis.ipl.support.management.ManagementClient; import ibis.ipl.support.vivaldi.Coordinates; import ibis.ipl.support.vivaldi.VivaldiClient; import ibis.util.TypedProperties; import java.io.IOException; import java.io.PrintStream; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This implementation of the {@link ibis.ipl.Ibis} interface is a base class, * to be extended by specific Ibis implementations. */ public abstract class Ibis implements ibis.ipl.Ibis // , IbisMBean { // property to uniquely identify an Ibis locally, even when it has not // joined the registry yet public static final String ID_PROPERTY = "ibis.local.id"; /** Debugging output. */ private static final Logger logger = LoggerFactory .getLogger("ibis.ipl.impl.Ibis"); /** The IbisCapabilities as specified by the user. */ private final IbisCapabilities capabilities; /** List of port types given by the user */ private final PortType[] portTypes; private final IbisStarter starter; /** * Properties, as given to * {@link ibis.ipl.IbisFactory#createIbis(IbisCapabilities, Properties, boolean, RegistryEventHandler, PortType...)} * . */ protected TypedProperties properties; /** The Ibis registry. */ private final Registry registry; /** Management Client */ private final ManagementClient managementClient; /** Vivaldi Client */ private final VivaldiClient vivaldiClient; /** Identifies this Ibis instance in the registry. */ public final IbisIdentifier ident; /** Set when {@link #end()} is called. */ private boolean ended = false; /** The receiveports running on this Ibis instance. */ private HashMap<String, ReceivePort> receivePorts; /** The sendports running on this Ibis instance. */ private HashMap<String, SendPort> sendPorts; private HashMap<ibis.ipl.IbisIdentifier, Long> sentBytesPerIbis = null; private HashMap<ibis.ipl.IbisIdentifier, Long> receivedBytesPerIbis = null; /** Counter for allocating names for anonymous sendports. */ private static int send_counter = 0; /** Counter for allocating names for anonymous receiveports. */ private static int receive_counter = 0; /** Total number of messages send by closed send ports */ private long outgoingMessageCount = 0; /** Total number of messages received by closed receive ports */ private long incomingMessageCount = 0; /** Total number of bytes written to messages closed send ports */ private long bytesWritten = 0; /** Total number of bytes send by closed send ports */ private long bytesSent = 0; /** Total number of bytes read by closed receive ports */ private long bytesReceived = 0; /** Total number of bytes read from messages (for closed received ports) */ private long bytesRead = 0; /** * Version, consisting of both the generic implementation version, and the * "actual" implementation version. */ private String getImplementationVersion() throws Exception { String genericVersion = Ibis.class.getPackage() .getImplementationVersion(); // --Roelof on android the implementation version from the manifest gets // overwritten with a default implementation version of "0.0". This is // not the value we're searching for. if (genericVersion == null || genericVersion.equals("0.0")) { // try to get version from IPL_MANIFEST properties genericVersion = IbisFactory .getManifestProperty("implementation.version"); } logger.debug("Version of Generic Ibis = " + genericVersion); if (genericVersion == null || starter.getImplementationVersion() == null) { throw new Exception("cannot get version for ibis"); } return genericVersion + starter.getImplementationVersion(); } /** * Constructs an <code>Ibis</code> instance with the specified parameters. * * @param registryHandler * the registryHandler. * @param capabilities * the capabilities. * @param applicationTag * an application level tag for this Ibis instance * @param portTypes * the port types requested for this ibis implementation. * @param userProperties * the properties as provided by the Ibis factory. */ protected Ibis(RegistryEventHandler registryHandler, IbisCapabilities capabilities, Credentials credentials, byte[] applicationTag, PortType[] portTypes, Properties userProperties, IbisStarter starter) throws IbisCreationFailedException { if (capabilities == null) { throw new IbisConfigurationException("capabilities not specified"); } this.capabilities = capabilities; this.portTypes = portTypes; this.starter = starter; this.properties = new TypedProperties(); // bottom up add properties, starting with hard coded ones properties.addProperties(IbisProperties.getHardcodedProperties()); properties.addProperties(userProperties); // set unique ID for this Ibis. properties.setProperty(ID_PROPERTY, UUID.randomUUID().toString()); if (logger.isDebugEnabled()) { logger.debug("Ibis constructor: properties = " + properties); } receivePorts = new HashMap<String, ReceivePort>(); sendPorts = new HashMap<String, SendPort>(); + if (registryHandler != null) { + // Only install wrapper if user actually has an event handler. + // Otherwise, registry downcalls won't work. There needs to be another + // way to let an Ibis know of died Ibises. --Ceriel + registryHandler = new RegistryEventHandlerWrapper(registryHandler, this); + } try { registry = Registry.createRegistry(this.capabilities, - new RegistryEventHandlerWrapper(registryHandler, this), properties, getData(), + registryHandler, properties, getData(), getImplementationVersion(), applicationTag, credentials); } catch (IbisConfigurationException e) { throw e; } catch (Throwable e) { throw new IbisCreationFailedException("Could not create registry", e); } ident = registry.getIbisIdentifier(); if (properties.getBooleanProperty("ibis.vivaldi")) { try { vivaldiClient = new VivaldiClient(properties, registry); } catch (Exception e) { throw new IbisCreationFailedException( "Could not create vivaldi client", e); } } else { vivaldiClient = null; } if (properties.getBooleanProperty("ibis.bytescount")) { sentBytesPerIbis = new HashMap<ibis.ipl.IbisIdentifier, Long>(); receivedBytesPerIbis = new HashMap<ibis.ipl.IbisIdentifier, Long>(); } if (properties.getBooleanProperty("ibis.managementclient")) { try { managementClient = new ManagementClient(properties, this); } catch (Throwable e) { throw new IbisCreationFailedException( "Could not create management client", e); } } else { managementClient = null; } /* * // add bean to JMX try { MBeanServer mbs = * ManagementFactory.getPlatformMBeanServer(); ObjectName name = new * ObjectName("ibis.ipl.impl:type=Ibis"); mbs.registerMBean(this, name); * } catch (Exception e) { logger.warn("cannot registry MBean", e); } */ } void died(ibis.ipl.IbisIdentifier corpse) { killConnections(corpse); } void left(ibis.ipl.IbisIdentifier leftIbis) { killConnections(leftIbis); } protected void killConnections(ibis.ipl.IbisIdentifier corpse) { SendPort[] sps; ReceivePort[] rps; synchronized(this) { sps = sendPorts.values().toArray(new SendPort[sendPorts.size()]); rps = receivePorts.values().toArray(new ReceivePort[receivePorts.size()]); } for (SendPort s : sps) { s.killConnectionsWith(corpse); } for (ReceivePort p : rps) { p.killConnectionsWith(corpse); } } /** * Returns the current Ibis version. * * @return the ibis version. */ public String getVersion() { return starter.getNickName() + "-" + starter.getIplVersion(); } public ibis.ipl.Registry registry() { return registry; } public ibis.ipl.IbisIdentifier identifier() { return ident; } public Properties properties() { return new Properties(properties); } public void end() throws IOException { synchronized (this) { if (ended) { return; } ended = true; } try { registry.leave(); } catch (Throwable e) { throw new IbisIOException("Registry: leave failed ", e); } if (managementClient != null) { managementClient.end(); } if (vivaldiClient != null) { vivaldiClient.end(); } quit(); } public void poll() throws IOException { // Default has empty implementation. } synchronized void register(ReceivePort p) throws IOException { if (receivePorts.get(p.name) != null) { throw new IOException("Multiple instances of receiveport named " + p.name); } receivePorts.put(p.name, p); } synchronized void deRegister(ReceivePort p) { if (receivePorts.remove(p.name) != null) { // add statistics for this receive port to "total" statistics incomingMessageCount += p.getMessageCount(); bytesReceived += p.getBytesReceived(); bytesRead += p.getBytesRead(); } } synchronized void register(SendPort p) throws IOException { if (sendPorts.get(p.name) != null) { throw new IOException("Multiple instances of sendport named " + p.name); } sendPorts.put(p.name, p); } synchronized void deRegister(SendPort p) { if (sendPorts.remove(p.name) != null) { // add statistics for this sendport to "total" statistics outgoingMessageCount += p.getMessageCount(); bytesSent += p.getBytesSent(); bytesWritten += p.getBytesWritten(); } } synchronized void addSentPerIbis(long cnt, ibis.ipl.ReceivePortIdentifier[] idents) { if (sentBytesPerIbis == null) { return; } for (ibis.ipl.ReceivePortIdentifier rp : idents) { ibis.ipl.IbisIdentifier i = rp.ibisIdentifier(); Long oldval = sentBytesPerIbis.get(i); if (oldval != null) { cnt += oldval.longValue(); } sentBytesPerIbis.put(i, new Long(cnt)); } } synchronized void addReceivedPerIbis(long cnt, ibis.ipl.SendPortIdentifier[] idents) { if (receivedBytesPerIbis == null) { return; } for (ibis.ipl.SendPortIdentifier sp : idents) { ibis.ipl.IbisIdentifier i = sp.ibisIdentifier(); Long oldval = receivedBytesPerIbis.get(i); if (oldval != null) { cnt += oldval.longValue(); } receivedBytesPerIbis.put(i, new Long(cnt)); } } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Public methods, may called by Ibis implementations. // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /** * Returns the receiveport with the specified name, or <code>null</code> if * not present. * * @param name * the name of the receiveport. * @return the receiveport. */ public synchronized ReceivePort findReceivePort(String name) { return receivePorts.get(name); } /** * Returns the sendport with the specified name, or <code>null</code> if not * present. * * @param name * the name of the sendport. * @return the sendport. */ public synchronized SendPort findSendPort(String name) { return sendPorts.get(name); } public ReceivePortIdentifier createReceivePortIdentifier(String name, IbisIdentifier id) { return new ReceivePortIdentifier(name, id); } public SendPortIdentifier createSendPortIdentifier(String name, IbisIdentifier id) { return new SendPortIdentifier(name, id); } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Protected methods, to be implemented by Ibis implementations. // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /** * Implementation-dependent part of the {@link #end()} implementation. */ protected abstract void quit(); /** * This method should provide the implementation-dependent data of the Ibis * identifier for this Ibis instance. This method gets called from the Ibis * constructor. * * @exception IOException * may be thrown in case of trouble. * @return the implementation-dependent data, as a byte array. */ protected abstract byte[] getData() throws IOException; public ibis.ipl.SendPort createSendPort(PortType tp) throws IOException { return createSendPort(tp, null, null, null); } public ibis.ipl.SendPort createSendPort(PortType tp, String name) throws IOException { return createSendPort(tp, name, null, null); } private void matchPortType(PortType tp) { boolean matched = false; for (PortType p : portTypes) { if (tp.equals(p)) { matched = true; } } if (!matched) { throw new IbisConfigurationException("PortType \"" + tp + "\" not specified when creating this Ibis instance"); } } public ibis.ipl.SendPort createSendPort(PortType tp, String name, SendPortDisconnectUpcall cU, Properties properties) throws IOException { if (tp.hasCapability(PortType.CONNECTION_ULTRALIGHT)) { if (tp.hasCapability(PortType.CONNECTION_UPCALLS)) { throw new IbisConfigurationException( "Ultralight connections to not support connection upcalls"); } if (tp.hasCapability(PortType.COMMUNICATION_RELIABLE)) { throw new IbisConfigurationException( "Ultralight connections do not support reliability"); } if (tp.hasCapability(PortType.COMMUNICATION_FIFO)) { throw new IbisConfigurationException( "Ultralight connections do not support FIFO message ordering"); } } if (cU != null) { if (!tp.hasCapability(PortType.CONNECTION_UPCALLS)) { throw new IbisConfigurationException( "no connection upcalls requested for this port type"); } } if (name == null) { synchronized (this.getClass()) { name = "anonymous send port " + send_counter++; } } matchPortType(tp); return doCreateSendPort(tp, name, cU, properties); } /** * Creates a {@link ibis.ipl.SendPort} of the specified port type. * * @param tp * the port type. * @param name * the name of this sendport. * @param cU * object implementing the * {@link SendPortDisconnectUpcall#lostConnection(ibis.ipl.SendPort, ReceivePortIdentifier, Throwable)} * method. * @param properties * the port properties. * @return the new sendport. * @exception java.io.IOException * is thrown when the port could not be created. */ protected abstract ibis.ipl.SendPort doCreateSendPort(PortType tp, String name, SendPortDisconnectUpcall cU, Properties properties) throws IOException; public ibis.ipl.ReceivePort createReceivePort(PortType tp, String name) throws IOException { return createReceivePort(tp, name, null, null, null); } public ibis.ipl.ReceivePort createReceivePort(PortType tp, String name, MessageUpcall u) throws IOException { return createReceivePort(tp, name, u, null, null); } public ibis.ipl.ReceivePort createReceivePort(PortType tp, String name, ReceivePortConnectUpcall cU) throws IOException { return createReceivePort(tp, name, null, cU, null); } public ibis.ipl.ReceivePort createReceivePort(PortType tp, String name, MessageUpcall u, ReceivePortConnectUpcall cU, Properties properties) throws IOException { if (tp.hasCapability(PortType.CONNECTION_ULTRALIGHT)) { if (tp.hasCapability(PortType.CONNECTION_UPCALLS)) { throw new IbisConfigurationException( "Ultralight connections to not support connection upcalls"); } if (tp.hasCapability(PortType.COMMUNICATION_RELIABLE)) { throw new IbisConfigurationException( "Ultralight connections do not support reliability"); } if (tp.hasCapability(PortType.COMMUNICATION_FIFO)) { throw new IbisConfigurationException( "Ultralight connections do not support FIFO message ordering"); } } if (cU != null) { if (!tp.hasCapability(PortType.CONNECTION_UPCALLS)) { throw new IbisConfigurationException( "no connection upcalls requested for this port type"); } } if (u != null) { if (!tp.hasCapability(PortType.RECEIVE_AUTO_UPCALLS) && !tp.hasCapability(PortType.RECEIVE_POLL_UPCALLS)) { throw new IbisConfigurationException( "no message upcalls requested for this port type"); } } else { if (!tp.hasCapability(PortType.RECEIVE_EXPLICIT)) { throw new IbisConfigurationException( "no explicit receive requested for this port type"); } } if (name == null) { synchronized (this.getClass()) { name = "anonymous receive port " + receive_counter++; } } matchPortType(tp); return doCreateReceivePort(tp, name, u, cU, properties); } /** * Creates a named {@link ibis.ipl.ReceivePort} of the specified port type, * with upcall based communication. New connections will not be accepted * until {@link ibis.ipl.ReceivePort#enableConnections()} is invoked. This * is done to avoid upcalls during initialization. When a new connection * request arrives, or when a connection is lost, a ConnectUpcall is * performed. * * @param tp * the port type. * @param name * the name of this receiveport. * @param u * the upcall handler. * @param cU * object implementing <code>gotConnection</code>() and * <code>lostConnection</code>() upcalls. * @param properties * the port properties. * @return the new receiveport. * @exception java.io.IOException * is thrown when the port could not be created. */ protected abstract ibis.ipl.ReceivePort doCreateReceivePort(PortType tp, String name, MessageUpcall u, ReceivePortConnectUpcall cU, Properties properties) throws IOException; // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Protected management methods, can be overriden/used in implementations // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public String getManagementProperty(String key) throws NoSuchPropertyException { String result = managementProperties().get(key); if (result == null) { throw new NoSuchPropertyException("property \"" + key + "\" not found"); } return result; } public synchronized long getOutgoingMessageCount() { long outgoingMessageCount = this.outgoingMessageCount; // also add numbers for current send ports for (SendPort sendPort : sendPorts.values()) { outgoingMessageCount += sendPort.getMessageCount(); } return outgoingMessageCount; } public synchronized long getBytesSent() { long bytesSend = this.bytesSent; // also add numbers for current send ports for (SendPort sendPort : sendPorts.values()) { bytesSend += sendPort.getBytesSent(); } return bytesSend; } public synchronized long getBytesWritten() { long bytesWritten = this.bytesWritten; // also add numbers for current send ports for (SendPort sendPort : sendPorts.values()) { bytesWritten += sendPort.getBytesWritten(); } return bytesWritten; } public synchronized long getIncomingMessageCount() { long incomingMessageCount = this.incomingMessageCount; // also add numbers for current receive ports for (ReceivePort receivePort : receivePorts.values()) { incomingMessageCount += receivePort.getMessageCount(); } return incomingMessageCount; } public synchronized long getBytesReceived() { long bytesReceived = this.bytesReceived; // also add numbers for current receive ports for (ReceivePort receivePort : receivePorts.values()) { bytesReceived += receivePort.getBytesReceived(); } return bytesReceived; } public synchronized long getBytesRead() { long bytesRead = this.bytesRead; // also add numbers for current receive ports for (ReceivePort receivePort : receivePorts.values()) { bytesRead += receivePort.getBytesReceived(); } return bytesRead; } /** * @ibis.experimental */ public synchronized ibis.ipl.IbisIdentifier[] connectedTo() { HashSet<ibis.ipl.IbisIdentifier> result = new HashSet<ibis.ipl.IbisIdentifier>(); Collection<SendPort> ports = sendPorts.values(); for (SendPort sendPort : ports) { ibis.ipl.ReceivePortIdentifier[] receivePorts = sendPort .connectedTo(); for (ibis.ipl.ReceivePortIdentifier receivePort : receivePorts) { result.add(receivePort.ibisIdentifier()); } } return result.toArray(new ibis.ipl.IbisIdentifier[0]); } /** * @ibis.experimental */ public Coordinates getVivaldiCoordinates() { if (vivaldiClient == null) { return null; } return vivaldiClient.getCoordinates(); } /** * @ibis.experimental */ public synchronized Map<ibis.ipl.IbisIdentifier, Long> getSentBytesPerIbis() { if (sentBytesPerIbis == null) { return null; } return new HashMap<ibis.ipl.IbisIdentifier, Long>(sentBytesPerIbis); } /** * @ibis.experimental */ public synchronized Map<ibis.ipl.IbisIdentifier, Long> getReceivedBytesPerIbis() { if (receivedBytesPerIbis == null) { return null; } return new HashMap<ibis.ipl.IbisIdentifier, Long>(receivedBytesPerIbis); } /** * @ibis.experimental */ public String[] wonElections() { return registry.wonElections(); } /** * @ibis.experimental */ public synchronized Map<ibis.ipl.IbisIdentifier, Set<String>> getReceiverConnectionTypes() { Map<ibis.ipl.IbisIdentifier, Set<String>> result = new HashMap<ibis.ipl.IbisIdentifier, Set<String>>(); for (ReceivePort port : receivePorts.values()) { Map<IbisIdentifier, Set<String>> p = port.getConnectionTypes(); for (Entry<IbisIdentifier, Set<String>> entry : p.entrySet()) { Set<String> r = result.get(entry.getKey()); if (r == null) { r = new HashSet<String>(); } r.addAll(entry.getValue()); result.put(entry.getKey(), r); } } return result; } /** * @ibis.experimental */ public synchronized Map<ibis.ipl.IbisIdentifier, Set<String>> getSenderConnectionTypes() { Map<ibis.ipl.IbisIdentifier, Set<String>> result = new HashMap<ibis.ipl.IbisIdentifier, Set<String>>(); for (SendPort port : sendPorts.values()) { Map<IbisIdentifier, Set<String>> p = port.getConnectionTypes(); for (Entry<IbisIdentifier, Set<String>> entry : p.entrySet()) { Set<String> r = result.get(entry.getKey()); if (r == null) { r = new HashSet<String>(); } r.addAll(entry.getValue()); result.put(entry.getKey(), r); } } return result; } public synchronized Map<String, String> managementProperties() { Map<String, String> result = new HashMap<String, String>(); // put gathered statistics in the map result.put("outgoingMessageCount", "" + getOutgoingMessageCount()); result.put("bytesWritten", "" + getBytesWritten()); result.put("bytesSent", "" + getBytesSent()); result.put("incomingMessageCount", "" + getIncomingMessageCount()); result.put("bytesReceived", "" + getBytesReceived()); result.put("bytesRead", "" + getBytesRead()); return result; } public void printManagementProperties(PrintStream stream) { stream.format("Messages Sent: %d\n", getOutgoingMessageCount()); double mbWritten = getBytesWritten() / 1024.0 / 1024.0; stream.format("Data written to messages: %.2f Mb\n", mbWritten); double mbSent = getBytesSent() / 1024.0 / 1024.0; stream.format("Data sent out on network: %.2f Mb\n", mbSent); stream.format("Messages Received: %d\n", getIncomingMessageCount()); double mbReceived = getBytesReceived() / 1024.0 / 1024.0; stream.format("Data received from network: %.2f Mb\n", mbReceived); double mbRead = getBytesRead() / 1024.0 / 1024.0; stream.format("Data read from messages: %.2f Mb\n", mbRead); stream.flush(); } public void setManagementProperties(Map<String, String> properties) throws NoSuchPropertyException { // override if an Ibis _can_ set properties throw new NoSuchPropertyException("cannot set any properties"); } public void setManagementProperty(String key, String value) throws NoSuchPropertyException { // override if an Ibis _can_ set properties throw new NoSuchPropertyException("cannot set any properties"); } // jmx function public String getIdentifier() { return ident.toString(); } }
false
true
protected Ibis(RegistryEventHandler registryHandler, IbisCapabilities capabilities, Credentials credentials, byte[] applicationTag, PortType[] portTypes, Properties userProperties, IbisStarter starter) throws IbisCreationFailedException { if (capabilities == null) { throw new IbisConfigurationException("capabilities not specified"); } this.capabilities = capabilities; this.portTypes = portTypes; this.starter = starter; this.properties = new TypedProperties(); // bottom up add properties, starting with hard coded ones properties.addProperties(IbisProperties.getHardcodedProperties()); properties.addProperties(userProperties); // set unique ID for this Ibis. properties.setProperty(ID_PROPERTY, UUID.randomUUID().toString()); if (logger.isDebugEnabled()) { logger.debug("Ibis constructor: properties = " + properties); } receivePorts = new HashMap<String, ReceivePort>(); sendPorts = new HashMap<String, SendPort>(); try { registry = Registry.createRegistry(this.capabilities, new RegistryEventHandlerWrapper(registryHandler, this), properties, getData(), getImplementationVersion(), applicationTag, credentials); } catch (IbisConfigurationException e) { throw e; } catch (Throwable e) { throw new IbisCreationFailedException("Could not create registry", e); } ident = registry.getIbisIdentifier(); if (properties.getBooleanProperty("ibis.vivaldi")) { try { vivaldiClient = new VivaldiClient(properties, registry); } catch (Exception e) { throw new IbisCreationFailedException( "Could not create vivaldi client", e); } } else { vivaldiClient = null; } if (properties.getBooleanProperty("ibis.bytescount")) { sentBytesPerIbis = new HashMap<ibis.ipl.IbisIdentifier, Long>(); receivedBytesPerIbis = new HashMap<ibis.ipl.IbisIdentifier, Long>(); } if (properties.getBooleanProperty("ibis.managementclient")) { try { managementClient = new ManagementClient(properties, this); } catch (Throwable e) { throw new IbisCreationFailedException( "Could not create management client", e); } } else { managementClient = null; } /* * // add bean to JMX try { MBeanServer mbs = * ManagementFactory.getPlatformMBeanServer(); ObjectName name = new * ObjectName("ibis.ipl.impl:type=Ibis"); mbs.registerMBean(this, name); * } catch (Exception e) { logger.warn("cannot registry MBean", e); } */ }
protected Ibis(RegistryEventHandler registryHandler, IbisCapabilities capabilities, Credentials credentials, byte[] applicationTag, PortType[] portTypes, Properties userProperties, IbisStarter starter) throws IbisCreationFailedException { if (capabilities == null) { throw new IbisConfigurationException("capabilities not specified"); } this.capabilities = capabilities; this.portTypes = portTypes; this.starter = starter; this.properties = new TypedProperties(); // bottom up add properties, starting with hard coded ones properties.addProperties(IbisProperties.getHardcodedProperties()); properties.addProperties(userProperties); // set unique ID for this Ibis. properties.setProperty(ID_PROPERTY, UUID.randomUUID().toString()); if (logger.isDebugEnabled()) { logger.debug("Ibis constructor: properties = " + properties); } receivePorts = new HashMap<String, ReceivePort>(); sendPorts = new HashMap<String, SendPort>(); if (registryHandler != null) { // Only install wrapper if user actually has an event handler. // Otherwise, registry downcalls won't work. There needs to be another // way to let an Ibis know of died Ibises. --Ceriel registryHandler = new RegistryEventHandlerWrapper(registryHandler, this); } try { registry = Registry.createRegistry(this.capabilities, registryHandler, properties, getData(), getImplementationVersion(), applicationTag, credentials); } catch (IbisConfigurationException e) { throw e; } catch (Throwable e) { throw new IbisCreationFailedException("Could not create registry", e); } ident = registry.getIbisIdentifier(); if (properties.getBooleanProperty("ibis.vivaldi")) { try { vivaldiClient = new VivaldiClient(properties, registry); } catch (Exception e) { throw new IbisCreationFailedException( "Could not create vivaldi client", e); } } else { vivaldiClient = null; } if (properties.getBooleanProperty("ibis.bytescount")) { sentBytesPerIbis = new HashMap<ibis.ipl.IbisIdentifier, Long>(); receivedBytesPerIbis = new HashMap<ibis.ipl.IbisIdentifier, Long>(); } if (properties.getBooleanProperty("ibis.managementclient")) { try { managementClient = new ManagementClient(properties, this); } catch (Throwable e) { throw new IbisCreationFailedException( "Could not create management client", e); } } else { managementClient = null; } /* * // add bean to JMX try { MBeanServer mbs = * ManagementFactory.getPlatformMBeanServer(); ObjectName name = new * ObjectName("ibis.ipl.impl:type=Ibis"); mbs.registerMBean(this, name); * } catch (Exception e) { logger.warn("cannot registry MBean", e); } */ }
diff --git a/plugins/org.eclipse.acceleo.parser/src/org/eclipse/acceleo/internal/parser/ast/ocl/environment/AcceleoUMLReflection.java b/plugins/org.eclipse.acceleo.parser/src/org/eclipse/acceleo/internal/parser/ast/ocl/environment/AcceleoUMLReflection.java index 486dc7dd..9ef6d1b1 100644 --- a/plugins/org.eclipse.acceleo.parser/src/org/eclipse/acceleo/internal/parser/ast/ocl/environment/AcceleoUMLReflection.java +++ b/plugins/org.eclipse.acceleo.parser/src/org/eclipse/acceleo/internal/parser/ast/ocl/environment/AcceleoUMLReflection.java @@ -1,641 +1,642 @@ /******************************************************************************* * Copyright (c) 2009, 2011 Obeo. * 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: * Obeo - initial API and implementation *******************************************************************************/ package org.eclipse.acceleo.internal.parser.ast.ocl.environment; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EEnumLiteral; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EOperation; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EParameter; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.ocl.ecore.CallOperationAction; import org.eclipse.ocl.ecore.Constraint; import org.eclipse.ocl.ecore.SendSignalAction; import org.eclipse.ocl.utilities.ExpressionInOCL; import org.eclipse.ocl.utilities.TypedElement; /** * This implementation of an {@link org.eclipse.ocl.utilities.UMLReflection} allows us to remove the method * {@link org.eclipse.emf.ecore.EObject#eAllContents()} from the context. * * @author <a href="mailto:[email protected]">Laurent Goubet</a> */ public class AcceleoUMLReflection implements org.eclipse.ocl.utilities.UMLReflection<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> { /** Keeps a reference to the {@link org.eclipse.emf.ecore.EObject#eAllContents()} method. */ private static final EOperation EOBJECT_EALLCONTENTS; /** We will delegate all calls to this implementation. */ protected final org.eclipse.ocl.utilities.UMLReflection<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> delegate; static { EOperation temp = null; final EClass eObject = EcorePackage.eINSTANCE.getEObject(); for (EOperation operation : eObject.getEOperations()) { if ("eAllContents".equals(operation.getName()) //$NON-NLS-1$ && operation.getEType() == EcorePackage.eINSTANCE.getETreeIterator()) { temp = operation; break; } } EOBJECT_EALLCONTENTS = temp; } /** * Instantiates an UML Reflection given the one to which all calls are to be redirected. * * @param delegate * The UML Reflection to which calls are to be redirected. */ public AcceleoUMLReflection( org.eclipse.ocl.utilities.UMLReflection<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint> delegate) { super(); this.delegate = delegate; } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#asOCLType(java.lang.Object) */ public EClassifier asOCLType(EClassifier modelType) { return delegate.asOCLType(modelType); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#createCallOperationAction(java.lang.Object) */ public CallOperationAction createCallOperationAction(EOperation operation) { return delegate.createCallOperationAction(operation); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#createConstraint() */ public Constraint createConstraint() { return delegate.createConstraint(); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#createExpressionInOCL() */ public ExpressionInOCL<EClassifier, EParameter> createExpressionInOCL() { return delegate.createExpressionInOCL(); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#createOperation(java.lang.String, java.lang.Object, * java.util.List, java.util.List) */ public EOperation createOperation(String name, EClassifier resultType, List<String> paramNames, List<EClassifier> paramTypes) { return delegate.createOperation(name, resultType, paramNames, paramTypes); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#createProperty(java.lang.String, java.lang.Object) */ public EStructuralFeature createProperty(String name, EClassifier resultType) { return delegate.createProperty(name, resultType); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#createSendSignalAction(java.lang.Object) */ public SendSignalAction createSendSignalAction(EClassifier signal) { return delegate.createSendSignalAction(signal); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getAllSupertypes(java.lang.Object) */ public Collection<? extends EClassifier> getAllSupertypes(EClassifier classifier) { return delegate.getAllSupertypes(classifier); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getAssociationClass(java.lang.Object) */ public EClassifier getAssociationClass(EStructuralFeature property) { return delegate.getAssociationClass(property); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getAttributes(java.lang.Object) */ public List<EStructuralFeature> getAttributes(EClassifier classifier) { return delegate.getAttributes(classifier); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getClassifiers(java.lang.Object) */ public List<EClassifier> getClassifiers(EPackage pkg) { return delegate.getClassifiers(pkg); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getCommonSuperType(java.lang.Object, java.lang.Object) */ public EClassifier getCommonSuperType(EClassifier type1, EClassifier type2) { return delegate.getCommonSuperType(type1, type2); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getConstrainedElements(java.lang.Object) */ @SuppressWarnings({"rawtypes", "unchecked" }) /* * !Do not use generics on the return type of this override, API broke between OCL 1.2 and 3.0 and we * can't cope with both while maintaining a generic signature! */ public List getConstrainedElements(Constraint constraint) { return delegate.getConstrainedElements(constraint); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getConstraint(org.eclipse.ocl.utilities.ExpressionInOCL) */ public Constraint getConstraint(ExpressionInOCL<EClassifier, EParameter> specification) { return delegate.getConstraint(specification); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getConstraintName(java.lang.Object) */ public String getConstraintName(Constraint constraint) { return delegate.getConstraintName(constraint); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getDescription(java.lang.Object) */ public String getDescription(Object namedElement) { return delegate.getDescription(namedElement); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getEnumeration(java.lang.Object) */ public EClassifier getEnumeration(EEnumLiteral enumerationLiteral) { return delegate.getEnumeration(enumerationLiteral); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getEnumerationLiteral(java.lang.Object, java.lang.String) */ public EEnumLiteral getEnumerationLiteral(EClassifier enumerationType, String literalName) { return delegate.getEnumerationLiteral(enumerationType, literalName); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getEnumerationLiterals(java.lang.Object) */ public List<EEnumLiteral> getEnumerationLiterals(EClassifier enumerationType) { return delegate.getEnumerationLiterals(enumerationType); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getMemberEnds(java.lang.Object) */ public List<EStructuralFeature> getMemberEnds(EClassifier associationClass) { return delegate.getMemberEnds(associationClass); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getName(java.lang.Object) */ public String getName(Object namedElement) { return delegate.getName(namedElement); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getNestedPackages(java.lang.Object) */ public List<EPackage> getNestedPackages(EPackage pkg) { return delegate.getNestedPackages(pkg); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getNestingPackage(java.lang.Object) */ public EPackage getNestingPackage(EPackage pkg) { return delegate.getNestingPackage(pkg); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getOCLType(java.lang.Object) */ public EClassifier getOCLType(Object metaElement) { return delegate.getOCLType(metaElement); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getOperation(java.lang.Object) */ public EOperation getOperation(CallOperationAction callOperationAction) { return delegate.getOperation(callOperationAction); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getOperations(java.lang.Object) */ public synchronized List<EOperation> getOperations(EClassifier classifier) { final List<EOperation> operations = new ArrayList<EOperation>(delegate.getOperations(classifier)); operations.remove(EOBJECT_EALLCONTENTS); return operations; } /** * Obtains all of the operations going by the given name that are defined by the specified classifier. * This should always be preferred to {@link #getOperations(EClassifier)}. * <p> * Base implementation copied from org.eclipse.ocl.utilities.UMLReflection. * </p> * * @param classifier * A classifier in the model. * @param name * The name filter for the classifier's operations. * @return The operations applicable to the specified classifier, or an empty list if none. * @see org.eclipse.ocl.utilities.UMLReflection#getOperations(EClassifier) */ public synchronized List<EOperation> getOperations(EClassifier classifier, String name) { final List<EOperation> result = new ArrayList<EOperation>(); if (classifier instanceof EClass) { - final List<EOperation> candidates = ((EClass)classifier).getEOperations(); + final List<EOperation> candidates = new ArrayList<EOperation>(((EClass)classifier) + .getEOperations()); for (EOperation candidate : candidates) { if (name.equals(candidate.getName())) { result.add(candidate); } } } return result; } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getOwningClassifier(java.lang.Object) */ public EClassifier getOwningClassifier(Object feature) { return delegate.getOwningClassifier(feature); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getPackage(java.lang.Object) */ public EPackage getPackage(EClassifier classifier) { return delegate.getPackage(classifier); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getParameters(java.lang.Object) */ public List<EParameter> getParameters(EOperation operation) { return delegate.getParameters(operation); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getQualifiedName(java.lang.Object) */ public String getQualifiedName(Object namedElement) { return delegate.getQualifiedName(namedElement); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getQualifiers(java.lang.Object) */ public List<EStructuralFeature> getQualifiers(EStructuralFeature property) { return delegate.getQualifiers(property); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getRelationship(java.lang.Object, java.lang.Object) */ public int getRelationship(EClassifier type1, EClassifier type2) { return delegate.getRelationship(type1, type2); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getSignal(java.lang.Object) */ public EClassifier getSignal(SendSignalAction sendSignalAction) { return delegate.getSignal(sendSignalAction); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getSignals(java.lang.Object) */ public List<EClassifier> getSignals(EClassifier owner) { return delegate.getSignals(owner); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getSpecification(java.lang.Object) */ public ExpressionInOCL<EClassifier, EParameter> getSpecification(Constraint constraint) { return delegate.getSpecification(constraint); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getStereotype(java.lang.Object) */ public String getStereotype(Constraint constraint) { return delegate.getStereotype(constraint); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#getStereotypeApplication(java.lang.Object, * java.lang.Object) */ public Object getStereotypeApplication(Object baseElement, EClassifier stereotype) { return delegate.getStereotypeApplication(baseElement, stereotype); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isAssociationClass(java.lang.Object) */ public boolean isAssociationClass(EClassifier type) { return delegate.isAssociationClass(type); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isClass(java.lang.Object) */ public boolean isClass(Object metaElement) { return delegate.isClass(metaElement); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isClassifier(java.lang.Object) */ public boolean isClassifier(Object metaElement) { return delegate.isClassifier(metaElement); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isComparable(java.lang.Object) */ public boolean isComparable(EClassifier type) { return delegate.isComparable(type); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isConstraint(java.lang.Object) */ public boolean isConstraint(Object metaElement) { // should never be called as it appeared in helios and will then be overriden assert false; return false; } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isDataType(java.lang.Object) */ public boolean isDataType(Object metaElement) { return delegate.isDataType(metaElement); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isEnumeration(java.lang.Object) */ public boolean isEnumeration(EClassifier type) { return delegate.isEnumeration(type); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isMany(java.lang.Object) */ public boolean isMany(Object metaElement) { return delegate.isMany(metaElement); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isOperation(java.lang.Object) */ public boolean isOperation(Object metaElement) { return delegate.isOperation(metaElement); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isPackage(java.lang.Object) */ public boolean isPackage(Object metaElement) { // should never be called as it appeared in helios and will then be overriden assert false; return false; } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isProperty(java.lang.Object) */ public boolean isProperty(Object metaElement) { return delegate.isProperty(metaElement); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isQuery(java.lang.Object) */ public boolean isQuery(EOperation operation) { return delegate.isQuery(operation); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isStatic(java.lang.Object) */ public boolean isStatic(Object feature) { return delegate.isStatic(feature); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#isStereotype(java.lang.Object) */ public boolean isStereotype(EClassifier type) { return delegate.isStereotype(type); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#setConstraintName(java.lang.Object, java.lang.String) */ public void setConstraintName(Constraint constraint, String name) { delegate.setConstraintName(constraint, name); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#setIsStatic(java.lang.Object, boolean) */ public boolean setIsStatic(Object feature, boolean isStatic) { // should never be called as it appeared in helios and will then be overriden assert false; return false; } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#setName(org.eclipse.ocl.utilities.TypedElement, * java.lang.String) */ public void setName(TypedElement<EClassifier> element, String name) { delegate.setName(element, name); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#setSpecification(java.lang.Object, * org.eclipse.ocl.utilities.ExpressionInOCL) */ public void setSpecification(Constraint constraint, ExpressionInOCL<EClassifier, EParameter> specification) { delegate.setSpecification(constraint, specification); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#setStereotype(java.lang.Object, java.lang.String) */ public void setStereotype(Constraint constraint, String stereotype) { delegate.setStereotype(constraint, stereotype); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#setType(org.eclipse.ocl.utilities.TypedElement, * java.lang.Object) */ public void setType(TypedElement<EClassifier> element, EClassifier type) { delegate.setType(element, type); } /** * {@inheritDoc} * * @see org.eclipse.ocl.utilities.UMLReflection#addConstrainedElement(java.lang.Object, * org.eclipse.emf.ecore.EObject) */ public void addConstrainedElement(Constraint constraint, EObject constrainedElement) { // should never be called as it appeared in helios and will then be overriden assert false; } }
true
true
public synchronized List<EOperation> getOperations(EClassifier classifier, String name) { final List<EOperation> result = new ArrayList<EOperation>(); if (classifier instanceof EClass) { final List<EOperation> candidates = ((EClass)classifier).getEOperations(); for (EOperation candidate : candidates) { if (name.equals(candidate.getName())) { result.add(candidate); } } } return result; }
public synchronized List<EOperation> getOperations(EClassifier classifier, String name) { final List<EOperation> result = new ArrayList<EOperation>(); if (classifier instanceof EClass) { final List<EOperation> candidates = new ArrayList<EOperation>(((EClass)classifier) .getEOperations()); for (EOperation candidate : candidates) { if (name.equals(candidate.getName())) { result.add(candidate); } } } return result; }
diff --git a/CalcESTv4/src/controller/Berechnungen.java b/CalcESTv4/src/controller/Berechnungen.java index 9fd14fb..b0603a7 100644 --- a/CalcESTv4/src/controller/Berechnungen.java +++ b/CalcESTv4/src/controller/Berechnungen.java @@ -1,42 +1,42 @@ package controller; public class Berechnungen { public static double SummeEinkunft(double JahresBruttoLohn, double WerbungsKosten) { double SummeEinkunft = JahresBruttoLohn - WerbungsKosten; return Math.round(SummeEinkunft * 100.00) / 100.00; } public static double WerbungsKosten(int ArbeitsTage, double EntfernungWA, double ArbeitsMittelGezahlt, double TelefonKostenGezahlt) { double ENTFERNUNGSPAUSCHALE = 0.3; double WerbungsKostenAbzug = 0.0; double ArbeitsMittelAbzug = 0.0; double TelefonKostenAbzug = 0.0; double WerbungsKostenGezahlt = 0.0; if (ArbeitsMittelGezahlt <= 110.0) { - ArbeitsMittelAbzug = ArbeitsMittelGezahlt; + ArbeitsMittelAbzug = 110.0; } else { ArbeitsMittelAbzug = Math.round(ArbeitsMittelGezahlt * 100.00) / 100.00; } if (TelefonKostenGezahlt <= 240.0) { - TelefonKostenAbzug = TelefonKostenGezahlt; + TelefonKostenAbzug = 240.0; } else { TelefonKostenAbzug = Math.round(TelefonKostenGezahlt * 100.00) / 100.00; } WerbungsKostenGezahlt = Math.round(((ArbeitsTage * EntfernungWA * ENTFERNUNGSPAUSCHALE) + ArbeitsMittelGezahlt + TelefonKostenGezahlt) * 100.00) / 100.00; if (WerbungsKostenGezahlt <= 1000.0) { WerbungsKostenAbzug = 1000.0; } else { WerbungsKostenAbzug = Math.round(WerbungsKostenGezahlt * 100.00) / 100.00; } return Math.round(WerbungsKostenAbzug * 100.00) / 100.00; } }
false
true
public static double WerbungsKosten(int ArbeitsTage, double EntfernungWA, double ArbeitsMittelGezahlt, double TelefonKostenGezahlt) { double ENTFERNUNGSPAUSCHALE = 0.3; double WerbungsKostenAbzug = 0.0; double ArbeitsMittelAbzug = 0.0; double TelefonKostenAbzug = 0.0; double WerbungsKostenGezahlt = 0.0; if (ArbeitsMittelGezahlt <= 110.0) { ArbeitsMittelAbzug = ArbeitsMittelGezahlt; } else { ArbeitsMittelAbzug = Math.round(ArbeitsMittelGezahlt * 100.00) / 100.00; } if (TelefonKostenGezahlt <= 240.0) { TelefonKostenAbzug = TelefonKostenGezahlt; } else { TelefonKostenAbzug = Math.round(TelefonKostenGezahlt * 100.00) / 100.00; } WerbungsKostenGezahlt = Math.round(((ArbeitsTage * EntfernungWA * ENTFERNUNGSPAUSCHALE) + ArbeitsMittelGezahlt + TelefonKostenGezahlt) * 100.00) / 100.00; if (WerbungsKostenGezahlt <= 1000.0) { WerbungsKostenAbzug = 1000.0; } else { WerbungsKostenAbzug = Math.round(WerbungsKostenGezahlt * 100.00) / 100.00; } return Math.round(WerbungsKostenAbzug * 100.00) / 100.00; }
public static double WerbungsKosten(int ArbeitsTage, double EntfernungWA, double ArbeitsMittelGezahlt, double TelefonKostenGezahlt) { double ENTFERNUNGSPAUSCHALE = 0.3; double WerbungsKostenAbzug = 0.0; double ArbeitsMittelAbzug = 0.0; double TelefonKostenAbzug = 0.0; double WerbungsKostenGezahlt = 0.0; if (ArbeitsMittelGezahlt <= 110.0) { ArbeitsMittelAbzug = 110.0; } else { ArbeitsMittelAbzug = Math.round(ArbeitsMittelGezahlt * 100.00) / 100.00; } if (TelefonKostenGezahlt <= 240.0) { TelefonKostenAbzug = 240.0; } else { TelefonKostenAbzug = Math.round(TelefonKostenGezahlt * 100.00) / 100.00; } WerbungsKostenGezahlt = Math.round(((ArbeitsTage * EntfernungWA * ENTFERNUNGSPAUSCHALE) + ArbeitsMittelGezahlt + TelefonKostenGezahlt) * 100.00) / 100.00; if (WerbungsKostenGezahlt <= 1000.0) { WerbungsKostenAbzug = 1000.0; } else { WerbungsKostenAbzug = Math.round(WerbungsKostenGezahlt * 100.00) / 100.00; } return Math.round(WerbungsKostenAbzug * 100.00) / 100.00; }
diff --git a/src/main/java/com/lebelw/Tickets/commands/TemplateCmd.java b/src/main/java/com/lebelw/Tickets/commands/TemplateCmd.java index 9f3cecd..e3ead79 100644 --- a/src/main/java/com/lebelw/Tickets/commands/TemplateCmd.java +++ b/src/main/java/com/lebelw/Tickets/commands/TemplateCmd.java @@ -1,335 +1,337 @@ package com.lebelw.Tickets.commands; import java.sql.ResultSet; import java.sql.SQLException; import com.lebelw.Tickets.TDatabase; import com.lebelw.Tickets.TLogger; import com.lebelw.Tickets.TPermissions; import com.lebelw.Tickets.TTools; import com.lebelw.Tickets.Tickets; import com.lebelw.Tickets.extras.DataManager; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandException; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** * @description Handles a command. * @author Tagette */ public class TemplateCmd implements CommandExecutor { private final Tickets plugin; DataManager dbm = TDatabase.dbm; Player target; int currentticket, ticketarg, amount; public TemplateCmd(Tickets instance) { plugin = instance; } public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { boolean handled = false; if (is(label, "ticket")) { if (args == null || args.length == 0) { handled = true; if (isPlayer(sender)){ String name = getName(sender); try{ ResultSet result = dbm.query("SELECT ticket FROM players WHERE name='" + name + "'"); if (result != null && result.next()){ sendMessage(sender,colorizeText("You have ",ChatColor.GREEN) + result.getInt("ticket") + colorizeText(" ticket(s).",ChatColor.GREEN)); } else sendMessage(sender,colorizeText("You have 0 ticket",ChatColor.RED)); } catch (SQLException se) { TLogger.error(se.getMessage()); } } } else { //Is the first argument give? if (is(args[0],"help")){ handled = true; sendMessage(sender, "You are using " + colorizeText(Tickets.name, ChatColor.GREEN) + " version " + colorizeText(Tickets.version, ChatColor.GREEN) + "."); sendMessage(sender, "Commands:"); if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){ sendMessage(sender,colorizeText("/ticket give <Name> <Amount>",ChatColor.YELLOW) +" - Give ticket to semeone"); } if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){ sendMessage(sender,colorizeText("/ticket take <Name> <Amount>",ChatColor.YELLOW) +" - Take ticket to semeone"); } } else if (is(args[0],"send")){ handled = true; if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.send", getPlayer(sender).isOp())){ if (args.length == 1 || args.length == 2){ sendMessage(sender,colorizeText("/ticket send <Name> <Amount>",ChatColor.YELLOW) +" - Send ticket to semeone"); return handled; } if (!TTools.isInt(args[1])){ if (TTools.isInt(args[2])){ String sendername = ((Player)sender).getName(); String name = args[1]; try { target = plugin.matchSinglePlayer(sender, name); if (target.getName() != null){ name = target.getName(); } }catch (CommandException error){ sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED)); return handled; } ticketarg = Integer.parseInt(args[2]); if (checkIfPlayerExists(sendername)){ currentticket = getPlayerTicket(sendername); amount = currentticket - ticketarg; if (amount < 0){ sendMessage(sender,colorizeText("You online have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)! You can't send ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)!",ChatColor.RED)); + return handled; } if (givePlayerTicket(name,ticketarg)){ dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'"); sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN)); if (target.getName() != null){ sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN)); } } }else{ sendMessage(sender,colorizeText("You can't send ticket(s) because you don't have any!",ChatColor.RED)); } }else{ sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED)); } }else { sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED)); } }else{ sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED)); } } else if(is(args[0],"give")){ handled = true; //We check the guy permission if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){ //We check if we received a string for the first parameter (Player) if (args[1] != null && !TTools.isInt(args[1])){ //We check if we received a int for the second parameter (Amount) if (args[2] != null && TTools.isInt(args[2])){ String name = args[1]; try { target = plugin.matchSinglePlayer(sender, name); if (target.getName() != null){ name = target.getName(); } }catch (CommandException error){ sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED)); return handled; } ticketarg = Integer.parseInt(args[2]); if (givePlayerTicket(name,ticketarg)){ sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN)); if (target.getName() != null){ sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN)); } }else{ sendMessage(sender,colorizeText("A error occured",ChatColor.GREEN)); } } else{ sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED)); } } //Is the first argument take? else if(is(args[0],"take")){ handled = true; if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){ //We check if we received a string for the first parameter (Player) if (args[1] != null && !TTools.isInt(args[1])){ //We check if we received a int for the second parameter (Amount) if (args[2] != null && TTools.isInt(args[2])){ String name = args[1]; try { target = plugin.matchSinglePlayer(sender, name); if (target.getName() != null){ name = target.getName(); } }catch (CommandException error){ sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED)); return handled; } ticketarg = Integer.parseInt(args[2]); if (checkIfPlayerExists(name)){ currentticket = getPlayerTicket(name); amount = currentticket - ticketarg; if (amount < 0){ sendMessage(sender,colorizeText("You can't remove ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)! This player only have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)!",ChatColor.RED)); + return handled; } dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'"); }else{ sendMessage(sender,colorizeText("You can't remove tickets to " + name + " because he doesn't have any!",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED)); } } } } return handled; } // Simplifies and shortens the if statements for commands. private boolean is(String entered, String label) { return entered.equalsIgnoreCase(label); } // Checks if the current user is actually a player. private boolean isPlayer(CommandSender sender) { return sender != null && sender instanceof Player; } // Checks if the current user is actually a player and sends a message to that player. private boolean sendMessage(CommandSender sender, String message) { boolean sent = false; if (isPlayer(sender)) { Player player = (Player) sender; player.sendMessage(message); sent = true; } return sent; } private boolean sendLog(CommandSender sender, String message) { boolean sent = false; if (!isPlayer(sender)) { TLogger.info(message); sent = true; } return sent; } // Checks if the current user is actually a player and returns the name of that player. private String getName(CommandSender sender) { String name = ""; if (isPlayer(sender)) { Player player = (Player) sender; name = player.getName(); } return name; } // Gets the player if the current user is actually a player. private Player getPlayer(CommandSender sender) { Player player = null; if (isPlayer(sender)) { player = (Player) sender; } return player; } private String colorizeText(String text, ChatColor color) { return color + text + ChatColor.WHITE; } /* * Checks if a player account exists * * @param name The full name of the player. */ private boolean checkIfPlayerExists(String name) { ResultSet result = dbm.query("SELECT id FROM players WHERE name = '" + name + "'"); try { if (result != null && result.next()){ return true; } } catch (SQLException e) { // TODO Auto-generated catch block TLogger.warning(e.getMessage()); return false; } return false; } /* * Get the amount of tickets a player have * * @param name The full name of the player. */ private int getPlayerTicket(String name){ ResultSet result = dbm.query("SELECT ticket FROM players WHERE name = '" + name + "'"); try { if (result != null && result.next()){ return result.getInt("Ticket"); } } catch (SQLException e) { // TODO Auto-generated catch block TLogger.warning(e.getMessage()); return 0; } return 0; } /* * Create a player ticket account * * @param name The full name of the player. */ private boolean createPlayerTicketAccount(String name){ if (!checkIfPlayerExists(name)){ if(dbm.insert("INSERT INTO players(name) VALUES('" + name + "')")){ return true; }else{ return false; } }else{ return false; } } private boolean givePlayerTicket(String name, Integer amount){ if (checkIfPlayerExists(name)){ currentticket = getPlayerTicket(name); amount = currentticket + amount; return dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'"); }else{ if (createPlayerTicketAccount(name)){ return dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'"); }else{ return false; } } } }
false
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { boolean handled = false; if (is(label, "ticket")) { if (args == null || args.length == 0) { handled = true; if (isPlayer(sender)){ String name = getName(sender); try{ ResultSet result = dbm.query("SELECT ticket FROM players WHERE name='" + name + "'"); if (result != null && result.next()){ sendMessage(sender,colorizeText("You have ",ChatColor.GREEN) + result.getInt("ticket") + colorizeText(" ticket(s).",ChatColor.GREEN)); } else sendMessage(sender,colorizeText("You have 0 ticket",ChatColor.RED)); } catch (SQLException se) { TLogger.error(se.getMessage()); } } } else { //Is the first argument give? if (is(args[0],"help")){ handled = true; sendMessage(sender, "You are using " + colorizeText(Tickets.name, ChatColor.GREEN) + " version " + colorizeText(Tickets.version, ChatColor.GREEN) + "."); sendMessage(sender, "Commands:"); if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){ sendMessage(sender,colorizeText("/ticket give <Name> <Amount>",ChatColor.YELLOW) +" - Give ticket to semeone"); } if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){ sendMessage(sender,colorizeText("/ticket take <Name> <Amount>",ChatColor.YELLOW) +" - Take ticket to semeone"); } } else if (is(args[0],"send")){ handled = true; if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.send", getPlayer(sender).isOp())){ if (args.length == 1 || args.length == 2){ sendMessage(sender,colorizeText("/ticket send <Name> <Amount>",ChatColor.YELLOW) +" - Send ticket to semeone"); return handled; } if (!TTools.isInt(args[1])){ if (TTools.isInt(args[2])){ String sendername = ((Player)sender).getName(); String name = args[1]; try { target = plugin.matchSinglePlayer(sender, name); if (target.getName() != null){ name = target.getName(); } }catch (CommandException error){ sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED)); return handled; } ticketarg = Integer.parseInt(args[2]); if (checkIfPlayerExists(sendername)){ currentticket = getPlayerTicket(sendername); amount = currentticket - ticketarg; if (amount < 0){ sendMessage(sender,colorizeText("You online have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)! You can't send ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)!",ChatColor.RED)); } if (givePlayerTicket(name,ticketarg)){ dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'"); sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN)); if (target.getName() != null){ sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN)); } } }else{ sendMessage(sender,colorizeText("You can't send ticket(s) because you don't have any!",ChatColor.RED)); } }else{ sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED)); } }else { sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED)); } }else{ sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED)); } } else if(is(args[0],"give")){ handled = true; //We check the guy permission if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){ //We check if we received a string for the first parameter (Player) if (args[1] != null && !TTools.isInt(args[1])){ //We check if we received a int for the second parameter (Amount) if (args[2] != null && TTools.isInt(args[2])){ String name = args[1]; try { target = plugin.matchSinglePlayer(sender, name); if (target.getName() != null){ name = target.getName(); } }catch (CommandException error){ sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED)); return handled; } ticketarg = Integer.parseInt(args[2]); if (givePlayerTicket(name,ticketarg)){ sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN)); if (target.getName() != null){ sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN)); } }else{ sendMessage(sender,colorizeText("A error occured",ChatColor.GREEN)); } } else{ sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED)); } } //Is the first argument take? else if(is(args[0],"take")){ handled = true; if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){ //We check if we received a string for the first parameter (Player) if (args[1] != null && !TTools.isInt(args[1])){ //We check if we received a int for the second parameter (Amount) if (args[2] != null && TTools.isInt(args[2])){ String name = args[1]; try { target = plugin.matchSinglePlayer(sender, name); if (target.getName() != null){ name = target.getName(); } }catch (CommandException error){ sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED)); return handled; } ticketarg = Integer.parseInt(args[2]); if (checkIfPlayerExists(name)){ currentticket = getPlayerTicket(name); amount = currentticket - ticketarg; if (amount < 0){ sendMessage(sender,colorizeText("You can't remove ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)! This player only have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)!",ChatColor.RED)); } dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'"); }else{ sendMessage(sender,colorizeText("You can't remove tickets to " + name + " because he doesn't have any!",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED)); } } } } return handled; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { boolean handled = false; if (is(label, "ticket")) { if (args == null || args.length == 0) { handled = true; if (isPlayer(sender)){ String name = getName(sender); try{ ResultSet result = dbm.query("SELECT ticket FROM players WHERE name='" + name + "'"); if (result != null && result.next()){ sendMessage(sender,colorizeText("You have ",ChatColor.GREEN) + result.getInt("ticket") + colorizeText(" ticket(s).",ChatColor.GREEN)); } else sendMessage(sender,colorizeText("You have 0 ticket",ChatColor.RED)); } catch (SQLException se) { TLogger.error(se.getMessage()); } } } else { //Is the first argument give? if (is(args[0],"help")){ handled = true; sendMessage(sender, "You are using " + colorizeText(Tickets.name, ChatColor.GREEN) + " version " + colorizeText(Tickets.version, ChatColor.GREEN) + "."); sendMessage(sender, "Commands:"); if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){ sendMessage(sender,colorizeText("/ticket give <Name> <Amount>",ChatColor.YELLOW) +" - Give ticket to semeone"); } if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){ sendMessage(sender,colorizeText("/ticket take <Name> <Amount>",ChatColor.YELLOW) +" - Take ticket to semeone"); } } else if (is(args[0],"send")){ handled = true; if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.send", getPlayer(sender).isOp())){ if (args.length == 1 || args.length == 2){ sendMessage(sender,colorizeText("/ticket send <Name> <Amount>",ChatColor.YELLOW) +" - Send ticket to semeone"); return handled; } if (!TTools.isInt(args[1])){ if (TTools.isInt(args[2])){ String sendername = ((Player)sender).getName(); String name = args[1]; try { target = plugin.matchSinglePlayer(sender, name); if (target.getName() != null){ name = target.getName(); } }catch (CommandException error){ sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED)); return handled; } ticketarg = Integer.parseInt(args[2]); if (checkIfPlayerExists(sendername)){ currentticket = getPlayerTicket(sendername); amount = currentticket - ticketarg; if (amount < 0){ sendMessage(sender,colorizeText("You online have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)! You can't send ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)!",ChatColor.RED)); return handled; } if (givePlayerTicket(name,ticketarg)){ dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'"); sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN)); if (target.getName() != null){ sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN)); } } }else{ sendMessage(sender,colorizeText("You can't send ticket(s) because you don't have any!",ChatColor.RED)); } }else{ sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED)); } }else { sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED)); } }else{ sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED)); } } else if(is(args[0],"give")){ handled = true; //We check the guy permission if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){ //We check if we received a string for the first parameter (Player) if (args[1] != null && !TTools.isInt(args[1])){ //We check if we received a int for the second parameter (Amount) if (args[2] != null && TTools.isInt(args[2])){ String name = args[1]; try { target = plugin.matchSinglePlayer(sender, name); if (target.getName() != null){ name = target.getName(); } }catch (CommandException error){ sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED)); return handled; } ticketarg = Integer.parseInt(args[2]); if (givePlayerTicket(name,ticketarg)){ sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN)); if (target.getName() != null){ sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN)); } }else{ sendMessage(sender,colorizeText("A error occured",ChatColor.GREEN)); } } else{ sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED)); } } //Is the first argument take? else if(is(args[0],"take")){ handled = true; if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){ //We check if we received a string for the first parameter (Player) if (args[1] != null && !TTools.isInt(args[1])){ //We check if we received a int for the second parameter (Amount) if (args[2] != null && TTools.isInt(args[2])){ String name = args[1]; try { target = plugin.matchSinglePlayer(sender, name); if (target.getName() != null){ name = target.getName(); } }catch (CommandException error){ sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED)); return handled; } ticketarg = Integer.parseInt(args[2]); if (checkIfPlayerExists(name)){ currentticket = getPlayerTicket(name); amount = currentticket - ticketarg; if (amount < 0){ sendMessage(sender,colorizeText("You can't remove ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)! This player only have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)!",ChatColor.RED)); return handled; } dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'"); }else{ sendMessage(sender,colorizeText("You can't remove tickets to " + name + " because he doesn't have any!",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED)); } } else{ sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED)); } } } } return handled; }
diff --git a/osmorc/src/org/osmorc/inspection/MissingFinalNewlineInspection.java b/osmorc/src/org/osmorc/inspection/MissingFinalNewlineInspection.java index c9ee42ebdd..9902feee33 100644 --- a/osmorc/src/org/osmorc/inspection/MissingFinalNewlineInspection.java +++ b/osmorc/src/org/osmorc/inspection/MissingFinalNewlineInspection.java @@ -1,97 +1,97 @@ /* * Copyright (c) 2007-2009, Osmorc Development Team * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of 'Osmorc Development Team' nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.osmorc.inspection; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInspection.InspectionManager; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.osmorc.fix.ReplaceQuickFixQuickFix; import org.osmorc.manifest.lang.psi.ManifestHeaderValueImpl; import org.osmorc.manifest.lang.psi.ManifestFile; /** * @author Robert F. Beeger ([email protected]) */ public class MissingFinalNewlineInspection extends LocalInspectionTool { @Nls @NotNull public String getGroupDisplayName() { return "OSGi"; } @Nls @NotNull public String getDisplayName() { return "Missing Final New Line"; } @NotNull public String getShortName() { return "osmorcMissingFinalNewline"; } public boolean isEnabledByDefault() { return true; } @NotNull public HighlightDisplayLevel getDefaultLevel() { return HighlightDisplayLevel.ERROR; } @Override public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) { if (file instanceof ManifestFile) { String text = file.getText(); if (text.charAt(text.length() - 1) != '\n') { ManifestHeaderValueImpl headerValue = PsiTreeUtil.findElementOfClassAtOffset(file, text.length() - 1, ManifestHeaderValueImpl.class, false); if (headerValue != null) { return new ProblemDescriptor[]{manager.createProblemDescriptor(headerValue, - "Manifest file doen't end with a final newline", + "Manifest file doesn't end with a final newline", new AddNewlineQuickFix(headerValue), ProblemHighlightType.GENERIC_ERROR_OR_WARNING)}; } } } return new ProblemDescriptor[0]; } private static class AddNewlineQuickFix extends ReplaceQuickFixQuickFix { private AddNewlineQuickFix(ManifestHeaderValueImpl headerValue) { // TODO: This is a hack. Osmorc currently doesn't handle manifest file sections. Need to fix this once Osmorc handles sections. super("Add newline", headerValue, headerValue.getText() + "\n\n"); } } }
true
true
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) { if (file instanceof ManifestFile) { String text = file.getText(); if (text.charAt(text.length() - 1) != '\n') { ManifestHeaderValueImpl headerValue = PsiTreeUtil.findElementOfClassAtOffset(file, text.length() - 1, ManifestHeaderValueImpl.class, false); if (headerValue != null) { return new ProblemDescriptor[]{manager.createProblemDescriptor(headerValue, "Manifest file doen't end with a final newline", new AddNewlineQuickFix(headerValue), ProblemHighlightType.GENERIC_ERROR_OR_WARNING)}; } } } return new ProblemDescriptor[0]; }
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) { if (file instanceof ManifestFile) { String text = file.getText(); if (text.charAt(text.length() - 1) != '\n') { ManifestHeaderValueImpl headerValue = PsiTreeUtil.findElementOfClassAtOffset(file, text.length() - 1, ManifestHeaderValueImpl.class, false); if (headerValue != null) { return new ProblemDescriptor[]{manager.createProblemDescriptor(headerValue, "Manifest file doesn't end with a final newline", new AddNewlineQuickFix(headerValue), ProblemHighlightType.GENERIC_ERROR_OR_WARNING)}; } } } return new ProblemDescriptor[0]; }
diff --git a/modules/axiom-api/src/main/java/org/apache/axiom/attachments/impl/PartFactory.java b/modules/axiom-api/src/main/java/org/apache/axiom/attachments/impl/PartFactory.java index ecaaee923..c116233e5 100644 --- a/modules/axiom-api/src/main/java/org/apache/axiom/attachments/impl/PartFactory.java +++ b/modules/axiom-api/src/main/java/org/apache/axiom/attachments/impl/PartFactory.java @@ -1,292 +1,292 @@ /* * 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.axiom.attachments.impl; import org.apache.axiom.attachments.Part; import org.apache.axiom.attachments.lifecycle.LifecycleManager; import org.apache.axiom.attachments.utils.BAAInputStream; import org.apache.axiom.attachments.utils.BAAOutputStream; import org.apache.axiom.om.OMException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.james.mime4j.MimeException; import org.apache.james.mime4j.stream.EntityState; import org.apache.james.mime4j.stream.Field; import org.apache.james.mime4j.stream.MimeTokenStream; import javax.mail.Header; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Hashtable; import java.util.Map; /** * The PartFactory creates an object that represents a Part * (implements the Part interface). There are different ways * to represent a part (backing file or backing array etc.). * These different implementations should not be exposed to the * other layers of the code. The PartFactory helps maintain this * abstraction, and makes it easier to add new implementations. */ public class PartFactory { private static int inflight = 0; // How many attachments are currently being built. private static String semifore = "PartFactory.semifore"; private static Log log = LogFactory.getLog(PartFactory.class); // Maximum number of threads allowed through createPart private static int INFLIGHT_MAX = 4; // Constants for dynamic threshold // Dynamic Threshold = availMemory / THRESHOLD_FACTOR private static final int THRESHOLD_FACTOR = 5; private static void checkParserState(EntityState state, EntityState expected) throws IllegalStateException { if (expected != state) { throw new IllegalStateException("Internal error: expected parser to be in state " + expected + ", but got " + state); } } /** * Creates a part from the input stream. * The remaining parameters are used to determine if the * part should be represented in memory (byte buffers) or * backed by a file. * * @param in MIMEBodyPartInputStream * @param isSOAPPart * @param thresholdSize * @param attachmentDir * @param messageContentLength * @return Part * @throws OMException if any exception is encountered while processing. */ public static Part createPart(LifecycleManager manager, MimeTokenStream parser, boolean isSOAPPart, int thresholdSize, String attachmentDir, int messageContentLength ) throws OMException { if(log.isDebugEnabled()){ log.debug("Start createPart()"); log.debug(" isSOAPPart=" + isSOAPPart); log.debug(" thresholdSize= " + thresholdSize); log.debug(" attachmentDir=" + attachmentDir); log.debug(" messageContentLength " + messageContentLength); } try { checkParserState(parser.getState(), EntityState.T_START_BODYPART); // Read enough of the InputStream to build the headers // The readHeaders returns some extra bits that were read, but are part // of the data section. Hashtable headers = new Hashtable(); readHeaders(parser, headers); Part part; try { // Message throughput is increased if the number of threads in this // section is limited to INFLIGHT_MAX. Allowing more threads tends to cause // thrashing while reading from the HTTP InputStream. // Allowing fewer threads reduces the thrashing. And when the remaining threads // are notified their input (chunked) data is available. // // Note: SOAPParts are at the beginning of the message and much smaller than attachments, // so don't wait on soap parts. if (!isSOAPPart) { synchronized(semifore) { if (inflight >= INFLIGHT_MAX) { semifore.wait(); } inflight++; } } // Get new threshold based on the current available memory in the runtime. // We only use the thresholds for non-soap parts. if (!isSOAPPart && thresholdSize > 0) { thresholdSize = getRuntimeThreshold(thresholdSize, inflight); } if (isSOAPPart || thresholdSize <= 0 || (messageContentLength > 0 && messageContentLength < thresholdSize)) { // If the entire message is less than the threshold size, // keep it in memory. // If this is a SOAPPart, keep it in memory. // Get the bytes of the data without a lot // of resizing and GC. The BAAOutputStream // keeps the data in non-contiguous byte buffers. BAAOutputStream baaos = new BAAOutputStream(); BufferUtils.inputStream2OutputStream(parser.getInputStream(), baaos); part = new PartOnMemoryEnhanced(headers, baaos.buffers(), baaos.length()); } else { // We need to read the input stream to determine whether // the size is bigger or smaller than the threshold. BAAOutputStream baaos = new BAAOutputStream(); InputStream in = parser.getInputStream(); int count = BufferUtils.inputStream2OutputStream(in, baaos, thresholdSize); if (count < thresholdSize) { - return new PartOnMemoryEnhanced(headers, baaos.buffers(), baaos.length()); + part = new PartOnMemoryEnhanced(headers, baaos.buffers(), baaos.length()); } else { // A BAAInputStream is an input stream over a list of non-contiguous 4K buffers. BAAInputStream baais = new BAAInputStream(baaos.buffers(), baaos.length()); part = new PartOnFile(manager, headers, baais, in, attachmentDir); } } checkParserState(parser.next(), EntityState.T_END_BODYPART); } finally { if (!isSOAPPart) { synchronized(semifore) { semifore.notify(); inflight--; } } } return part; } catch (Exception e) { throw new OMException(e); } } /** * The implementing class must call initHeaders prior to using * any of the Part methods. * @param is * @param headers */ private static void readHeaders(MimeTokenStream parser, Map headers) throws IOException, MimeException { if(log.isDebugEnabled()){ log.debug("initHeaders"); } checkParserState(parser.next(), EntityState.T_START_HEADER); while (parser.next() == EntityState.T_FIELD) { Field field = parser.getField(); String name = field.getName(); String value = field.getBody(); if (log.isDebugEnabled()){ log.debug("addHeader: (" + name + ") value=(" + value +")"); } Header headerObj = new Header(name, value); // Use the lower case name as the key String key = name.toLowerCase(); headers.put(key, headerObj); } checkParserState(parser.next(), EntityState.T_BODY); } /** * This method checks the configured threshold and * the current runtime information. If it appears that we could * run out of memory, the threshold is reduced. * * This method allows the user to request a much larger threshold without * fear of running out of memory. Using a larger in memory threshold generally * results in better throughput. * * @param configThreshold * @param inflight * @return threshold */ private static int getRuntimeThreshold(int configThreshold, int inflight) { // Determine how much free memory is available Runtime r = Runtime.getRuntime(); long totalmem = r.totalMemory(); long maxmem = r.maxMemory(); long freemem = r.freeMemory(); // @REVIEW // If maximum is not defined...limit to 1G if (maxmem == java.lang.Long.MAX_VALUE) { maxmem = 1024*1024*1024; } long availmem = maxmem - (totalmem - freemem); // Now determine the dynamic threshold int dynamicThreshold = (int) availmem / (THRESHOLD_FACTOR * inflight); // If it appears that we might run out of memory with this // threshold, reduce the threshold size. if (dynamicThreshold < configThreshold) { if (log.isDebugEnabled()) { log.debug("Using Runtime Attachment File Threshold " + dynamicThreshold); log.debug("maxmem = " + maxmem); log.debug("totalmem = " + totalmem); log.debug("freemem = " + freemem); log.debug("availmem = " + availmem); } } else { dynamicThreshold = configThreshold; if (log.isDebugEnabled()) { log.debug("Using Configured Attachment File Threshold " + configThreshold); log.debug("maxmem = " + maxmem); log.debug("totalmem = " + totalmem); log.debug("freemem = " + freemem); log.debug("availmem = " + availmem); } } return dynamicThreshold; } /** * A normal ByteArrayOutputStream, except that it returns the buffer * directly instead of returning a copy of the buffer. */ static class BAOS extends ByteArrayOutputStream { /** * Create a BAOS with a decent sized buffer */ public BAOS() { super(16 * 1024); } public byte[] toByteArray() { return buf; } } }
true
true
public static Part createPart(LifecycleManager manager, MimeTokenStream parser, boolean isSOAPPart, int thresholdSize, String attachmentDir, int messageContentLength ) throws OMException { if(log.isDebugEnabled()){ log.debug("Start createPart()"); log.debug(" isSOAPPart=" + isSOAPPart); log.debug(" thresholdSize= " + thresholdSize); log.debug(" attachmentDir=" + attachmentDir); log.debug(" messageContentLength " + messageContentLength); } try { checkParserState(parser.getState(), EntityState.T_START_BODYPART); // Read enough of the InputStream to build the headers // The readHeaders returns some extra bits that were read, but are part // of the data section. Hashtable headers = new Hashtable(); readHeaders(parser, headers); Part part; try { // Message throughput is increased if the number of threads in this // section is limited to INFLIGHT_MAX. Allowing more threads tends to cause // thrashing while reading from the HTTP InputStream. // Allowing fewer threads reduces the thrashing. And when the remaining threads // are notified their input (chunked) data is available. // // Note: SOAPParts are at the beginning of the message and much smaller than attachments, // so don't wait on soap parts. if (!isSOAPPart) { synchronized(semifore) { if (inflight >= INFLIGHT_MAX) { semifore.wait(); } inflight++; } } // Get new threshold based on the current available memory in the runtime. // We only use the thresholds for non-soap parts. if (!isSOAPPart && thresholdSize > 0) { thresholdSize = getRuntimeThreshold(thresholdSize, inflight); } if (isSOAPPart || thresholdSize <= 0 || (messageContentLength > 0 && messageContentLength < thresholdSize)) { // If the entire message is less than the threshold size, // keep it in memory. // If this is a SOAPPart, keep it in memory. // Get the bytes of the data without a lot // of resizing and GC. The BAAOutputStream // keeps the data in non-contiguous byte buffers. BAAOutputStream baaos = new BAAOutputStream(); BufferUtils.inputStream2OutputStream(parser.getInputStream(), baaos); part = new PartOnMemoryEnhanced(headers, baaos.buffers(), baaos.length()); } else { // We need to read the input stream to determine whether // the size is bigger or smaller than the threshold. BAAOutputStream baaos = new BAAOutputStream(); InputStream in = parser.getInputStream(); int count = BufferUtils.inputStream2OutputStream(in, baaos, thresholdSize); if (count < thresholdSize) { return new PartOnMemoryEnhanced(headers, baaos.buffers(), baaos.length()); } else { // A BAAInputStream is an input stream over a list of non-contiguous 4K buffers. BAAInputStream baais = new BAAInputStream(baaos.buffers(), baaos.length()); part = new PartOnFile(manager, headers, baais, in, attachmentDir); } } checkParserState(parser.next(), EntityState.T_END_BODYPART); } finally { if (!isSOAPPart) { synchronized(semifore) { semifore.notify(); inflight--; } } } return part; } catch (Exception e) { throw new OMException(e); } }
public static Part createPart(LifecycleManager manager, MimeTokenStream parser, boolean isSOAPPart, int thresholdSize, String attachmentDir, int messageContentLength ) throws OMException { if(log.isDebugEnabled()){ log.debug("Start createPart()"); log.debug(" isSOAPPart=" + isSOAPPart); log.debug(" thresholdSize= " + thresholdSize); log.debug(" attachmentDir=" + attachmentDir); log.debug(" messageContentLength " + messageContentLength); } try { checkParserState(parser.getState(), EntityState.T_START_BODYPART); // Read enough of the InputStream to build the headers // The readHeaders returns some extra bits that were read, but are part // of the data section. Hashtable headers = new Hashtable(); readHeaders(parser, headers); Part part; try { // Message throughput is increased if the number of threads in this // section is limited to INFLIGHT_MAX. Allowing more threads tends to cause // thrashing while reading from the HTTP InputStream. // Allowing fewer threads reduces the thrashing. And when the remaining threads // are notified their input (chunked) data is available. // // Note: SOAPParts are at the beginning of the message and much smaller than attachments, // so don't wait on soap parts. if (!isSOAPPart) { synchronized(semifore) { if (inflight >= INFLIGHT_MAX) { semifore.wait(); } inflight++; } } // Get new threshold based on the current available memory in the runtime. // We only use the thresholds for non-soap parts. if (!isSOAPPart && thresholdSize > 0) { thresholdSize = getRuntimeThreshold(thresholdSize, inflight); } if (isSOAPPart || thresholdSize <= 0 || (messageContentLength > 0 && messageContentLength < thresholdSize)) { // If the entire message is less than the threshold size, // keep it in memory. // If this is a SOAPPart, keep it in memory. // Get the bytes of the data without a lot // of resizing and GC. The BAAOutputStream // keeps the data in non-contiguous byte buffers. BAAOutputStream baaos = new BAAOutputStream(); BufferUtils.inputStream2OutputStream(parser.getInputStream(), baaos); part = new PartOnMemoryEnhanced(headers, baaos.buffers(), baaos.length()); } else { // We need to read the input stream to determine whether // the size is bigger or smaller than the threshold. BAAOutputStream baaos = new BAAOutputStream(); InputStream in = parser.getInputStream(); int count = BufferUtils.inputStream2OutputStream(in, baaos, thresholdSize); if (count < thresholdSize) { part = new PartOnMemoryEnhanced(headers, baaos.buffers(), baaos.length()); } else { // A BAAInputStream is an input stream over a list of non-contiguous 4K buffers. BAAInputStream baais = new BAAInputStream(baaos.buffers(), baaos.length()); part = new PartOnFile(manager, headers, baais, in, attachmentDir); } } checkParserState(parser.next(), EntityState.T_END_BODYPART); } finally { if (!isSOAPPart) { synchronized(semifore) { semifore.notify(); inflight--; } } } return part; } catch (Exception e) { throw new OMException(e); } }
diff --git a/src/test/java/org/lastbamboo/common/ice/IceAgentImplTest.java b/src/test/java/org/lastbamboo/common/ice/IceAgentImplTest.java index 10e0e10..7eb40a4 100644 --- a/src/test/java/org/lastbamboo/common/ice/IceAgentImplTest.java +++ b/src/test/java/org/lastbamboo/common/ice/IceAgentImplTest.java @@ -1,273 +1,281 @@ package org.lastbamboo.common.ice; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Collection; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.ConnectFuture; import org.apache.mina.common.ExecutorThreadModel; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.transport.socket.nio.DatagramConnector; import org.apache.mina.transport.socket.nio.DatagramConnectorConfig; import org.junit.Assert; import org.junit.Test; import org.lastbamboo.common.ice.candidate.IceCandidatePair; import org.lastbamboo.common.offer.answer.MediaOfferAnswer; import org.lastbamboo.common.offer.answer.OfferAnswerListener; import org.lastbamboo.common.offer.answer.OfferAnswerMediaListener; import org.lastbamboo.common.stun.stack.StunDemuxableProtocolCodecFactory; import org.lastbamboo.common.stun.stack.StunIoHandler; import org.lastbamboo.common.stun.stack.StunProtocolCodecFactory; import org.lastbamboo.common.stun.stack.message.IcmpErrorStunMessage; import org.lastbamboo.common.stun.stack.message.StunMessage; import org.lastbamboo.common.stun.stack.message.StunMessageVisitor; import org.lastbamboo.common.stun.stack.message.StunMessageVisitorAdapter; import org.lastbamboo.common.stun.stack.message.StunMessageVisitorFactory; import org.lastbamboo.common.turn.client.TurnClientListener; import org.lastbamboo.common.util.mina.DemuxableProtocolCodecFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Test connections between ICE agents. */ public class IceAgentImplTest { private final Logger m_log = LoggerFactory.getLogger(getClass()); private final AtomicBoolean m_gotIcmpError = new AtomicBoolean(false); /** * Tests creating a local UDP connection using ICE. * * @throws Exception If any unexpected error occurs. */ @Test public void testLocalUdpConnection() throws Exception { final IceMediaStreamDesc desc = new IceMediaStreamDesc(false, true, "message", "http", 1); final GeneralIceMediaStreamFactory generalStreamFactory = new GeneralIceMediaStreamFactoryImpl(); final IceMediaStreamFactory mediaStreamFactory1 = new IceMediaStreamFactory() { public IceMediaStream newStream(final IceAgent iceAgent) { final DemuxableProtocolCodecFactory otherCodecFactory = new StunDemuxableProtocolCodecFactory(); final IoHandler clientIoHandler = new IoHandlerAdapter(); final TurnClientListener delegateListener = null; return generalStreamFactory.newIceMediaStream(desc, iceAgent, otherCodecFactory, Void.class, clientIoHandler, delegateListener); } }; final IceMediaStreamFactory mediaStreamFactory2 = new IceMediaStreamFactory() { public IceMediaStream newStream(final IceAgent iceAgent) { final DemuxableProtocolCodecFactory otherCodecFactory = new StunDemuxableProtocolCodecFactory(); final IoHandler clientIoHandler = new IoHandlerAdapter(); final TurnClientListener delegateListener = null; return generalStreamFactory.newIceMediaStream(desc, iceAgent, otherCodecFactory, Void.class, clientIoHandler, delegateListener); } }; final IceMediaFactory iceMediaFactory = new IceMediaFactory() { public void newMedia(IceCandidatePair pair, boolean client, final OfferAnswerMediaListener mediaListener) { } }; final IceAgent offerer = new IceAgentImpl( mediaStreamFactory1, true, iceMediaFactory); final byte[] offer = offerer.generateOffer(); m_log.debug("Telling answerer to process offer: {}", new String(offer)); final IceAgent answerer = new IceAgentImpl( mediaStreamFactory2, false, iceMediaFactory); Assert.assertFalse(answerer.isControlling()); m_log.debug("About to generate answer..."); final byte[] answer = answerer.generateAnswer(); m_log.debug("Generated answer: {}", new String(answer)); final AtomicBoolean answererCompleted = new AtomicBoolean(false); final AtomicBoolean offererCompleted = new AtomicBoolean(false); final OfferAnswerListener offererStateListener = new OfferAnswerListener() { public void onOfferAnswerComplete(final MediaOfferAnswer offerAnswer) { - offererCompleted.set(true); + synchronized (offererCompleted) + { + offererCompleted.set(true); + offererCompleted.notifyAll(); + } } }; final OfferAnswerListener answererStateListener = new OfferAnswerListener() { public void onOfferAnswerComplete(final MediaOfferAnswer offerAnswer) { - answererCompleted.set(true); + synchronized (answererCompleted) + { + answererCompleted.set(true); + answererCompleted.notifyAll(); + } } }; final AtomicBoolean threadFailed = new AtomicBoolean(false); final Thread answerThread = new Thread(new Runnable() { public void run() { try { answerer.processOffer(ByteBuffer.wrap(offer), answererStateListener); } catch (final IOException e) { threadFailed.set(true); } } }); answerThread.setDaemon(true); answerThread.start(); Thread.yield(); final Collection<IceMediaStream> streams = answerer.getMediaStreams(); Assert.assertEquals(1, streams.size()); offerer.processAnswer(ByteBuffer.wrap(answer), offererStateListener); //final Socket sock = offerer.createSocket(); Assert.assertFalse(threadFailed.get()); synchronized (offererCompleted) { if (!offererCompleted.get()) offererCompleted.wait(16000); } synchronized (answererCompleted) { if (!answererCompleted.get()) answererCompleted.wait(16000); } Assert.assertTrue("Did not complete offer", offererCompleted.get()); Assert.assertTrue("Did not complete answer", answererCompleted.get()); } /* NOTE: The address used in this test only worked on a specific network -- one where we could consistently generate ICMP errors. public void testPortUnreachable() throws Exception { final InetSocketAddress localAddress = new InetSocketAddress(NetworkUtils.getLocalHost(), 44252); final InetSocketAddress remoteAddress = new InetSocketAddress("141.157.201.230", 54911); final IoSession session = createClientSession(localAddress, remoteAddress); assertTrue(session.isConnected()); m_gotIcmpError.set(false); session.write(new BindingRequest()); synchronized (this.m_gotIcmpError) { this.m_gotIcmpError.wait(2000); } assertTrue("Did not get ICMP error", m_gotIcmpError.get()); } */ private IoSession createClientSession(final InetSocketAddress localAddress, final InetSocketAddress remoteAddress) { final DatagramConnector connector = new DatagramConnector(); final DatagramConnectorConfig cfg = connector.getDefaultConfig(); cfg.getSessionConfig().setReuseAddress(true); final String controlling = "Whatever"; cfg.setThreadModel( ExecutorThreadModel.getInstance( "IceUdpStunChecker-"+controlling)); final ProtocolCodecFactory codecFactory = new StunProtocolCodecFactory(); final ProtocolCodecFilter stunFilter = new ProtocolCodecFilter(codecFactory); connector.getFilterChain().addLast("stunFilter", stunFilter); final StunMessageVisitorFactory visitorFactory = new StunMessageVisitorFactory<StunMessage, IceMediaStream>() { public StunMessageVisitor<StunMessage> createVisitor(IoSession session) { final StunMessageVisitor<StunMessage> visitor = new StunMessageVisitorAdapter<StunMessage>() { public StunMessage visitIcmpErrorMesssage( final IcmpErrorStunMessage message) { m_log.debug("Got ICMP error!!"); m_gotIcmpError.set(true); synchronized (m_gotIcmpError) { m_gotIcmpError.notify(); } return message; } }; return visitor; } public StunMessageVisitor<StunMessage> createVisitor( final IoSession session, final IceMediaStream attachment) { return createVisitor(session); } }; final IoHandler ioHandler = new StunIoHandler<StunMessage>(visitorFactory); m_log.debug("Connecting from "+localAddress+" to "+remoteAddress); final ConnectFuture cf = connector.connect(remoteAddress, localAddress, ioHandler); cf.join(); final IoSession session = cf.getSession(); if (session == null) { m_log.error("Could not create session from "+ localAddress +" to "+remoteAddress); throw new NullPointerException("Could not create session!!"); } return session; } }
false
true
public void testLocalUdpConnection() throws Exception { final IceMediaStreamDesc desc = new IceMediaStreamDesc(false, true, "message", "http", 1); final GeneralIceMediaStreamFactory generalStreamFactory = new GeneralIceMediaStreamFactoryImpl(); final IceMediaStreamFactory mediaStreamFactory1 = new IceMediaStreamFactory() { public IceMediaStream newStream(final IceAgent iceAgent) { final DemuxableProtocolCodecFactory otherCodecFactory = new StunDemuxableProtocolCodecFactory(); final IoHandler clientIoHandler = new IoHandlerAdapter(); final TurnClientListener delegateListener = null; return generalStreamFactory.newIceMediaStream(desc, iceAgent, otherCodecFactory, Void.class, clientIoHandler, delegateListener); } }; final IceMediaStreamFactory mediaStreamFactory2 = new IceMediaStreamFactory() { public IceMediaStream newStream(final IceAgent iceAgent) { final DemuxableProtocolCodecFactory otherCodecFactory = new StunDemuxableProtocolCodecFactory(); final IoHandler clientIoHandler = new IoHandlerAdapter(); final TurnClientListener delegateListener = null; return generalStreamFactory.newIceMediaStream(desc, iceAgent, otherCodecFactory, Void.class, clientIoHandler, delegateListener); } }; final IceMediaFactory iceMediaFactory = new IceMediaFactory() { public void newMedia(IceCandidatePair pair, boolean client, final OfferAnswerMediaListener mediaListener) { } }; final IceAgent offerer = new IceAgentImpl( mediaStreamFactory1, true, iceMediaFactory); final byte[] offer = offerer.generateOffer(); m_log.debug("Telling answerer to process offer: {}", new String(offer)); final IceAgent answerer = new IceAgentImpl( mediaStreamFactory2, false, iceMediaFactory); Assert.assertFalse(answerer.isControlling()); m_log.debug("About to generate answer..."); final byte[] answer = answerer.generateAnswer(); m_log.debug("Generated answer: {}", new String(answer)); final AtomicBoolean answererCompleted = new AtomicBoolean(false); final AtomicBoolean offererCompleted = new AtomicBoolean(false); final OfferAnswerListener offererStateListener = new OfferAnswerListener() { public void onOfferAnswerComplete(final MediaOfferAnswer offerAnswer) { offererCompleted.set(true); } }; final OfferAnswerListener answererStateListener = new OfferAnswerListener() { public void onOfferAnswerComplete(final MediaOfferAnswer offerAnswer) { answererCompleted.set(true); } }; final AtomicBoolean threadFailed = new AtomicBoolean(false); final Thread answerThread = new Thread(new Runnable() { public void run() { try { answerer.processOffer(ByteBuffer.wrap(offer), answererStateListener); } catch (final IOException e) { threadFailed.set(true); } } }); answerThread.setDaemon(true); answerThread.start(); Thread.yield(); final Collection<IceMediaStream> streams = answerer.getMediaStreams(); Assert.assertEquals(1, streams.size()); offerer.processAnswer(ByteBuffer.wrap(answer), offererStateListener); //final Socket sock = offerer.createSocket(); Assert.assertFalse(threadFailed.get()); synchronized (offererCompleted) { if (!offererCompleted.get()) offererCompleted.wait(16000); } synchronized (answererCompleted) { if (!answererCompleted.get()) answererCompleted.wait(16000); } Assert.assertTrue("Did not complete offer", offererCompleted.get()); Assert.assertTrue("Did not complete answer", answererCompleted.get()); }
public void testLocalUdpConnection() throws Exception { final IceMediaStreamDesc desc = new IceMediaStreamDesc(false, true, "message", "http", 1); final GeneralIceMediaStreamFactory generalStreamFactory = new GeneralIceMediaStreamFactoryImpl(); final IceMediaStreamFactory mediaStreamFactory1 = new IceMediaStreamFactory() { public IceMediaStream newStream(final IceAgent iceAgent) { final DemuxableProtocolCodecFactory otherCodecFactory = new StunDemuxableProtocolCodecFactory(); final IoHandler clientIoHandler = new IoHandlerAdapter(); final TurnClientListener delegateListener = null; return generalStreamFactory.newIceMediaStream(desc, iceAgent, otherCodecFactory, Void.class, clientIoHandler, delegateListener); } }; final IceMediaStreamFactory mediaStreamFactory2 = new IceMediaStreamFactory() { public IceMediaStream newStream(final IceAgent iceAgent) { final DemuxableProtocolCodecFactory otherCodecFactory = new StunDemuxableProtocolCodecFactory(); final IoHandler clientIoHandler = new IoHandlerAdapter(); final TurnClientListener delegateListener = null; return generalStreamFactory.newIceMediaStream(desc, iceAgent, otherCodecFactory, Void.class, clientIoHandler, delegateListener); } }; final IceMediaFactory iceMediaFactory = new IceMediaFactory() { public void newMedia(IceCandidatePair pair, boolean client, final OfferAnswerMediaListener mediaListener) { } }; final IceAgent offerer = new IceAgentImpl( mediaStreamFactory1, true, iceMediaFactory); final byte[] offer = offerer.generateOffer(); m_log.debug("Telling answerer to process offer: {}", new String(offer)); final IceAgent answerer = new IceAgentImpl( mediaStreamFactory2, false, iceMediaFactory); Assert.assertFalse(answerer.isControlling()); m_log.debug("About to generate answer..."); final byte[] answer = answerer.generateAnswer(); m_log.debug("Generated answer: {}", new String(answer)); final AtomicBoolean answererCompleted = new AtomicBoolean(false); final AtomicBoolean offererCompleted = new AtomicBoolean(false); final OfferAnswerListener offererStateListener = new OfferAnswerListener() { public void onOfferAnswerComplete(final MediaOfferAnswer offerAnswer) { synchronized (offererCompleted) { offererCompleted.set(true); offererCompleted.notifyAll(); } } }; final OfferAnswerListener answererStateListener = new OfferAnswerListener() { public void onOfferAnswerComplete(final MediaOfferAnswer offerAnswer) { synchronized (answererCompleted) { answererCompleted.set(true); answererCompleted.notifyAll(); } } }; final AtomicBoolean threadFailed = new AtomicBoolean(false); final Thread answerThread = new Thread(new Runnable() { public void run() { try { answerer.processOffer(ByteBuffer.wrap(offer), answererStateListener); } catch (final IOException e) { threadFailed.set(true); } } }); answerThread.setDaemon(true); answerThread.start(); Thread.yield(); final Collection<IceMediaStream> streams = answerer.getMediaStreams(); Assert.assertEquals(1, streams.size()); offerer.processAnswer(ByteBuffer.wrap(answer), offererStateListener); //final Socket sock = offerer.createSocket(); Assert.assertFalse(threadFailed.get()); synchronized (offererCompleted) { if (!offererCompleted.get()) offererCompleted.wait(16000); } synchronized (answererCompleted) { if (!answererCompleted.get()) answererCompleted.wait(16000); } Assert.assertTrue("Did not complete offer", offererCompleted.get()); Assert.assertTrue("Did not complete answer", answererCompleted.get()); }
diff --git a/Pathogenum/src/client/ClientHubState.java b/Pathogenum/src/client/ClientHubState.java index 5a71455..c4ff61b 100644 --- a/Pathogenum/src/client/ClientHubState.java +++ b/Pathogenum/src/client/ClientHubState.java @@ -1,332 +1,336 @@ package client; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.InputImplementation; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.Music; import org.newdawn.slick.SlickException; import org.newdawn.slick.gui.MouseOverArea; import org.newdawn.slick.gui.TextField; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import com.google.common.base.CharMatcher; import utils.GameAddress; /** * A gamestate representing the Hub menu, where the list of lobbys will be * displayed amongst a global chat window. * * @author Mardrey, BigFarmor * */ public class ClientHubState extends BasicGameState { public static final int ID = 0; Image sendButton; Image newgameButton; Image joingameButton; Image refreshButton; TextField inputText; TextField outputText; TextField gamesField; TextField newGameNameField; TextField newGamePortField; TextField errorMessages; TextField IpText; String[] chatMessages; ArrayList<GameAddress> gamesList; ClientConnectionHandler cch; ArrayList<TextField> tFields; boolean pressedSend = false; boolean pressedJoin = false; boolean pressedNew = false; boolean pressedRefresh = false; private static InetAddress ia; private static int port; /** * creates a clientConnectionHandler for handling connections to the * server.. durr * * @param ia * @param port */ public ClientHubState(InetAddress ia, int port) { this.ia = ia; this.port = port; try { cch = ClientConnectionHandler.getCCH(ia, port); } catch (NumberFormatException e) { e.printStackTrace(); } } public static InetAddress getHost() { return ia; } public static int getPort() { return port; } @Override public void init(GameContainer arg0, StateBasedGame arg1) throws SlickException { tFields = new ArrayList<TextField>(); cch.refreshGames(); chatMessages = new String[5]; gamesList = new ArrayList<GameAddress>(); sendButton = new Image("resources/gfx/SendButton.png"); joingameButton = new Image("resources/gfx/JoingameButton.png"); newgameButton = new Image("resources/gfx/NewgameButton.png"); refreshButton = new Image("resources/gfx/RefreshButton.png"); inputText = new TextField(arg0, arg0.getDefaultFont(), 400, 250, sendButton.getWidth(), 30); outputText = new TextField(arg0, arg0.getDefaultFont(), 400, 100, 500, 100); gamesField = new TextField(arg0, arg0.getDefaultFont(), 200, 450, 500, 100); newGameNameField = new TextField(arg0, arg0.getDefaultFont(), 200, 200, newgameButton.getWidth(), 30); newGamePortField = new TextField(arg0, arg0.getDefaultFont(), 200, 250, newgameButton.getWidth(), 30); errorMessages = new TextField(arg0, arg0.getDefaultFont(), 50, 680, 300, 30); IpText = new TextField(arg0,arg0.getDefaultFont(),600,250,300,30); newGameNameField.setText("Game Name"); newGamePortField.setText("Game Port"); outputText.setAcceptingInput(false); gamesField.setAcceptingInput(false); errorMessages.setAcceptingInput(false); inputText.setBackgroundColor(new Color(0, 0, 0)); outputText.setBackgroundColor(new Color(0, 0, 0)); gamesField.setBackgroundColor(new Color(0, 0, 0)); errorMessages.setBackgroundColor(new Color(0, 0, 0)); tFields.add(inputText); tFields.add(outputText); tFields.add(gamesField); tFields.add(newGameNameField); tFields.add(newGamePortField); tFields.add(errorMessages); tFields.add(IpText); } @Override public void render(GameContainer arg0, StateBasedGame arg1, Graphics arg2) throws SlickException { arg2.drawImage(sendButton, 400, 300); arg2.drawImage(newgameButton, 200, 300); arg2.drawImage(joingameButton, 600, 300); arg2.drawImage(refreshButton, 50, 600); for(TextField tf: tFields){ tf.render(arg0, arg2); } //inputText.render(arg0, arg2); //outputText.render(arg0, arg2); //gamesField.render(arg0, arg2); //newGameNameField.render(arg0, arg2); //newGamePortField.render(arg0, arg2); //errorMessages.render(arg0, arg2); } @Override public void update(GameContainer arg0, StateBasedGame arg1, int arg2) throws SlickException { if (pressedSend && !Mouse.isButtonDown(0)) { // Prevents clicks being // counted several times pressedSend = false; } if (pressedNew && !Mouse.isButtonDown(0)) { // --||-- pressedNew = false; } if (pressedJoin && !Mouse.isButtonDown(0)) {// --||-- pressedJoin = false; } if (pressedRefresh && !Mouse.isButtonDown(0)) {// --||-- pressedRefresh = false; } /* * Sends chat message to server */ MouseOverArea moa = new MouseOverArea(arg0, sendButton, 400, 300, sendButton.getWidth(), sendButton.getHeight()); if (moa.isMouseOver() && Mouse.isButtonDown(0) && !(inputText.getText().equals("")) && !pressedSend) { System.out.println("PRESSED! Message is: " + inputText.getText()); pressedSend = true; boolean isAscii = CharMatcher.ASCII.matchesAllOf(inputText.getText()); if(isAscii){ cch.sendMessage(inputText.getText()); inputText.setText(""); } else{ errorMessages.setText("Illegal chat character"); } } /* * Creates new game in server */ moa = new MouseOverArea(arg0, newgameButton, 200, 300, newgameButton.getWidth(), newgameButton.getHeight()); if (moa.isMouseOver() && Mouse.isButtonDown(0) && !pressedNew) { System.out.println("PRESSED! NEW GAME"); pressedNew = true; int port = checkPortValidity(); + boolean isAscii = CharMatcher.ASCII.matchesAllOf(newGameNameField.getText()); if (newGameNameField.getText().equals("")) { errorMessages.setText("No game name"); } else if (newGamePortField.getText().equals("")) { errorMessages.setText("No port number"); } else if (port == -1) { errorMessages.setText("Invalid port number"); } + else if(!isAscii){ + errorMessages.setText("Invalid game name"); + } else { cch.createNewLobby(newGameNameField.getText(), port); arg1.enterState(ClientLobbyState.ID); return; } // LobbyGameState // IMPLEMENT } /* * Joins existing game */ moa = new MouseOverArea(arg0, joingameButton, 600, 300, joingameButton.getWidth(), joingameButton.getHeight()); if (moa.isMouseOver() && Mouse.isButtonDown(0) && !pressedJoin) { pressedJoin = true; System.out.println("PRESSED! JOIN GAME"); String ipText = IpText.getText(); String[] hostAndPort = ipText.split(":"); if(hostAndPort.length == 2){ String host = hostAndPort[0]; String portString = hostAndPort[1]; int port = Integer.parseInt(portString); cch.joinLobby(host,port); arg1.enterState(ClientLobbyState.ID); }else{ errorMessages.setText("Incorrect join format"); } } /* * Refreshes game list */ moa = new MouseOverArea(arg0, refreshButton, 50, 600, refreshButton.getWidth(), refreshButton.getHeight()); if (moa.isMouseOver() && Mouse.isButtonDown(0) && !pressedRefresh) { pressedRefresh = true; System.out.println("PRESSED! Refresh"); printGames(); } ArrayList<String> chatList = cch.getMessage(); addNewLines(chatList); popMessages(chatList); } private void addNewLines(ArrayList<String> chatList) { for(int i = 0; i< chatList.size(); i++){ String s = chatList.get(i); if(s.length()>50){ String firstString = s.substring(0, 49); String lastString = s.substring(49,s.length()); String totString = firstString+"\n"+lastString; chatList.set(i, totString); } } } private void printGames() { cch.refreshGames(); gamesList = cch.getGames(); String text = ""; for (GameAddress address : gamesList) { text += address.getGameName(); text += " : "; text += address.getHost(); text += " : "; text += address.getPort(); text += "\n"; } gamesField.setText(text); System.out.println("GAMESLIST!!!!!\n" + text); } private int checkPortValidity() { int port = 0; try { port = Integer.parseInt(newGamePortField.getText()); if (port < 1024 || port > 65535) { return -1; } } catch (NumberFormatException e) { return -1; } return port; } /** * returns the id of this gamestate (must not have a duplicate) */ @Override public int getID() { // TODO Auto-generated method stub return ID; } /** * outputs the text returned by the inputthread to the chat window, pushes * older messages down the list * * @param chatList */ private void popMessages(ArrayList<String> chatList) { int clSize = chatList.size(); for (int t = 0; t < clSize; t++) { for (int i = chatMessages.length - 1; i > 0; i--) { chatMessages[i] = chatMessages[i - 1]; } chatMessages[0] = chatList.get(t); } String messages = ""; for (int i = 0; i < chatMessages.length; i++) { if (chatMessages[i] != null) { messages += chatMessages[i]; messages += "\n"; } } // System.out.println(messages); outputText.setText(messages); } }
false
true
public void update(GameContainer arg0, StateBasedGame arg1, int arg2) throws SlickException { if (pressedSend && !Mouse.isButtonDown(0)) { // Prevents clicks being // counted several times pressedSend = false; } if (pressedNew && !Mouse.isButtonDown(0)) { // --||-- pressedNew = false; } if (pressedJoin && !Mouse.isButtonDown(0)) {// --||-- pressedJoin = false; } if (pressedRefresh && !Mouse.isButtonDown(0)) {// --||-- pressedRefresh = false; } /* * Sends chat message to server */ MouseOverArea moa = new MouseOverArea(arg0, sendButton, 400, 300, sendButton.getWidth(), sendButton.getHeight()); if (moa.isMouseOver() && Mouse.isButtonDown(0) && !(inputText.getText().equals("")) && !pressedSend) { System.out.println("PRESSED! Message is: " + inputText.getText()); pressedSend = true; boolean isAscii = CharMatcher.ASCII.matchesAllOf(inputText.getText()); if(isAscii){ cch.sendMessage(inputText.getText()); inputText.setText(""); } else{ errorMessages.setText("Illegal chat character"); } } /* * Creates new game in server */ moa = new MouseOverArea(arg0, newgameButton, 200, 300, newgameButton.getWidth(), newgameButton.getHeight()); if (moa.isMouseOver() && Mouse.isButtonDown(0) && !pressedNew) { System.out.println("PRESSED! NEW GAME"); pressedNew = true; int port = checkPortValidity(); if (newGameNameField.getText().equals("")) { errorMessages.setText("No game name"); } else if (newGamePortField.getText().equals("")) { errorMessages.setText("No port number"); } else if (port == -1) { errorMessages.setText("Invalid port number"); } else { cch.createNewLobby(newGameNameField.getText(), port); arg1.enterState(ClientLobbyState.ID); return; } // LobbyGameState // IMPLEMENT } /* * Joins existing game */ moa = new MouseOverArea(arg0, joingameButton, 600, 300, joingameButton.getWidth(), joingameButton.getHeight()); if (moa.isMouseOver() && Mouse.isButtonDown(0) && !pressedJoin) { pressedJoin = true; System.out.println("PRESSED! JOIN GAME"); String ipText = IpText.getText(); String[] hostAndPort = ipText.split(":"); if(hostAndPort.length == 2){ String host = hostAndPort[0]; String portString = hostAndPort[1]; int port = Integer.parseInt(portString); cch.joinLobby(host,port); arg1.enterState(ClientLobbyState.ID); }else{ errorMessages.setText("Incorrect join format"); } } /* * Refreshes game list */ moa = new MouseOverArea(arg0, refreshButton, 50, 600, refreshButton.getWidth(), refreshButton.getHeight()); if (moa.isMouseOver() && Mouse.isButtonDown(0) && !pressedRefresh) { pressedRefresh = true; System.out.println("PRESSED! Refresh"); printGames(); } ArrayList<String> chatList = cch.getMessage(); addNewLines(chatList); popMessages(chatList); }
public void update(GameContainer arg0, StateBasedGame arg1, int arg2) throws SlickException { if (pressedSend && !Mouse.isButtonDown(0)) { // Prevents clicks being // counted several times pressedSend = false; } if (pressedNew && !Mouse.isButtonDown(0)) { // --||-- pressedNew = false; } if (pressedJoin && !Mouse.isButtonDown(0)) {// --||-- pressedJoin = false; } if (pressedRefresh && !Mouse.isButtonDown(0)) {// --||-- pressedRefresh = false; } /* * Sends chat message to server */ MouseOverArea moa = new MouseOverArea(arg0, sendButton, 400, 300, sendButton.getWidth(), sendButton.getHeight()); if (moa.isMouseOver() && Mouse.isButtonDown(0) && !(inputText.getText().equals("")) && !pressedSend) { System.out.println("PRESSED! Message is: " + inputText.getText()); pressedSend = true; boolean isAscii = CharMatcher.ASCII.matchesAllOf(inputText.getText()); if(isAscii){ cch.sendMessage(inputText.getText()); inputText.setText(""); } else{ errorMessages.setText("Illegal chat character"); } } /* * Creates new game in server */ moa = new MouseOverArea(arg0, newgameButton, 200, 300, newgameButton.getWidth(), newgameButton.getHeight()); if (moa.isMouseOver() && Mouse.isButtonDown(0) && !pressedNew) { System.out.println("PRESSED! NEW GAME"); pressedNew = true; int port = checkPortValidity(); boolean isAscii = CharMatcher.ASCII.matchesAllOf(newGameNameField.getText()); if (newGameNameField.getText().equals("")) { errorMessages.setText("No game name"); } else if (newGamePortField.getText().equals("")) { errorMessages.setText("No port number"); } else if (port == -1) { errorMessages.setText("Invalid port number"); } else if(!isAscii){ errorMessages.setText("Invalid game name"); } else { cch.createNewLobby(newGameNameField.getText(), port); arg1.enterState(ClientLobbyState.ID); return; } // LobbyGameState // IMPLEMENT } /* * Joins existing game */ moa = new MouseOverArea(arg0, joingameButton, 600, 300, joingameButton.getWidth(), joingameButton.getHeight()); if (moa.isMouseOver() && Mouse.isButtonDown(0) && !pressedJoin) { pressedJoin = true; System.out.println("PRESSED! JOIN GAME"); String ipText = IpText.getText(); String[] hostAndPort = ipText.split(":"); if(hostAndPort.length == 2){ String host = hostAndPort[0]; String portString = hostAndPort[1]; int port = Integer.parseInt(portString); cch.joinLobby(host,port); arg1.enterState(ClientLobbyState.ID); }else{ errorMessages.setText("Incorrect join format"); } } /* * Refreshes game list */ moa = new MouseOverArea(arg0, refreshButton, 50, 600, refreshButton.getWidth(), refreshButton.getHeight()); if (moa.isMouseOver() && Mouse.isButtonDown(0) && !pressedRefresh) { pressedRefresh = true; System.out.println("PRESSED! Refresh"); printGames(); } ArrayList<String> chatList = cch.getMessage(); addNewLines(chatList); popMessages(chatList); }
diff --git a/src/share/classes/com/sun/tools/javah/StaticJNIClassHelper.java b/src/share/classes/com/sun/tools/javah/StaticJNIClassHelper.java index 103c1c69..a1236e70 100644 --- a/src/share/classes/com/sun/tools/javah/StaticJNIClassHelper.java +++ b/src/share/classes/com/sun/tools/javah/StaticJNIClassHelper.java @@ -1,389 +1,392 @@ /* * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tools.javah; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import com.sun.tools.javah.staticjni.ArrayCallback; import com.sun.tools.javah.staticjni.Callback; import com.sun.tools.javah.staticjni.ExceptionCallback; import com.sun.tools.javah.staticjni.FieldCallback; import net.xymus.staticjni.NativeArrayAccess; import net.xymus.staticjni.NativeArrayAccesses; import net.xymus.staticjni.NativeArrayAccessCritical; import net.xymus.staticjni.NativeArrayAccessesCritical; import net.xymus.staticjni.NativeCall; import net.xymus.staticjni.NativeCalls; import net.xymus.staticjni.NativeNew; import net.xymus.staticjni.NativeNews; import net.xymus.staticjni.NativeSuperCall; /** * Header file generator for JNI. * * Not a true Gen, actually a wrapper for 3 other Gens */ public class StaticJNIClassHelper { StaticJNIClassHelper( StaticJNI gen ) { this.gen = gen; } StaticJNI gen; TypeElement currentClass = null; // Explicit calls Set<Callback> callbacks = new HashSet<Callback>(); Set<FieldCallback> fieldCallbacks = new HashSet<FieldCallback>(); Set<Callback> superCallbacks = new HashSet<Callback>(); Set<Callback> constCallbacks = new HashSet<Callback>(); Set<ExceptionCallback> exceptionCallbacks = new HashSet<ExceptionCallback>(); Set<ArrayCallback> arrayCallbacks = new HashSet<ArrayCallback>(); // Referred types Set<TypeMirror> referredTypes = new HashSet<TypeMirror>(); @SuppressWarnings("unchecked") public void setCurrentClass ( TypeElement clazz ) { if ( clazz != currentClass ) { currentClass = clazz; callbacks.clear(); fieldCallbacks.clear(); + superCallbacks.clear(); + constCallbacks.clear(); + exceptionCallbacks.clear(); arrayCallbacks.clear(); referredTypes.clear(); List<ExecutableElement> classmethods = ElementFilter.methodsIn(clazz.getEnclosedElements()); for (ExecutableElement md: classmethods) { if(md.getModifiers().contains(Modifier.NATIVE)){ TypeMirror mtr = gen.types.erasure(md.getReturnType()); // return type if ( gen.advancedStaticType( mtr ) ) referredTypes.add( mtr ); // params type List<? extends VariableElement> paramargs = md.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type if (! md.getModifiers().contains(Modifier.STATIC) ) { TypeMirror t = clazz.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // scan annotations for NativeCalls List<? extends AnnotationMirror> annotations = md.getAnnotationMirrors(); for ( AnnotationMirror annotation: annotations ) { String str = annotation.getAnnotationType().toString(); // NativeCall annotation if ( str.equals( NativeCall.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v)) { tryToRegisterNativeCall( clazz, md, v.toString(), callbacks, fieldCallbacks ); } } // NativeCalls annotation if ( str.equals( NativeCalls.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { // elems.getConstantExpression tryToRegisterNativeCall( clazz, md, ((AnnotationValue)e).getValue().toString(), callbacks, fieldCallbacks ); } } // NativeNew annotation if ( str.equals( NativeNew.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v)) { tryToRegisterNativeNew( clazz, md, v.toString(), constCallbacks ); } } // NativeNews annotation if ( str.equals( NativeNews.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeNew( clazz, md, ((AnnotationValue)e).getValue().toString(), constCallbacks ); } } // super if ( str.equals( NativeSuperCall.class.getCanonicalName() ) ) { superCallbacks.add( new Callback(clazz, md) ); } // arrays if ( str.equals( NativeArrayAccess.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v) ) tryToRegisterNativeArrayAccess( clazz, md, v.toString(), arrayCallbacks, false ); } } if ( str.equals( NativeArrayAccesses.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeArrayAccess( clazz, md, ((AnnotationValue)e).getValue().toString(), arrayCallbacks, false ); } } } // arrays critical if ( str.equals( NativeArrayAccessCritical.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v) ) tryToRegisterNativeArrayAccess( clazz, md, v.toString(), arrayCallbacks, true ); } } if ( str.equals( NativeArrayAccessesCritical.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeArrayAccess( clazz, md, ((AnnotationValue)e).getValue().toString(), arrayCallbacks, true ); } } } } // check possible throw from the throws keyword for ( TypeMirror t : md.getThrownTypes() ) { exceptionCallbacks.add( new ExceptionCallback(t) ); } // Scan imports for types for ( Callback cb: callbacks ) { ExecutableElement m = cb.meth; TypeMirror r = gen.types.erasure(m.getReturnType()); if ( gen.advancedStaticType(r) ) referredTypes.add( r ); paramargs = m.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type if (! m.getModifiers().contains(Modifier.STATIC) ) { TypeMirror t = cb.recvType.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } } for ( Callback cb: constCallbacks ) { ExecutableElement m = cb.meth; TypeMirror r = gen.types.erasure(m.getReturnType()); if ( gen.advancedStaticType(r) ) referredTypes.add( r ); paramargs = m.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type TypeMirror t = cb.recvType.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } for ( FieldCallback f: fieldCallbacks ) { TypeMirror t = f.recvType.asType(); if ( gen.advancedStaticType(t) ) referredTypes.add( t ); t = f.field.asType(); if ( gen.advancedStaticType(t) ) referredTypes.add( t ); } } } } } void tryToRegisterNativeCall(TypeElement clazz, ExecutableElement from_meth, String name, Set<Callback> callbacks, Set<FieldCallback> callbacks_to_field ) { TypeElement from_clazz = clazz; String from = from_clazz.toString() + "." + from_meth.toString(); // modifies args for non local calls String[] words = name.split(" "); if ( words.length > 1 ) { Element e = gen.elems.getTypeElement( words[0] ); if ( e != null && TypeElement.class.isInstance(e) ) { clazz = (TypeElement)e; name = words[1]; } else { gen.util.error("err.staticjni.classnotfound", words[0], from ); } } // try to find in methods List<ExecutableElement> methods = ElementFilter.methodsIn( clazz.getEnclosedElements() ); for (ExecutableElement m: methods) { if ( name.toString().equals( m.getSimpleName().toString() ) ) { callbacks.add( new Callback(clazz, m)); return; } } // try to find in fields List<VariableElement> fields = ElementFilter.fieldsIn( clazz.getEnclosedElements() ); for ( VariableElement f: fields ) { if ( f.getSimpleName().toString().equals( name ) ) { callbacks_to_field.add( new FieldCallback(clazz, f) ); return; } } gen.util.error("err.staticjni.methnotfound", name, from ); } void tryToRegisterNativeNew(TypeElement clazz, ExecutableElement from_meth, String name, Set<Callback> callbacks ) { TypeElement from_clazz = clazz; String from = from_clazz.toString() + "." + from_meth.toString(); // find class String[] words = name.split(" "); //if ( words.length > 1 ) { Element e = gen.elems.getTypeElement( words[0] ); if ( e != null && TypeElement.class.isInstance(e) ) { clazz = (TypeElement)e; } else { gen.util.error("err.staticjni.classnotfound", words[0], from ); } //} // return first constructor List<ExecutableElement> consts = ElementFilter.constructorsIn( clazz.getEnclosedElements() ); for (ExecutableElement c: consts) { callbacks.add( new Callback(clazz, c)); return; } gen.util.error("err.staticjni.methnotfound", name, from ); } void tryToRegisterNativeArrayAccess(TypeElement clazz, ExecutableElement from_meth, String name, Set<ArrayCallback> callbacks, boolean critical ) { TypeElement from_clazz = clazz; String from = from_clazz.toString() + "." + from_meth.toString(); int p = name.lastIndexOf("[]"); if ( p == -1 ) { gen.util.error("err.staticjni.arrayformatinvalid", name ); return; } // find class TypeMirror t = javaNameToType( name ); if ( t != null ) { callbacks.add(new ArrayCallback((ArrayType)t, critical )); return; } else { gen.util.error("err.staticjni.classnotfound", name, from ); } gen.util.error("err.staticjni.methnotfound", name, from ); } TypeMirror javaNameToType( String name ) { TypeMirror t; int p = name.lastIndexOf("[]"); if ( p != -1 ) { String sub_name = name.substring(0,p); t = javaNameToType( sub_name ); return gen.types.getArrayType(t); } if(name.equals("void")) return gen.types.getPrimitiveType( TypeKind.VOID ); if(name.equals("boolean")) return gen.types.getPrimitiveType( TypeKind.INT ); if(name.equals("byte")) return gen.types.getPrimitiveType( TypeKind.BYTE ); if(name.equals("char")) return gen.types.getPrimitiveType( TypeKind.CHAR ); if(name.equals("short")) return gen.types.getPrimitiveType( TypeKind.SHORT ); if(name.equals("int")) return gen.types.getPrimitiveType( TypeKind.INT ); if(name.equals("long")) return gen.types.getPrimitiveType( TypeKind.LONG ); if(name.equals("float")) return gen.types.getPrimitiveType( TypeKind.FLOAT ); if(name.equals("double")) return gen.types.getPrimitiveType( TypeKind.DOUBLE ); return gen.elems.getTypeElement( name ).asType(); } }
true
true
public void setCurrentClass ( TypeElement clazz ) { if ( clazz != currentClass ) { currentClass = clazz; callbacks.clear(); fieldCallbacks.clear(); arrayCallbacks.clear(); referredTypes.clear(); List<ExecutableElement> classmethods = ElementFilter.methodsIn(clazz.getEnclosedElements()); for (ExecutableElement md: classmethods) { if(md.getModifiers().contains(Modifier.NATIVE)){ TypeMirror mtr = gen.types.erasure(md.getReturnType()); // return type if ( gen.advancedStaticType( mtr ) ) referredTypes.add( mtr ); // params type List<? extends VariableElement> paramargs = md.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type if (! md.getModifiers().contains(Modifier.STATIC) ) { TypeMirror t = clazz.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // scan annotations for NativeCalls List<? extends AnnotationMirror> annotations = md.getAnnotationMirrors(); for ( AnnotationMirror annotation: annotations ) { String str = annotation.getAnnotationType().toString(); // NativeCall annotation if ( str.equals( NativeCall.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v)) { tryToRegisterNativeCall( clazz, md, v.toString(), callbacks, fieldCallbacks ); } } // NativeCalls annotation if ( str.equals( NativeCalls.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { // elems.getConstantExpression tryToRegisterNativeCall( clazz, md, ((AnnotationValue)e).getValue().toString(), callbacks, fieldCallbacks ); } } // NativeNew annotation if ( str.equals( NativeNew.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v)) { tryToRegisterNativeNew( clazz, md, v.toString(), constCallbacks ); } } // NativeNews annotation if ( str.equals( NativeNews.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeNew( clazz, md, ((AnnotationValue)e).getValue().toString(), constCallbacks ); } } // super if ( str.equals( NativeSuperCall.class.getCanonicalName() ) ) { superCallbacks.add( new Callback(clazz, md) ); } // arrays if ( str.equals( NativeArrayAccess.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v) ) tryToRegisterNativeArrayAccess( clazz, md, v.toString(), arrayCallbacks, false ); } } if ( str.equals( NativeArrayAccesses.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeArrayAccess( clazz, md, ((AnnotationValue)e).getValue().toString(), arrayCallbacks, false ); } } } // arrays critical if ( str.equals( NativeArrayAccessCritical.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v) ) tryToRegisterNativeArrayAccess( clazz, md, v.toString(), arrayCallbacks, true ); } } if ( str.equals( NativeArrayAccessesCritical.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeArrayAccess( clazz, md, ((AnnotationValue)e).getValue().toString(), arrayCallbacks, true ); } } } } // check possible throw from the throws keyword for ( TypeMirror t : md.getThrownTypes() ) { exceptionCallbacks.add( new ExceptionCallback(t) ); } // Scan imports for types for ( Callback cb: callbacks ) { ExecutableElement m = cb.meth; TypeMirror r = gen.types.erasure(m.getReturnType()); if ( gen.advancedStaticType(r) ) referredTypes.add( r ); paramargs = m.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type if (! m.getModifiers().contains(Modifier.STATIC) ) { TypeMirror t = cb.recvType.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } } for ( Callback cb: constCallbacks ) { ExecutableElement m = cb.meth; TypeMirror r = gen.types.erasure(m.getReturnType()); if ( gen.advancedStaticType(r) ) referredTypes.add( r ); paramargs = m.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type TypeMirror t = cb.recvType.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } for ( FieldCallback f: fieldCallbacks ) { TypeMirror t = f.recvType.asType(); if ( gen.advancedStaticType(t) ) referredTypes.add( t ); t = f.field.asType(); if ( gen.advancedStaticType(t) ) referredTypes.add( t ); } } } } }
public void setCurrentClass ( TypeElement clazz ) { if ( clazz != currentClass ) { currentClass = clazz; callbacks.clear(); fieldCallbacks.clear(); superCallbacks.clear(); constCallbacks.clear(); exceptionCallbacks.clear(); arrayCallbacks.clear(); referredTypes.clear(); List<ExecutableElement> classmethods = ElementFilter.methodsIn(clazz.getEnclosedElements()); for (ExecutableElement md: classmethods) { if(md.getModifiers().contains(Modifier.NATIVE)){ TypeMirror mtr = gen.types.erasure(md.getReturnType()); // return type if ( gen.advancedStaticType( mtr ) ) referredTypes.add( mtr ); // params type List<? extends VariableElement> paramargs = md.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type if (! md.getModifiers().contains(Modifier.STATIC) ) { TypeMirror t = clazz.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // scan annotations for NativeCalls List<? extends AnnotationMirror> annotations = md.getAnnotationMirrors(); for ( AnnotationMirror annotation: annotations ) { String str = annotation.getAnnotationType().toString(); // NativeCall annotation if ( str.equals( NativeCall.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v)) { tryToRegisterNativeCall( clazz, md, v.toString(), callbacks, fieldCallbacks ); } } // NativeCalls annotation if ( str.equals( NativeCalls.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { // elems.getConstantExpression tryToRegisterNativeCall( clazz, md, ((AnnotationValue)e).getValue().toString(), callbacks, fieldCallbacks ); } } // NativeNew annotation if ( str.equals( NativeNew.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v)) { tryToRegisterNativeNew( clazz, md, v.toString(), constCallbacks ); } } // NativeNews annotation if ( str.equals( NativeNews.class.getCanonicalName() ) ) for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeNew( clazz, md, ((AnnotationValue)e).getValue().toString(), constCallbacks ); } } // super if ( str.equals( NativeSuperCall.class.getCanonicalName() ) ) { superCallbacks.add( new Callback(clazz, md) ); } // arrays if ( str.equals( NativeArrayAccess.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v) ) tryToRegisterNativeArrayAccess( clazz, md, v.toString(), arrayCallbacks, false ); } } if ( str.equals( NativeArrayAccesses.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeArrayAccess( clazz, md, ((AnnotationValue)e).getValue().toString(), arrayCallbacks, false ); } } } // arrays critical if ( str.equals( NativeArrayAccessCritical.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( String.class.isInstance(v) ) tryToRegisterNativeArrayAccess( clazz, md, v.toString(), arrayCallbacks, true ); } } if ( str.equals( NativeArrayAccessesCritical.class.getCanonicalName() ) ) { for ( ExecutableElement p: annotation.getElementValues().keySet() ) if ( p.getSimpleName().toString().equals( "value" ) ) { Object v = annotation.getElementValues().get( p ).getValue(); if ( List.class.isInstance(v) ) for ( Object e: (List<Object>)v ) { tryToRegisterNativeArrayAccess( clazz, md, ((AnnotationValue)e).getValue().toString(), arrayCallbacks, true ); } } } } // check possible throw from the throws keyword for ( TypeMirror t : md.getThrownTypes() ) { exceptionCallbacks.add( new ExceptionCallback(t) ); } // Scan imports for types for ( Callback cb: callbacks ) { ExecutableElement m = cb.meth; TypeMirror r = gen.types.erasure(m.getReturnType()); if ( gen.advancedStaticType(r) ) referredTypes.add( r ); paramargs = m.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type if (! m.getModifiers().contains(Modifier.STATIC) ) { TypeMirror t = cb.recvType.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } } for ( Callback cb: constCallbacks ) { ExecutableElement m = cb.meth; TypeMirror r = gen.types.erasure(m.getReturnType()); if ( gen.advancedStaticType(r) ) referredTypes.add( r ); paramargs = m.getParameters(); for (VariableElement p: paramargs) { TypeMirror t = gen.types.erasure(p.asType()); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } // self type TypeMirror t = cb.recvType.asType(); if ( gen.advancedStaticType( t ) ) referredTypes.add( t ); } for ( FieldCallback f: fieldCallbacks ) { TypeMirror t = f.recvType.asType(); if ( gen.advancedStaticType(t) ) referredTypes.add( t ); t = f.field.asType(); if ( gen.advancedStaticType(t) ) referredTypes.add( t ); } } } } }
diff --git a/src/org/apache/xerces/impl/xs/XMLSchemaValidator.java b/src/org/apache/xerces/impl/xs/XMLSchemaValidator.java index 30b262a2..99737feb 100644 --- a/src/org/apache/xerces/impl/xs/XMLSchemaValidator.java +++ b/src/org/apache/xerces/impl/xs/XMLSchemaValidator.java @@ -1,4813 +1,4814 @@ /* * 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.xerces.impl.xs; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Stack; import java.util.Vector; import javax.xml.XMLConstants; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.RevalidationHandler; import org.apache.xerces.impl.XMLEntityManager; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.dv.DatatypeException; import org.apache.xerces.impl.dv.InvalidDatatypeValueException; import org.apache.xerces.impl.dv.ValidatedInfo; import org.apache.xerces.impl.dv.XSSimpleType; import org.apache.xerces.impl.dv.xs.TypeValidatorHelper; import org.apache.xerces.impl.dv.xs.XSSimpleTypeDecl; import org.apache.xerces.impl.validation.ConfigurableValidationState; import org.apache.xerces.impl.validation.ValidationManager; import org.apache.xerces.impl.validation.ValidationState; import org.apache.xerces.impl.xs.identity.Field; import org.apache.xerces.impl.xs.identity.FieldActivator; import org.apache.xerces.impl.xs.identity.IdentityConstraint; import org.apache.xerces.impl.xs.identity.KeyRef; import org.apache.xerces.impl.xs.identity.Selector; import org.apache.xerces.impl.xs.identity.UniqueOrKey; import org.apache.xerces.impl.xs.identity.ValueStore; import org.apache.xerces.impl.xs.identity.XPathMatcher; import org.apache.xerces.impl.xs.models.CMBuilder; import org.apache.xerces.impl.xs.models.CMNodeFactory; import org.apache.xerces.impl.xs.models.XSCMValidator; import org.apache.xerces.impl.xs.util.XSTypeHelper; import org.apache.xerces.util.AugmentationsImpl; import org.apache.xerces.util.IntStack; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLAttributesImpl; import org.apache.xerces.util.XMLChar; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.util.URI.MalformedURIException; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLDocumentHandler; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XMLResourceIdentifier; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.xni.parser.XMLComponent; import org.apache.xerces.xni.parser.XMLComponentManager; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLDocumentFilter; import org.apache.xerces.xni.parser.XMLDocumentSource; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xs.AttributePSVI; import org.apache.xerces.xs.ElementPSVI; import org.apache.xerces.xs.ShortList; import org.apache.xerces.xs.StringList; import org.apache.xerces.xs.XSConstants; import org.apache.xerces.xs.XSObjectList; import org.apache.xerces.xs.XSSimpleTypeDefinition; import org.apache.xerces.xs.XSTypeDefinition; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; /** * The XML Schema validator. The validator implements a document * filter: receiving document events from the scanner; validating * the content and structure; augmenting the InfoSet, if applicable; * and notifying the parser of the information resulting from the * validation process. * <p> * This component requires the following features and properties from the * component manager that uses it: * <ul> * <li>http://xml.org/sax/features/validation</li> * <li>http://apache.org/xml/properties/internal/symbol-table</li> * <li>http://apache.org/xml/properties/internal/error-reporter</li> * <li>http://apache.org/xml/properties/internal/entity-resolver</li> * </ul> * * @xerces.internal * * @author Sandy Gao IBM * @author Elena Litani IBM * @author Andy Clark IBM * @author Neeraj Bajaj, Sun Microsystems, inc. * @version $Id$ */ public class XMLSchemaValidator implements XMLComponent, XMLDocumentFilter, FieldActivator, RevalidationHandler, XSElementDeclHelper { // // Constants // private static final boolean DEBUG = false; // feature identifiers /** Feature identifier: validation. */ protected static final String VALIDATION = Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE; /** Feature identifier: validation. */ protected static final String SCHEMA_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE; /** Feature identifier: schema full checking*/ protected static final String SCHEMA_FULL_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING; /** Feature identifier: dynamic validation. */ protected static final String DYNAMIC_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.DYNAMIC_VALIDATION_FEATURE; /** Feature identifier: expose schema normalized value */ protected static final String NORMALIZE_DATA = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_NORMALIZED_VALUE; /** Feature identifier: send element default value via characters() */ protected static final String SCHEMA_ELEMENT_DEFAULT = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_ELEMENT_DEFAULT; /** Feature identifier: augment PSVI */ protected static final String SCHEMA_AUGMENT_PSVI = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_AUGMENT_PSVI; /** Feature identifier: whether to recognize java encoding names */ protected static final String ALLOW_JAVA_ENCODINGS = Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE; /** Feature identifier: standard uri conformant feature. */ protected static final String STANDARD_URI_CONFORMANT_FEATURE = Constants.XERCES_FEATURE_PREFIX + Constants.STANDARD_URI_CONFORMANT_FEATURE; /** Feature: generate synthetic annotations */ protected static final String GENERATE_SYNTHETIC_ANNOTATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.GENERATE_SYNTHETIC_ANNOTATIONS_FEATURE; /** Feature identifier: validate annotations. */ protected static final String VALIDATE_ANNOTATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.VALIDATE_ANNOTATIONS_FEATURE; /** Feature identifier: honour all schemaLocations */ protected static final String HONOUR_ALL_SCHEMALOCATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.HONOUR_ALL_SCHEMALOCATIONS_FEATURE; /** Feature identifier: use grammar pool only */ protected static final String USE_GRAMMAR_POOL_ONLY = Constants.XERCES_FEATURE_PREFIX + Constants.USE_GRAMMAR_POOL_ONLY_FEATURE; /** Feature identifier: whether to continue parsing a schema after a fatal error is encountered */ protected static final String CONTINUE_AFTER_FATAL_ERROR = Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE; protected static final String PARSER_SETTINGS = Constants.XERCES_FEATURE_PREFIX + Constants.PARSER_SETTINGS; /** Feature identifier: namespace growth */ protected static final String NAMESPACE_GROWTH = Constants.XERCES_FEATURE_PREFIX + Constants.NAMESPACE_GROWTH_FEATURE; /** Feature identifier: tolerate duplicates */ protected static final String TOLERATE_DUPLICATES = Constants.XERCES_FEATURE_PREFIX + Constants.TOLERATE_DUPLICATES_FEATURE; /** Feature identifier: whether to ignore xsi:type attributes until a global element declaration is encountered */ protected static final String IGNORE_XSI_TYPE = Constants.XERCES_FEATURE_PREFIX + Constants.IGNORE_XSI_TYPE_FEATURE; /** Feature identifier: whether to ignore ID/IDREF errors */ protected static final String ID_IDREF_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.ID_IDREF_CHECKING_FEATURE; /** Feature identifier: whether to ignore unparsed entity errors */ protected static final String UNPARSED_ENTITY_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.UNPARSED_ENTITY_CHECKING_FEATURE; /** Feature identifier: whether to ignore identity constraint errors */ protected static final String IDENTITY_CONSTRAINT_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.IDC_CHECKING_FEATURE; /** Feature identifier: whether to ignore type alternatives */ protected static final String TYPE_ALTERNATIVES_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.TYPE_ALTERNATIVES_CHEKING_FEATURE; // property identifiers /** Property identifier: symbol table. */ public static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: error reporter. */ public static final String ERROR_REPORTER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; /** Property identifier: entity resolver. */ public static final String ENTITY_RESOLVER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; /** Property identifier: grammar pool. */ public static final String XMLGRAMMAR_POOL = Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY; protected static final String VALIDATION_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY; protected static final String ENTITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY; /** Property identifier: schema location. */ protected static final String SCHEMA_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_LOCATION; /** Property identifier: no namespace schema location. */ protected static final String SCHEMA_NONS_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_NONS_LOCATION; /** Property identifier: JAXP schema source. */ protected static final String JAXP_SCHEMA_SOURCE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE; /** Property identifier: JAXP schema language. */ protected static final String JAXP_SCHEMA_LANGUAGE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE; /** Property identifier: root type definition. */ protected static final String ROOT_TYPE_DEF = Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_TYPE_DEFINITION_PROPERTY; /** Property identifier: root element declaration. */ protected static final String ROOT_ELEMENT_DECL = Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_ELEMENT_DECLARATION_PROPERTY; /** Property identifier: Schema DV Factory */ protected static final String SCHEMA_DV_FACTORY = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_DV_FACTORY_PROPERTY; /** Property identifier: xml schema version. */ protected static final String XML_SCHEMA_VERSION = Constants.XERCES_PROPERTY_PREFIX + Constants.XML_SCHEMA_VERSION_PROPERTY; // recognized features and properties /** Recognized features. */ private static final String[] RECOGNIZED_FEATURES = { VALIDATION, SCHEMA_VALIDATION, DYNAMIC_VALIDATION, SCHEMA_FULL_CHECKING, ALLOW_JAVA_ENCODINGS, CONTINUE_AFTER_FATAL_ERROR, STANDARD_URI_CONFORMANT_FEATURE, GENERATE_SYNTHETIC_ANNOTATIONS, VALIDATE_ANNOTATIONS, HONOUR_ALL_SCHEMALOCATIONS, USE_GRAMMAR_POOL_ONLY, IGNORE_XSI_TYPE, ID_IDREF_CHECKING, IDENTITY_CONSTRAINT_CHECKING, UNPARSED_ENTITY_CHECKING, NAMESPACE_GROWTH, TOLERATE_DUPLICATES, TYPE_ALTERNATIVES_CHECKING }; /** Feature defaults. */ private static final Boolean[] FEATURE_DEFAULTS = { null, // NOTE: The following defaults are nulled out on purpose. // If they are set, then when the XML Schema validator // is constructed dynamically, these values may override // those set by the application. This goes against the // whole purpose of XMLComponent#getFeatureDefault but // it can't be helped in this case. -Ac // NOTE: Instead of adding default values here, add them (and // the corresponding recognized features) to the objects // that have an XMLSchemaValidator instance as a member, // such as the parser configurations. -PM null, //Boolean.FALSE, null, //Boolean.FALSE, null, //Boolean.FALSE, null, //Boolean.FALSE, null, //Boolean.FALSE, null, null, null, null, null, null, null, null, null, null, null, null }; /** Recognized properties. */ private static final String[] RECOGNIZED_PROPERTIES = { SYMBOL_TABLE, ERROR_REPORTER, ENTITY_RESOLVER, VALIDATION_MANAGER, SCHEMA_LOCATION, SCHEMA_NONS_LOCATION, JAXP_SCHEMA_SOURCE, JAXP_SCHEMA_LANGUAGE, ROOT_TYPE_DEF, ROOT_ELEMENT_DECL, SCHEMA_DV_FACTORY, XML_SCHEMA_VERSION, }; /** Property defaults. */ private static final Object[] PROPERTY_DEFAULTS = { null, null, null, null, null, null, null, null, null, null, null, null}; // this is the number of valuestores of each kind // we expect an element to have. It's almost // never > 1; so leave it at that. protected static final int ID_CONSTRAINT_NUM = 1; // xsi:* attribute declarations static final XSAttributeDecl XSI_TYPE = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE); static final XSAttributeDecl XSI_NIL = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL); static final XSAttributeDecl XSI_SCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION); static final XSAttributeDecl XSI_NONAMESPACESCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); // private static final Hashtable EMPTY_TABLE = new Hashtable(); // // Data // /** current PSVI element info */ protected ElementPSVImpl fCurrentPSVI = new ElementPSVImpl(); // since it is the responsibility of each component to an // Augmentations parameter if one is null, to save ourselves from // having to create this object continually, it is created here. // If it is not present in calls that we're passing on, we *must* // clear this before we introduce it into the pipeline. protected final AugmentationsImpl fAugmentations = new AugmentationsImpl(); // this is included for the convenience of handleEndElement protected XMLString fDefaultValue; // Validation features protected boolean fDynamicValidation = false; protected boolean fSchemaDynamicValidation = false; protected boolean fDoValidation = false; protected boolean fFullChecking = false; protected boolean fNormalizeData = true; protected boolean fSchemaElementDefault = true; protected boolean fAugPSVI = true; protected boolean fIdConstraint = false; protected boolean fUseGrammarPoolOnly = false; // Namespace growth feature protected boolean fNamespaceGrowth = false; /** Schema type: None, DTD, Schema */ private String fSchemaType = null; // to indicate whether we are in the scope of entity reference or CData protected boolean fEntityRef = false; protected boolean fInCDATA = false; // properties /** Symbol table. */ protected SymbolTable fSymbolTable; /** * While parsing a document, keep the location of the document. */ private XMLLocator fLocator; /** * A wrapper of the standard error reporter. We'll store all schema errors * in this wrapper object, so that we can get all errors (error codes) of * a specific element. This is useful for PSVI. */ protected final class XSIErrorReporter { // the error reporter property XMLErrorReporter fErrorReporter; // store error codes; starting position of the errors for each element; // number of element (depth); and whether to record error Vector fErrors = new Vector(); int[] fContext = new int[INITIAL_STACK_SIZE]; int fContextCount; // set the external error reporter, clear errors public void reset(XMLErrorReporter errorReporter) { fErrorReporter = errorReporter; fErrors.removeAllElements(); fContextCount = 0; } // should be called when starting process an element or an attribute. // store the starting position for the current context public void pushContext() { if (!fAugPSVI) { return; } // resize array if necessary if (fContextCount == fContext.length) { int newSize = fContextCount + INC_STACK_SIZE; int[] newArray = new int[newSize]; System.arraycopy(fContext, 0, newArray, 0, fContextCount); fContext = newArray; } fContext[fContextCount++] = fErrors.size(); } // should be called on endElement: get all errors of the current element public String[] popContext() { if (!fAugPSVI) { return null; } // get starting position of the current element int contextPos = fContext[--fContextCount]; // number of errors of the current element int size = fErrors.size() - contextPos; // if no errors, return null if (size == 0) return null; // copy errors from the list to an string array String[] errors = new String[size]; for (int i = 0; i < size; i++) { errors[i] = (String) fErrors.elementAt(contextPos + i); } // remove errors of the current element fErrors.setSize(contextPos); return errors; } // should be called when an attribute is done: get all errors of // this attribute, but leave the errors to the containing element // also called after an element was strictly assessed. public String[] mergeContext() { if (!fAugPSVI) { return null; } // get starting position of the current element int contextPos = fContext[--fContextCount]; // number of errors of the current element int size = fErrors.size() - contextPos; // if no errors, return null if (size == 0) return null; // copy errors from the list to an string array String[] errors = new String[size]; for (int i = 0; i < size; i++) { errors[i] = (String) fErrors.elementAt(contextPos + i); } // don't resize the vector: leave the errors for this attribute // to the containing element return errors; } public void reportError(String domain, String key, Object[] arguments, short severity) throws XNIException { String message = fErrorReporter.reportError(domain, key, arguments, severity); if (fAugPSVI) { fErrors.addElement(key); fErrors.addElement(message); } } // reportError(String,String,Object[],short) public void reportError( XMLLocator location, String domain, String key, Object[] arguments, short severity) throws XNIException { String message = fErrorReporter.reportError(location, domain, key, arguments, severity); if (fAugPSVI) { fErrors.addElement(key); fErrors.addElement(message); } } // reportError(XMLLocator,String,String,Object[],short) } /** Error reporter. */ protected final XSIErrorReporter fXSIErrorReporter = new XSIErrorReporter(); /** Entity resolver */ protected XMLEntityResolver fEntityResolver; // updated during reset protected ValidationManager fValidationManager = null; protected ConfigurableValidationState fValidationState = new ConfigurableValidationState(); protected XMLGrammarPool fGrammarPool; // schema location property values protected String fExternalSchemas = null; protected String fExternalNoNamespaceSchema = null; //JAXP Schema Source property protected Object fJaxpSchemaSource = null; /** Schema Grammar Description passed, to give a chance to application to supply the Grammar */ protected final XSDDescription fXSDDescription = new XSDDescription(); protected final Hashtable fLocationPairs = new Hashtable(); protected final Hashtable fExpandedLocationPairs = new Hashtable(); protected final ArrayList fUnparsedLocations = new ArrayList(); /** XML Schema 1.1 Support */ short fSchemaVersion; /** XML Schema Constraints */ XSConstraints fXSConstraints; // handlers /** Document handler. */ protected XMLDocumentHandler fDocumentHandler; protected XMLDocumentSource fDocumentSource; // // XMLComponent methods // /** * Returns a list of feature identifiers that are recognized by * this component. This method may return null if no features * are recognized by this component. */ public String[] getRecognizedFeatures() { return (String[]) (RECOGNIZED_FEATURES.clone()); } // getRecognizedFeatures():String[] /** * Sets the state of a feature. This method is called by the component * manager any time after reset when a feature changes state. * <p> * <strong>Note:</strong> Components should silently ignore features * that do not affect the operation of the component. * * @param featureId The feature identifier. * @param state The state of the feature. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setFeature(String featureId, boolean state) throws XMLConfigurationException { } // setFeature(String,boolean) /** * Returns a list of property identifiers that are recognized by * this component. This method may return null if no properties * are recognized by this component. */ public String[] getRecognizedProperties() { return (String[]) (RECOGNIZED_PROPERTIES.clone()); } // getRecognizedProperties():String[] /** * Sets the value of a property. This method is called by the component * manager any time after reset when a property changes value. * <p> * <strong>Note:</strong> Components should silently ignore properties * that do not affect the operation of the component. * * @param propertyId The property identifier. * @param value The value of the property. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setProperty(String propertyId, Object value) throws XMLConfigurationException { if (propertyId.equals(ROOT_TYPE_DEF)) { if (value == null) { fRootTypeQName = null; fRootTypeDefinition = null; } else if (value instanceof javax.xml.namespace.QName) { fRootTypeQName = (javax.xml.namespace.QName) value; fRootTypeDefinition = null; } else { fRootTypeDefinition = (XSTypeDefinition) value; fRootTypeQName = null; } } else if (propertyId.equals(ROOT_ELEMENT_DECL)) { if (value == null) { fRootElementDeclQName = null; fRootElementDeclaration = null; } else if (value instanceof javax.xml.namespace.QName) { fRootElementDeclQName = (javax.xml.namespace.QName) value; fRootElementDeclaration = null; } else { fRootElementDeclaration = (XSElementDecl) value; fRootElementDeclQName = null; } } else if (propertyId.equals(XML_SCHEMA_VERSION)) { // TODO: do we use fSchemaLoader.setProperty fSchemaLoader.setSchemaVersion((String)value); fSchemaVersion = fSchemaLoader.getSchemaVersion(); fXSConstraints = fSchemaLoader.getXSConstraints(); } } // setProperty(String,Object) /** * Returns the default state for a feature, or null if this * component does not want to report a default value for this * feature. * * @param featureId The feature identifier. * * @since Xerces 2.2.0 */ public Boolean getFeatureDefault(String featureId) { for (int i = 0; i < RECOGNIZED_FEATURES.length; i++) { if (RECOGNIZED_FEATURES[i].equals(featureId)) { return FEATURE_DEFAULTS[i]; } } return null; } // getFeatureDefault(String):Boolean /** * Returns the default state for a property, or null if this * component does not want to report a default value for this * property. * * @param propertyId The property identifier. * * @since Xerces 2.2.0 */ public Object getPropertyDefault(String propertyId) { for (int i = 0; i < RECOGNIZED_PROPERTIES.length; i++) { if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) { return PROPERTY_DEFAULTS[i]; } } return null; } // getPropertyDefault(String):Object // // XMLDocumentSource methods // /** Sets the document handler to receive information about the document. */ public void setDocumentHandler(XMLDocumentHandler documentHandler) { fDocumentHandler = documentHandler; } // setDocumentHandler(XMLDocumentHandler) /** Returns the document handler */ public XMLDocumentHandler getDocumentHandler() { return fDocumentHandler; } // setDocumentHandler(XMLDocumentHandler) // // XMLDocumentHandler methods // /** Sets the document source */ public void setDocumentSource(XMLDocumentSource source) { fDocumentSource = source; } // setDocumentSource /** Returns the document source */ public XMLDocumentSource getDocumentSource() { return fDocumentSource; } // getDocumentSource /** * The start of the document. * * @param locator The system identifier of the entity if the entity * is external, null otherwise. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param namespaceContext * The namespace context in effect at the * start of this document. * This object represents the current context. * Implementors of this class are responsible * for copying the namespace bindings from the * the current context (and its parent contexts) * if that information is important. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startDocument( XMLLocator locator, String encoding, NamespaceContext namespaceContext, Augmentations augs) throws XNIException { fValidationState.setNamespaceSupport(namespaceContext); fState4XsiType.setNamespaceSupport(namespaceContext); fState4ApplyDefault.setNamespaceSupport(namespaceContext); fLocator = locator; handleStartDocument(locator, encoding); // call handlers if (fDocumentHandler != null) { fDocumentHandler.startDocument(locator, encoding, namespaceContext, augs); } } // startDocument(XMLLocator,String) /** * Notifies of the presence of an XMLDecl line in the document. If * present, this method will be called immediately following the * startDocument call. * * @param version The XML version. * @param encoding The IANA encoding name of the document, or null if * not specified. * @param standalone The standalone value, or null if not specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void xmlDecl(String version, String encoding, String standalone, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.xmlDecl(version, encoding, standalone, augs); } } // xmlDecl(String,String,String) /** * Notifies of the presence of the DOCTYPE line in the document. * * @param rootElement The name of the root element. * @param publicId The public identifier if an external DTD or null * if the external DTD is specified using SYSTEM. * @param systemId The system identifier if an external DTD, null * otherwise. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void doctypeDecl( String rootElement, String publicId, String systemId, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.doctypeDecl(rootElement, publicId, systemId, augs); } } // doctypeDecl(String,String,String) /** * The start of an element. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { Augmentations modifiedAugs = handleStartElement(element, attributes, augs); // call handlers if (fDocumentHandler != null) { fDocumentHandler.startElement(element, attributes, modifiedAugs); } } // startElement(QName,XMLAttributes, Augmentations) /** * An empty element. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { Augmentations modifiedAugs = handleStartElement(element, attributes, augs); // in the case where there is a {value constraint}, and the element // doesn't have any text content, change emptyElement call to // start + characters + end fDefaultValue = null; // fElementDepth == -2 indicates that the schema validator was removed // from the pipeline. then we don't need to call handleEndElement. if (fElementDepth != -2) modifiedAugs = handleEndElement(element, modifiedAugs); // call handlers if (fDocumentHandler != null) { if (!fSchemaElementDefault || fDefaultValue == null) { fDocumentHandler.emptyElement(element, attributes, modifiedAugs); } else { fDocumentHandler.startElement(element, attributes, modifiedAugs); fDocumentHandler.characters(fDefaultValue, null); fDocumentHandler.endElement(element, modifiedAugs); } } } // emptyElement(QName,XMLAttributes, Augmentations) /** * Character content. * * @param text The content. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void characters(XMLString text, Augmentations augs) throws XNIException { text = handleCharacters(text); // call handlers if (fDocumentHandler != null) { if (fNormalizeData && fUnionType) { // for union types we can't normalize data // thus we only need to send augs information if any; // the normalized data for union will be send // after normalization is performed (at the endElement()) if (augs != null) fDocumentHandler.characters(fEmptyXMLStr, augs); } else { fDocumentHandler.characters(text, augs); } } } // characters(XMLString) /** * Ignorable whitespace. For this method to be called, the document * source must have some way of determining that the text containing * only whitespace characters should be considered ignorable. For * example, the validator can determine if a length of whitespace * characters in the document are ignorable based on the element * content model. * * @param text The ignorable whitespace. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException { handleIgnorableWhitespace(text); // call handlers if (fDocumentHandler != null) { fDocumentHandler.ignorableWhitespace(text, augs); } } // ignorableWhitespace(XMLString) /** * The end of an element. * * @param element The name of the element. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endElement(QName element, Augmentations augs) throws XNIException { // in the case where there is a {value constraint}, and the element // doesn't have any text content, add a characters call. fDefaultValue = null; Augmentations modifiedAugs = handleEndElement(element, augs); // call handlers if (fDocumentHandler != null) { if (!fSchemaElementDefault || fDefaultValue == null) { fDocumentHandler.endElement(element, modifiedAugs); } else { fDocumentHandler.characters(fDefaultValue, null); fDocumentHandler.endElement(element, modifiedAugs); } } } // endElement(QName, Augmentations) /** * The start of a CDATA section. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startCDATA(Augmentations augs) throws XNIException { // REVISIT: what should we do here if schema normalization is on?? fInCDATA = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.startCDATA(augs); } } // startCDATA() /** * The end of a CDATA section. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endCDATA(Augmentations augs) throws XNIException { // call handlers fInCDATA = false; if (fDocumentHandler != null) { fDocumentHandler.endCDATA(augs); } } // endCDATA() /** * The end of the document. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endDocument(Augmentations augs) throws XNIException { handleEndDocument(); // call handlers if (fDocumentHandler != null) { fDocumentHandler.endDocument(augs); } fLocator = null; } // endDocument(Augmentations) // // DOMRevalidationHandler methods // public boolean characterData(String data, Augmentations augs) { fSawText = fSawText || data.length() > 0; // REVISIT: this methods basically duplicates implementation of // handleCharacters(). We should be able to reuse some code // if whitespace == -1 skip normalization, because it is a complexType // or a union type. if (fNormalizeData && fWhiteSpace != -1 && fWhiteSpace != XSSimpleType.WS_PRESERVE) { // normalize data normalizeWhitespace(data, fWhiteSpace == XSSimpleType.WS_COLLAPSE); fBuffer.append(fNormalizedStr.ch, fNormalizedStr.offset, fNormalizedStr.length); } else { if (fAppendBuffer) fBuffer.append(data); } // When it's a complex type with element-only content, we need to // find out whether the content contains any non-whitespace character. boolean allWhiteSpace = true; if (fCurrentType != null && fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) { // data outside of element content for (int i = 0; i < data.length(); i++) { if (!XMLChar.isSpace(data.charAt(i))) { allWhiteSpace = false; fSawCharacters = true; break; } } } } return allWhiteSpace; } public void elementDefault(String data) { // no-op } // // XMLDocumentHandler and XMLDTDHandler methods // /** * This method notifies the start of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the general entity. * @param identifier The resource identifier. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param augs Additional information that may include infoset augmentations * * @exception XNIException Thrown by handler to signal an error. */ public void startGeneralEntity( String name, XMLResourceIdentifier identifier, String encoding, Augmentations augs) throws XNIException { // REVISIT: what should happen if normalize_data_ is on?? fEntityRef = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.startGeneralEntity(name, identifier, encoding, augs); } } // startEntity(String,String,String,String,String) /** * Notifies of the presence of a TextDecl line in an entity. If present, * this method will be called immediately following the startEntity call. * <p> * <strong>Note:</strong> This method will never be called for the * document entity; it is only called for external general entities * referenced in document content. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param version The XML version, or null if not specified. * @param encoding The IANA encoding name of the entity. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void textDecl(String version, String encoding, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.textDecl(version, encoding, augs); } } // textDecl(String,String) /** * A comment. * * @param text The text in the comment. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by application to signal an error. */ public void comment(XMLString text, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.comment(text, augs); } } // comment(XMLString) /** * A processing instruction. Processing instructions consist of a * target name and, optionally, text data. The data is only meaningful * to the application. * <p> * Typically, a processing instruction's data will contain a series * of pseudo-attributes. These pseudo-attributes follow the form of * element attributes but are <strong>not</strong> parsed or presented * to the application as anything other than text. The application is * responsible for parsing the data. * * @param target The target. * @param data The data or null if none specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void processingInstruction(String target, XMLString data, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.processingInstruction(target, data, augs); } } // processingInstruction(String,XMLString) /** * This method notifies the end of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the entity. * @param augs Additional information that may include infoset augmentations * * @exception XNIException * Thrown by handler to signal an error. */ public void endGeneralEntity(String name, Augmentations augs) throws XNIException { // call handlers fEntityRef = false; if (fDocumentHandler != null) { fDocumentHandler.endGeneralEntity(name, augs); } } // endEntity(String) // constants static final int INITIAL_STACK_SIZE = 8; static final int INC_STACK_SIZE = 8; // // Data // // Schema Normalization private static final boolean DEBUG_NORMALIZATION = false; // temporary empty string buffer. private final XMLString fEmptyXMLStr = new XMLString(null, 0, -1); // temporary character buffer, and empty string buffer. private static final int BUFFER_SIZE = 20; private final XMLString fNormalizedStr = new XMLString(); private boolean fFirstChunk = true; // got first chunk in characters() (SAX) private boolean fTrailing = false; // Previous chunk had a trailing space private short fWhiteSpace = -1; //whiteSpace: preserve/replace/collapse private boolean fUnionType = false; /** Schema grammar resolver. */ private final XSGrammarBucket fGrammarBucket = new XSGrammarBucket(); private final SubstitutionGroupHandler fSubGroupHandler = new SubstitutionGroupHandler(this); /** the DV usd to convert xsi:type to a QName */ // REVISIT: in new simple type design, make things in DVs static, // so that we can QNameDV.getCompiledForm() // using 1.0 xs:QName private final XSSimpleType fQNameDV = (XSSimpleType) SchemaGrammar.getS4SGrammar(Constants.SCHEMA_VERSION_1_0).getGlobalTypeDecl(SchemaSymbols.ATTVAL_QNAME); private final CMNodeFactory nodeFactory = new CMNodeFactory(); /** used to build content models */ // REVISIT: create decl pool, and pass it to each traversers private final CMBuilder fCMBuilder = new CMBuilder(nodeFactory); // Schema grammar loader private final XMLSchemaLoader fSchemaLoader = new XMLSchemaLoader( fXSIErrorReporter.fErrorReporter, fGrammarBucket, fSubGroupHandler, fCMBuilder); // state /** String representation of the validation root. */ // REVISIT: what do we store here? QName, XPATH, some ID? use rawname now. private String fValidationRoot; /** Skip validation: anything below this level should be skipped */ private int fSkipValidationDepth; /** anything above this level has validation_attempted != full */ private int fNFullValidationDepth; /** anything above this level has validation_attempted != none */ private int fNNoneValidationDepth; /** Element depth: -2: validator not in pipeline; >= -1 current depth. */ private int fElementDepth; /** Seen sub elements. */ private boolean fSubElement; /** Seen sub elements stack. */ private boolean[] fSubElementStack = new boolean[INITIAL_STACK_SIZE]; /** Current element declaration. */ private XSElementDecl fCurrentElemDecl; /** Element decl stack. */ private XSElementDecl[] fElemDeclStack = new XSElementDecl[INITIAL_STACK_SIZE]; /** nil value of the current element */ private boolean fNil; /** nil value stack */ private boolean[] fNilStack = new boolean[INITIAL_STACK_SIZE]; /** notation value of the current element */ private XSNotationDecl fNotation; /** notation stack */ private XSNotationDecl[] fNotationStack = new XSNotationDecl[INITIAL_STACK_SIZE]; /** Current type. */ private XSTypeDefinition fCurrentType; /** type stack. */ private XSTypeDefinition[] fTypeStack = new XSTypeDefinition[INITIAL_STACK_SIZE]; /** Current content model. */ private XSCMValidator fCurrentCM; /** Content model stack. */ private XSCMValidator[] fCMStack = new XSCMValidator[INITIAL_STACK_SIZE]; /** the current state of the current content model */ private int[] fCurrCMState; /** stack to hold content model states */ private int[][] fCMStateStack = new int[INITIAL_STACK_SIZE][]; /** whether the curret element is strictly assessed */ private boolean fStrictAssess = true; /** strict assess stack */ private boolean[] fStrictAssessStack = new boolean[INITIAL_STACK_SIZE]; /** Temporary string buffers. */ private final StringBuffer fBuffer = new StringBuffer(); /** Whether need to append characters to fBuffer */ private boolean fAppendBuffer = true; /** Did we see any character data? */ private boolean fSawText = false; /** stack to record if we saw character data */ private boolean[] fSawTextStack = new boolean[INITIAL_STACK_SIZE]; /** Did we see non-whitespace character data? */ private boolean fSawCharacters = false; /** Stack to record if we saw character data outside of element content*/ private boolean[] fStringContent = new boolean[INITIAL_STACK_SIZE]; /** temporary qname */ private final QName fTempQName = new QName(); /** value of the "root-type-definition" property. */ private javax.xml.namespace.QName fRootTypeQName = null; private XSTypeDefinition fRootTypeDefinition = null; /** value of the "root-element-declaration" property. */ private javax.xml.namespace.QName fRootElementDeclQName = null; private XSElementDecl fRootElementDeclaration = null; private int fIgnoreXSITypeDepth; private boolean fIDCChecking; private boolean fTypeAlternativesChecking; /** temporary validated info */ private ValidatedInfo fValidatedInfo = new ValidatedInfo(); // used to validate default/fixed values against xsi:type // only need to check facets, so we set extraChecking to false (in reset) private ValidationState fState4XsiType = new ValidationState(); // used to apply default/fixed values // only need to check id/idref/entity, so we set checkFacets to false private ValidationState fState4ApplyDefault = new ValidationState(); // identity constraint information /** * Stack of active XPath matchers for identity constraints. All * active XPath matchers are notified of startElement * and endElement callbacks in order to perform their matches. * <p> * For each element with identity constraints, the selector of * each identity constraint is activated. When the selector matches * its XPath, then all the fields of the identity constraint are * activated. * <p> * <strong>Note:</strong> Once the activation scope is left, the * XPath matchers are automatically removed from the stack of * active matchers and no longer receive callbacks. */ protected XPathMatcherStack fMatcherStack = new XPathMatcherStack(); /** Cache of value stores for identity constraint fields. */ protected ValueStoreCache fValueStoreCache = new ValueStoreCache(); // assertion validator subcomponent private XSDAssertionValidator fAssertionValidator = null; // variable to track validity of simple content for union types. // used for assertions processing. private boolean fisAtomicValueValid = true; // 'type alternative' validator subcomponent private XSDTypeAlternativeValidator fTypeAlternativeValidator = null; // // Constructors // /** Default constructor. */ public XMLSchemaValidator() { fState4XsiType.setExtraChecking(false); fState4ApplyDefault.setFacetChecking(false); fSchemaVersion = fSchemaLoader.getSchemaVersion(); fXSConstraints = fSchemaLoader.getXSConstraints(); fAssertionValidator = new XSDAssertionValidator(this); fTypeAlternativeValidator = new XSDTypeAlternativeValidator(); } // <init>() /* * Resets the component. The component can query the component manager * about any features and properties that affect the operation of the * component. * * @param componentManager The component manager. * * @throws SAXException Thrown by component on finitialization error. * For example, if a feature or property is * required for the operation of the component, the * component manager may throw a * SAXNotRecognizedException or a * SAXNotSupportedException. */ public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { fIdConstraint = false; //reset XSDDescription fLocationPairs.clear(); fExpandedLocationPairs.clear(); // cleanup id table fValidationState.resetIDTables(); // reset schema loader fSchemaLoader.reset(componentManager); // initialize state fCurrentElemDecl = null; fCurrentCM = null; fCurrCMState = null; fSkipValidationDepth = -1; fNFullValidationDepth = -1; fNNoneValidationDepth = -1; fElementDepth = -1; fSubElement = false; fSchemaDynamicValidation = false; // datatype normalization fEntityRef = false; fInCDATA = false; fMatcherStack.clear(); // get error reporter fXSIErrorReporter.reset((XMLErrorReporter) componentManager.getProperty(ERROR_REPORTER)); boolean parser_settings; try { parser_settings = componentManager.getFeature(PARSER_SETTINGS); } catch (XMLConfigurationException e){ parser_settings = true; } if (!parser_settings) { // parser settings have not been changed fValidationManager.addValidationState(fValidationState); // the node limit on the SecurityManager may have changed so need to refresh. nodeFactory.reset(); // Re-parse external schema location properties. XMLSchemaLoader.processExternalHints( fExternalSchemas, fExternalNoNamespaceSchema, fLocationPairs, fXSIErrorReporter.fErrorReporter); return; } // pass the component manager to the factory.. nodeFactory.reset(componentManager); // get symbol table. if it's a new one, add symbols to it. SymbolTable symbolTable = (SymbolTable) componentManager.getProperty(SYMBOL_TABLE); if (symbolTable != fSymbolTable) { fSymbolTable = symbolTable; } try { fNamespaceGrowth = componentManager.getFeature(NAMESPACE_GROWTH); } catch (XMLConfigurationException e) { fNamespaceGrowth = false; } try { fDynamicValidation = componentManager.getFeature(DYNAMIC_VALIDATION); } catch (XMLConfigurationException e) { fDynamicValidation = false; } if (fDynamicValidation) { fDoValidation = true; } else { try { fDoValidation = componentManager.getFeature(VALIDATION); } catch (XMLConfigurationException e) { fDoValidation = false; } } if (fDoValidation) { try { fDoValidation = componentManager.getFeature(XMLSchemaValidator.SCHEMA_VALIDATION); } catch (XMLConfigurationException e) { } } try { fFullChecking = componentManager.getFeature(SCHEMA_FULL_CHECKING); } catch (XMLConfigurationException e) { fFullChecking = false; } try { fNormalizeData = componentManager.getFeature(NORMALIZE_DATA); } catch (XMLConfigurationException e) { fNormalizeData = false; } try { fSchemaElementDefault = componentManager.getFeature(SCHEMA_ELEMENT_DEFAULT); } catch (XMLConfigurationException e) { fSchemaElementDefault = false; } try { fAugPSVI = componentManager.getFeature(SCHEMA_AUGMENT_PSVI); } catch (XMLConfigurationException e) { fAugPSVI = true; } try { fSchemaType = (String) componentManager.getProperty( Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE); } catch (XMLConfigurationException e) { fSchemaType = null; } try { fUseGrammarPoolOnly = componentManager.getFeature(USE_GRAMMAR_POOL_ONLY); } catch (XMLConfigurationException e) { fUseGrammarPoolOnly = false; } fEntityResolver = (XMLEntityResolver) componentManager.getProperty(ENTITY_MANAGER); final TypeValidatorHelper typeValidatorHelper = TypeValidatorHelper.getInstance(fSchemaVersion); fValidationManager = (ValidationManager) componentManager.getProperty(VALIDATION_MANAGER); fValidationManager.addValidationState(fValidationState); fValidationState.setSymbolTable(fSymbolTable); fValidationState.setTypeValidatorHelper(typeValidatorHelper); try { final Object rootType = componentManager.getProperty(ROOT_TYPE_DEF); if (rootType == null) { fRootTypeQName = null; fRootTypeDefinition = null; } else if (rootType instanceof javax.xml.namespace.QName) { fRootTypeQName = (javax.xml.namespace.QName) rootType; fRootTypeDefinition = null; } else { fRootTypeDefinition = (XSTypeDefinition) rootType; fRootTypeQName = null; } } catch (XMLConfigurationException e) { fRootTypeQName = null; fRootTypeDefinition = null; } try { final Object rootDecl = componentManager.getProperty(ROOT_ELEMENT_DECL); if (rootDecl == null) { fRootElementDeclQName = null; fRootElementDeclaration = null; } else if (rootDecl instanceof javax.xml.namespace.QName) { fRootElementDeclQName = (javax.xml.namespace.QName) rootDecl; fRootElementDeclaration = null; } else { fRootElementDeclaration = (XSElementDecl) rootDecl; fRootElementDeclQName = null; } } catch (XMLConfigurationException e) { fRootElementDeclQName = null; fRootElementDeclaration = null; } boolean ignoreXSIType; try { ignoreXSIType = componentManager.getFeature(IGNORE_XSI_TYPE); } catch (XMLConfigurationException e) { ignoreXSIType = false; } // An initial value of -1 means that the root element considers itself // below the depth where xsi:type stopped being ignored (which means that // xsi:type attributes will not be ignored for the entire document) fIgnoreXSITypeDepth = ignoreXSIType ? 0 : -1; try { fIDCChecking = componentManager.getFeature(IDENTITY_CONSTRAINT_CHECKING); } catch (XMLConfigurationException e) { fIDCChecking = true; } try { fValidationState.setIdIdrefChecking(componentManager.getFeature(ID_IDREF_CHECKING)); } catch (XMLConfigurationException e) { fValidationState.setIdIdrefChecking(true); } try { fValidationState.setUnparsedEntityChecking(componentManager.getFeature(UNPARSED_ENTITY_CHECKING)); } catch (XMLConfigurationException e) { fValidationState.setUnparsedEntityChecking(true); } try { fTypeAlternativesChecking = componentManager.getFeature(TYPE_ALTERNATIVES_CHECKING); } catch (XMLConfigurationException e) { fTypeAlternativesChecking = true; } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNamespaceSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNamespaceSchema = null; } // store the external schema locations. they are set when reset is called, // so any other schemaLocation declaration for the same namespace will be // effectively ignored. becuase we choose to take first location hint // available for a particular namespace. XMLSchemaLoader.processExternalHints( fExternalSchemas, fExternalNoNamespaceSchema, fLocationPairs, fXSIErrorReporter.fErrorReporter); try { fJaxpSchemaSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE); } catch (XMLConfigurationException e) { fJaxpSchemaSource = null; } // clear grammars, and put the one for schema namespace there try { fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL); } catch (XMLConfigurationException e) { fGrammarPool = null; } fState4XsiType.setSymbolTable(symbolTable); fState4ApplyDefault.setSymbolTable(symbolTable); fState4XsiType.setTypeValidatorHelper(typeValidatorHelper); fState4ApplyDefault.setTypeValidatorHelper(typeValidatorHelper); } // reset(XMLComponentManager) // // FieldActivator methods // /** * Start the value scope for the specified identity constraint. This * method is called when the selector matches in order to initialize * the value store. * * @param identityConstraint The identity constraint. */ public void startValueScopeFor(IdentityConstraint identityConstraint, int initialDepth) { ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint, initialDepth); valueStore.startValueScope(); } // startValueScopeFor(IdentityConstraint identityConstraint) /** * Request to activate the specified field. This method returns the * matcher for the field. * * @param field The field to activate. */ public XPathMatcher activateField(Field field, int initialDepth) { ValueStore valueStore = fValueStoreCache.getValueStoreFor(field.getIdentityConstraint(), initialDepth); XPathMatcher matcher = field.createMatcher(valueStore); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(); return matcher; } // activateField(Field):XPathMatcher /** * Ends the value scope for the specified identity constraint. * * @param identityConstraint The identity constraint. */ public void endValueScopeFor(IdentityConstraint identityConstraint, int initialDepth) { ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint, initialDepth); valueStore.endValueScope(); } // endValueScopeFor(IdentityConstraint) // a utility method for Identity constraints private void activateSelectorFor(IdentityConstraint ic) { Selector selector = ic.getSelector(); FieldActivator activator = this; if (selector == null) return; XPathMatcher matcher = selector.createMatcher(activator, fElementDepth); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(); } // Implements XSElementDeclHelper interface public XSElementDecl getGlobalElementDecl(QName element) { final SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, null); if (sGrammar != null) { return sGrammar.getGlobalElementDecl(element.localpart); } return null; } // // Protected methods // /** ensure element stack capacity */ void ensureStackCapacity() { if (fElementDepth == fElemDeclStack.length) { int newSize = fElementDepth + INC_STACK_SIZE; boolean[] newArrayB = new boolean[newSize]; System.arraycopy(fSubElementStack, 0, newArrayB, 0, fElementDepth); fSubElementStack = newArrayB; XSElementDecl[] newArrayE = new XSElementDecl[newSize]; System.arraycopy(fElemDeclStack, 0, newArrayE, 0, fElementDepth); fElemDeclStack = newArrayE; newArrayB = new boolean[newSize]; System.arraycopy(fNilStack, 0, newArrayB, 0, fElementDepth); fNilStack = newArrayB; XSNotationDecl[] newArrayN = new XSNotationDecl[newSize]; System.arraycopy(fNotationStack, 0, newArrayN, 0, fElementDepth); fNotationStack = newArrayN; XSTypeDefinition[] newArrayT = new XSTypeDefinition[newSize]; System.arraycopy(fTypeStack, 0, newArrayT, 0, fElementDepth); fTypeStack = newArrayT; XSCMValidator[] newArrayC = new XSCMValidator[newSize]; System.arraycopy(fCMStack, 0, newArrayC, 0, fElementDepth); fCMStack = newArrayC; newArrayB = new boolean[newSize]; System.arraycopy(fSawTextStack, 0, newArrayB, 0, fElementDepth); fSawTextStack = newArrayB; newArrayB = new boolean[newSize]; System.arraycopy(fStringContent, 0, newArrayB, 0, fElementDepth); fStringContent = newArrayB; newArrayB = new boolean[newSize]; System.arraycopy(fStrictAssessStack, 0, newArrayB, 0, fElementDepth); fStrictAssessStack = newArrayB; int[][] newArrayIA = new int[newSize][]; System.arraycopy(fCMStateStack, 0, newArrayIA, 0, fElementDepth); fCMStateStack = newArrayIA; } } // ensureStackCapacity // handle start document void handleStartDocument(XMLLocator locator, String encoding) { if (fIDCChecking) { fValueStoreCache.startDocument(); } if (fAugPSVI) { fCurrentPSVI.fGrammars = null; fCurrentPSVI.fSchemaInformation = null; } } // handleStartDocument(XMLLocator,String) void handleEndDocument() { if (fIDCChecking) { fValueStoreCache.endDocument(); } } // handleEndDocument() // handle character contents // returns the normalized string if possible, otherwise the original string XMLString handleCharacters(XMLString text) { if (fSkipValidationDepth >= 0) return text; fSawText = fSawText || text.length > 0; // Note: data in EntityRef and CDATA is normalized as well // if whitespace == -1 skip normalization, because it is a complexType // or a union type. if (fNormalizeData && fWhiteSpace != -1 && fWhiteSpace != XSSimpleType.WS_PRESERVE) { // normalize data normalizeWhitespace(text, fWhiteSpace == XSSimpleType.WS_COLLAPSE); text = fNormalizedStr; } if (fAppendBuffer) fBuffer.append(text.ch, text.offset, text.length); // When it's a complex type with element-only content, we need to // find out whether the content contains any non-whitespace character. if (fCurrentType != null && fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) { // data outside of element content for (int i = text.offset; i < text.offset + text.length; i++) { if (!XMLChar.isSpace(text.ch[i])) { fSawCharacters = true; break; } } } } // delegate to assertions validator subcomponent if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fAssertionValidator.characterDataHandler(text); } return text; } // handleCharacters(XMLString) /** * Normalize whitespace in an XMLString according to the rules defined * in XML Schema specifications. * @param value The string to normalize. * @param collapse replace or collapse */ private void normalizeWhitespace(XMLString value, boolean collapse) { boolean skipSpace = collapse; boolean sawNonWS = false; boolean leading = false; boolean trailing = false; char c; int size = value.offset + value.length; // ensure the ch array is big enough if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < value.length + 1) { fNormalizedStr.ch = new char[value.length + 1]; } // don't include the leading ' ' for now. might include it later. fNormalizedStr.offset = 1; fNormalizedStr.length = 1; for (int i = value.offset; i < size; i++) { c = value.ch[i]; if (XMLChar.isSpace(c)) { if (!skipSpace) { // take the first whitespace as a space and skip the others fNormalizedStr.ch[fNormalizedStr.length++] = ' '; skipSpace = collapse; } if (!sawNonWS) { // this is a leading whitespace, record it leading = true; } } else { fNormalizedStr.ch[fNormalizedStr.length++] = c; skipSpace = false; sawNonWS = true; } } if (skipSpace) { if (fNormalizedStr.length > 1) { // if we finished on a space trim it but also record it fNormalizedStr.length--; trailing = true; } else if (leading && !fFirstChunk) { // if all we had was whitespace we skipped record it as // trailing whitespace as well trailing = true; } } if (fNormalizedStr.length > 1) { if (!fFirstChunk && (fWhiteSpace == XSSimpleType.WS_COLLAPSE)) { if (fTrailing) { // previous chunk ended on whitespace // insert whitespace fNormalizedStr.offset = 0; fNormalizedStr.ch[0] = ' '; } else if (leading) { // previous chunk ended on character, // this chunk starts with whitespace fNormalizedStr.offset = 0; fNormalizedStr.ch[0] = ' '; } } } // The length includes the leading ' '. Now removing it. fNormalizedStr.length -= fNormalizedStr.offset; fTrailing = trailing; if (trailing || sawNonWS) fFirstChunk = false; } private void normalizeWhitespace(String value, boolean collapse) { boolean skipSpace = collapse; char c; int size = value.length(); // ensure the ch array is big enough if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < size) { fNormalizedStr.ch = new char[size]; } fNormalizedStr.offset = 0; fNormalizedStr.length = 0; for (int i = 0; i < size; i++) { c = value.charAt(i); if (XMLChar.isSpace(c)) { if (!skipSpace) { // take the first whitespace as a space and skip the others fNormalizedStr.ch[fNormalizedStr.length++] = ' '; skipSpace = collapse; } } else { fNormalizedStr.ch[fNormalizedStr.length++] = c; skipSpace = false; } } if (skipSpace) { if (fNormalizedStr.length != 0) // if we finished on a space trim it but also record it fNormalizedStr.length--; } } // handle ignorable whitespace void handleIgnorableWhitespace(XMLString text) { if (fSkipValidationDepth >= 0) return; // REVISIT: the same process needs to be performed as handleCharacters. // only it's simpler here: we know all characters are whitespaces. } // handleIgnorableWhitespace(XMLString) /** Handle element. */ Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) { if (DEBUG) { System.out.println("==>handleStartElement: " + element); } // root element if (fElementDepth == -1 && fValidationManager.isGrammarFound()) { if (fSchemaType == null) { // schemaType is not specified // if a DTD grammar is found, we do the same thing as Dynamic: // if a schema grammar is found, validation is performed; // otherwise, skip the whole document. fSchemaDynamicValidation = true; } else { // [1] Either schemaType is DTD, and in this case validate/schema is turned off // [2] Validating against XML Schemas only // [a] dynamic validation is false: report error if SchemaGrammar is not found // [b] dynamic validation is true: if grammar is not found ignore. } } // get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, // parse them to get the grammars. But only do this if the grammar can grow. if (!fUseGrammarPoolOnly) { String sLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); //store the location hints.. we need to do it so that we can defer the loading of grammar until //there is a reference to a component from that namespace. To provide location hints to the //application for a namespace storeLocations(sLocation, nsLocation); } // if we are in the content of "skip", then just skip this element // REVISIT: is this the correct behaviour for ID constraints? -NG if (fSkipValidationDepth >= 0) { fElementDepth++; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // if we are not skipping this element, and there is a content model, // we try to find the corresponding decl object for this element. // the reason we move this part of code here is to make sure the // error reported here (if any) is stored within the parent element's // context, instead of that of the current element. Object decl = null; if (fCurrentCM != null) { decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler, this); // it could be an element decl or a wildcard decl if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; //REVISIT: is it the only case we will have particle = null? Vector next; if (ctype.fParticle != null && (next = fCurrentCM.whatCanGoHere(fCurrCMState)).size() > 0) { String expected = expectedStr(next); - final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); + final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); + String elemExpandedQname = (element.uri != null) ? "{"+'"'+element.uri+'"'+":"+element.localpart+"}" : element.localpart; if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of minOccurs if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.h", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.g", new Object[] { element.rawname, - fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); + fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } // Check if this is a violation of maxOccurs else if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.e", new Object[] { element.rawname, - expected, Integer.toString(maxOccurs) }); + expected, Integer.toString(maxOccurs) }); } else { - reportSchemaError("cvc-complex-type.2.4.a", new Object[] { element.rawname, expected }); + reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { - reportSchemaError("cvc-complex-type.2.4.a", new Object[] { element.rawname, expected }); + reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of maxOccurs if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.f", new Object[] { element.rawname, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } } } // if it's not the root element, we push the current states in the stacks if (fElementDepth != -1) { ensureStackCapacity(); fSubElementStack[fElementDepth] = true; fSubElement = false; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fNotationStack[fElementDepth] = fNotation; fTypeStack[fElementDepth] = fCurrentType; fStrictAssessStack[fElementDepth] = fStrictAssess; fCMStack[fElementDepth] = fCurrentCM; fCMStateStack[fElementDepth] = fCurrCMState; fSawTextStack[fElementDepth] = fSawText; fStringContent[fElementDepth] = fSawCharacters; } // increase the element depth after we've saved // all states for the parent element fElementDepth++; fCurrentElemDecl = null; XSWildcardDecl wildcard = null; fCurrentType = null; fStrictAssess = true; fNil = false; fNotation = null; // and the buffer to hold the value of the element fBuffer.setLength(0); fSawText = false; fSawCharacters = false; // check what kind of declaration the "decl" from // oneTransition() maps to if (decl != null) { if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl) decl; } else if (decl instanceof XSOpenContentDecl) { wildcard = (XSWildcardDecl) ((XSOpenContentDecl)decl).getWildcard(); } else { wildcard = (XSWildcardDecl) decl; } } // if the wildcard is skip, then return if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) { fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } if (fElementDepth == 0) { // 1.1.1.1 An element declaration was stipulated by the processor if (fRootElementDeclaration != null) { fCurrentElemDecl = fRootElementDeclaration; checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } else if (fRootElementDeclQName != null) { processRootElementDeclQName(fRootElementDeclQName, element); } // 1.2.1.1 A type definition was stipulated by the processor else if (fRootTypeDefinition != null) { fCurrentType = fRootTypeDefinition; } else if (fRootTypeQName != null) { processRootTypeQName(fRootTypeQName); } } // if there was no processor stipulated type if (fCurrentType == null) { // try again to get the element decl: // case 1: find declaration for root element // case 2: find declaration for element from another namespace if (fCurrentElemDecl == null) { // try to find schema grammar by different means.. SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, attributes); if (sGrammar != null) { fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } } if (fCurrentElemDecl != null) { // then get the type fCurrentType = fCurrentElemDecl.fType; } } //process type alternatives if (fTypeAlternativesChecking && fCurrentElemDecl != null) { XSTypeDefinition currentType = fTypeAlternativeValidator.getCurrentType(fCurrentElemDecl, element, attributes); if (currentType != null) { fCurrentType = currentType; } } // check if we should be ignoring xsi:type on this element if (fElementDepth == fIgnoreXSITypeDepth && fCurrentElemDecl == null) { fIgnoreXSITypeDepth++; } // process xsi:type attribute information String xsiType = null; if (fElementDepth >= fIgnoreXSITypeDepth) { xsiType = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_TYPE); } // if no decl/type found for the current element if (fCurrentType == null && xsiType == null) { // if this is the validation root, report an error, because // we can't find eith decl or type for this element // REVISIT: should we report error, or warning? if (fElementDepth == 0) { // for dynamic validation, skip the whole content, // because no grammar was found. if (fDynamicValidation || fSchemaDynamicValidation) { // no schema grammar was found, but it's either dynamic // validation, or another kind of grammar was found (DTD, // for example). The intended behavior here is to skip // the whole document. To improve performance, we try to // remove the validator from the pipeline, since it's not // supposed to do anything. if (fDocumentSource != null) { fDocumentSource.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) fDocumentHandler.setDocumentSource(fDocumentSource); // indicate that the validator was removed. fElementDepth = -2; return augs; } fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // We don't call reportSchemaError here, because the spec // doesn't think it's invalid not to be able to find a // declaration or type definition for an element. Xerces is // reporting it as an error for historical reasons, but in // PSVI, we shouldn't mark this element as invalid because // of this. - SG fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "cvc-elt.1.a", new Object[] { element.rawname }, XMLErrorReporter.SEVERITY_ERROR); } // if wildcard = strict, report error. // needs to be called before fXSIErrorReporter.pushContext() // so that the error belongs to the parent element. else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { // report error, because wilcard = strict reportSchemaError("cvc-complex-type.2.4.c", new Object[] { element.rawname }); } // no element decl or type found for this element. // Allowed by the spec, we can choose to either laxly assess this // element, or to skip it. Now we choose lax assessment. fCurrentType = SchemaGrammar.getXSAnyType(fSchemaVersion); fStrictAssess = false; fNFullValidationDepth = fElementDepth; // any type has mixed content, so we don't need to append buffer fAppendBuffer = false; // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); } else { // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); // get xsi:type if (xsiType != null) { XSTypeDefinition oldType = fCurrentType; fCurrentType = getAndCheckXsiType(element, xsiType, attributes); // If it fails, use the old type. Use anyType if ther is no old type. if (fCurrentType == null) { if (oldType == null) fCurrentType = SchemaGrammar.getXSAnyType(fSchemaVersion); else fCurrentType = oldType; } } fNNoneValidationDepth = fElementDepth; // if the element has a fixed value constraint, we need to append if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { fAppendBuffer = true; } // if the type is simple, we need to append else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { fAppendBuffer = true; } else { // if the type is simple content complex type, we need to append XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; fAppendBuffer = (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE); } } // Element Locally Valid (Element) // 2 Its {abstract} must be false. if (fCurrentElemDecl != null && fCurrentElemDecl.getAbstract()) reportSchemaError("cvc-elt.2", new Object[] { element.rawname }); // make the current element validation root if (fElementDepth == 0) { fValidationRoot = element.rawname; } // update normalization flags if (fNormalizeData) { // reset values fFirstChunk = true; fTrailing = false; fUnionType = false; fWhiteSpace = -1; } // Element Locally Valid (Type) // 2 Its {abstract} must be false. if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.getAbstract()) { reportSchemaError("cvc-type.2", new Object[] { element.rawname }); } if (fNormalizeData) { // find out if the content type is simple and if variety is union // to be able to do character normalization if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = ctype.fXSSimpleType.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } } } // normalization: simple type else if (fNormalizeData) { // if !union type XSSimpleType dv = (XSSimpleType) fCurrentType; if (dv.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = dv.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } // then try to get the content model fCurrentCM = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { fCurrentCM = ((XSComplexTypeDecl) fCurrentType).getContentModel(fCMBuilder); } // and get the initial content model state fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); // get information about xsi:nil String xsiNil = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NIL); // only deal with xsi:nil when there is an element declaration if (xsiNil != null && fCurrentElemDecl != null) fNil = getXsiNil(element, xsiNil); // now validate everything related with the attributes // first, get the attribute group XSAttributeGroupDecl attrGrp = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; attrGrp = ctype.getAttrGrp(); } if (fIDCChecking) { // activate identity constraints fValueStoreCache.startElement(); fMatcherStack.pushContext(); //if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0 && !fIgnoreIDC) { if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0) { fIdConstraint = true; // initialize when identity constrains are defined for the elem fValueStoreCache.initValueStoresFor(fCurrentElemDecl, this); } } processAttributes(element, attributes, attrGrp); // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // delegate to 'type alternative' validator subcomponent if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fTypeAlternativeValidator.handleStartElement(fCurrentElemDecl, attributes); } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement( element, attributes); } if (fAugPSVI) { augs = getEmptyAugs(augs); // PSVI: add validation context fCurrentPSVI.fValidationContext = fValidationRoot; // PSVI: add element declaration fCurrentPSVI.fDeclaration = fCurrentElemDecl; // PSVI: add element type fCurrentPSVI.fTypeDecl = fCurrentType; // PSVI: add notation attribute fCurrentPSVI.fNotation = fNotation; // PSVI: add nil fCurrentPSVI.fNil = fNil; } // delegate to assertions validator subcomponent if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fAssertionValidator.handleStartElement(element, attributes); } return augs; } // handleStartElement(QName,XMLAttributes,boolean) /** * Handle end element. If there is not text content, and there is a * {value constraint} on the corresponding element decl, then * set the fDefaultValue XMLString representing the default value. */ Augmentations handleEndElement(QName element, Augmentations augs) { if (DEBUG) { System.out.println("==>handleEndElement:" + element); } // delegate to 'type alternative' validator subcomponent if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fTypeAlternativeValidator.handleEndElement(); } // if we are skipping, return if (fSkipValidationDepth >= 0) { // but if this is the top element that we are skipping, // restore the states. if (fSkipValidationDepth == fElementDepth && fSkipValidationDepth > 0) { // set the partial validation depth to the depth of parent fNFullValidationDepth = fSkipValidationDepth - 1; fSkipValidationDepth = -1; fElementDepth--; fSubElement = fSubElementStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fNotation = fNotationStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fStrictAssess = fStrictAssessStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawText = fSawTextStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; } else { fElementDepth--; } // PSVI: validation attempted: // use default values in psvi item for // validation attempted, validity, and error codes // check extra schema constraints on root element if (fElementDepth == -1 && fFullChecking && !fUseGrammarPoolOnly) { fXSConstraints.fullSchemaChecking( fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // now validate the content of the element processElementContent(element); if (fIDCChecking) { // Element Locally Valid (Element) // 6 The element information item must be valid with respect to each of the {identity-constraint definitions} as per Identity-constraint Satisfied (3.11.4). // call matchers and de-activate context int oldCount = fMatcherStack.getMatcherCount(); for (int i = oldCount - 1; i >= 0; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (fCurrentElemDecl == null) { matcher.endElement(element, fCurrentType, false, fValidatedInfo.actualValue, fValidatedInfo.actualValueType, fValidatedInfo.itemValueTypes); } else { matcher.endElement( element, fCurrentType, fCurrentElemDecl.getNillable(), fDefaultValue == null ? fValidatedInfo.actualValue : fCurrentElemDecl.fDefault.actualValue, fDefaultValue == null ? fValidatedInfo.actualValueType : fCurrentElemDecl.fDefault.actualValueType, fDefaultValue == null ? fValidatedInfo.itemValueTypes : fCurrentElemDecl.fDefault.itemValueTypes); } } if (fMatcherStack.size() > 0) { fMatcherStack.popContext(); } int newCount = fMatcherStack.getMatcherCount(); // handle everything *but* keyref's. for (int i = oldCount - 1; i >= newCount; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (matcher instanceof Selector.Matcher) { Selector.Matcher selMatcher = (Selector.Matcher) matcher; IdentityConstraint id; if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() != IdentityConstraint.IC_KEYREF) { fValueStoreCache.transplant(id, selMatcher.getInitialDepth()); } } } // now handle keyref's/... for (int i = oldCount - 1; i >= newCount; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (matcher instanceof Selector.Matcher) { Selector.Matcher selMatcher = (Selector.Matcher) matcher; IdentityConstraint id; if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() == IdentityConstraint.IC_KEYREF) { ValueStoreBase values = fValueStoreCache.getValueStoreFor(id, selMatcher.getInitialDepth()); if (values != null) // nothing to do if nothing matched! values.endDocumentFragment(); } } } fValueStoreCache.endElement(); } // delegate to assertions validator subcomponent if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fAssertionValidator.handleEndElement(element, fCurrentElemDecl, fCurrentType, fNotation, fGrammarBucket, fisAtomicValueValid); fisAtomicValueValid = true; } // Check if we should modify the xsi:type ignore depth // This check is independent of whether this is the validation root, // and should be done before the element depth is decremented. if (fElementDepth < fIgnoreXSITypeDepth) { fIgnoreXSITypeDepth--; } SchemaGrammar[] grammars = null; // have we reached the end tag of the validation root? if (fElementDepth == 0) { // 7 If the element information item is the validation root, it must be valid per Validation Root Valid (ID/IDREF) (3.3.4). String invIdRef = fValidationState.checkIDRefID(); fValidationState.resetIDTables(); if (invIdRef != null) { reportSchemaError("cvc-id.1", new Object[] { invIdRef }); } // check extra schema constraints if (fFullChecking && !fUseGrammarPoolOnly) { fXSConstraints.fullSchemaChecking( fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } grammars = fGrammarBucket.getGrammars(); // return the final set of grammars validator ended up with if (fGrammarPool != null) { // Set grammars as immutable for (int k=0; k < grammars.length; k++) { grammars[k].setImmutable(true); } fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA, grammars); } augs = endElementPSVI(true, grammars, augs); } else { augs = endElementPSVI(false, grammars, augs); // decrease element depth and restore states fElementDepth--; // get the states for the parent element. fSubElement = fSubElementStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fNotation = fNotationStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fStrictAssess = fStrictAssessStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawText = fSawTextStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; // We should have a stack for whitespace value, and pop it up here. // But when fWhiteSpace != -1, and we see a sub-element, it must be // an error (at least for Schema 1.0). So for valid documents, the // only value we are going to push/pop in the stack is -1. // Here we just mimic the effect of popping -1. -SG fWhiteSpace = -1; // Same for append buffer. Simple types and elements with fixed // value constraint don't allow sub-elements. -SG fAppendBuffer = false; // same here. fUnionType = false; } return augs; } // handleEndElement(QName,boolean)*/ final Augmentations endElementPSVI( boolean root, SchemaGrammar[] grammars, Augmentations augs) { if (fAugPSVI) { augs = getEmptyAugs(augs); // the 5 properties sent on startElement calls fCurrentPSVI.fDeclaration = this.fCurrentElemDecl; fCurrentPSVI.fTypeDecl = this.fCurrentType; fCurrentPSVI.fNotation = this.fNotation; fCurrentPSVI.fValidationContext = this.fValidationRoot; fCurrentPSVI.fNil = this.fNil; // PSVI: validation attempted // nothing below or at the same level has none or partial // (which means this level is strictly assessed, and all chidren // are full), so this one has full if (fElementDepth > fNFullValidationDepth) { fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_FULL; } // nothing below or at the same level has full or partial // (which means this level is not strictly assessed, and all chidren // are none), so this one has none else if (fElementDepth > fNNoneValidationDepth) { fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_NONE; } // otherwise partial, and anything above this level will be partial else { fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_PARTIAL; } // this guarantees that depth settings do not cross-over between sibling nodes if (fNFullValidationDepth == fElementDepth) { fNFullValidationDepth = fElementDepth - 1; } if (fNNoneValidationDepth == fElementDepth) { fNNoneValidationDepth = fElementDepth - 1; } if (fDefaultValue != null) fCurrentPSVI.fSpecified = true; fCurrentPSVI.fValue.copyFrom(fValidatedInfo); if (fStrictAssess) { // get all errors for the current element, its attribute, // and subelements (if they were strictly assessed). // any error would make this element invalid. // and we merge these errors to the parent element. String[] errors = fXSIErrorReporter.mergeContext(); // PSVI: error codes fCurrentPSVI.fErrors = errors; // PSVI: validity fCurrentPSVI.fValidity = (errors == null) ? ElementPSVI.VALIDITY_VALID : ElementPSVI.VALIDITY_INVALID; } else { // PSVI: validity fCurrentPSVI.fValidity = ElementPSVI.VALIDITY_NOTKNOWN; // Discard the current context: ignore any error happened within // the sub-elements/attributes of this element, because those // errors won't affect the validity of the parent elements. fXSIErrorReporter.popContext(); } if (root) { // store [schema information] in the PSVI fCurrentPSVI.fGrammars = grammars; fCurrentPSVI.fSchemaInformation = null; } } return augs; } Augmentations getEmptyAugs(Augmentations augs) { if (augs == null) { augs = fAugmentations; augs.removeAllItems(); } augs.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); fCurrentPSVI.reset(); return augs; } void storeLocations(String sLocation, String nsLocation) { if (sLocation != null) { if (!XMLSchemaLoader.tokenizeSchemaLocationStr(sLocation, fLocationPairs, fLocator == null ? null : fLocator.getExpandedSystemId())) { // error! fXSIErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "SchemaLocation", new Object[] { sLocation }, XMLErrorReporter.SEVERITY_WARNING); } } if (nsLocation != null) { XMLSchemaLoader.LocationArray la = ((XMLSchemaLoader.LocationArray) fLocationPairs.get(XMLSymbols.EMPTY_STRING)); if (la == null) { la = new XMLSchemaLoader.LocationArray(); fLocationPairs.put(XMLSymbols.EMPTY_STRING, la); } if (fLocator != null) { try { nsLocation = XMLEntityManager.expandSystemId(nsLocation, fLocator.getExpandedSystemId(), false); } catch (MalformedURIException e) { } } la.addLocation(nsLocation); } } //storeLocations //this is the function where logic of retrieving grammar is written , parser first tries to get the grammar from //the local pool, if not in local pool, it gives chance to application to be able to retrieve the grammar, then it //tries to parse the grammar using location hints from the give namespace. SchemaGrammar findSchemaGrammar( short contextType, String namespace, QName enclosingElement, QName triggeringComponent, XMLAttributes attributes) { SchemaGrammar grammar = null; //get the grammar from local pool... grammar = fGrammarBucket.getGrammar(namespace); if (grammar == null) { fXSDDescription.setNamespace(namespace); if (fGrammarPool != null) { grammar = (SchemaGrammar) fGrammarPool.retrieveGrammar(fXSDDescription); if (grammar != null) { // put this grammar into the bucket, along with grammars // imported by it (directly or indirectly) if (!fGrammarBucket.putGrammar(grammar, true, fNamespaceGrowth)) { // REVISIT: a conflict between new grammar(s) and grammars // in the bucket. What to do? A warning? An exception? fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "GrammarConflict", null, XMLErrorReporter.SEVERITY_WARNING); grammar = null; } } } } if (!fUseGrammarPoolOnly && (grammar == null || (fNamespaceGrowth && !hasSchemaComponent(grammar, contextType, triggeringComponent)))) { fXSDDescription.reset(); fXSDDescription.fContextType = contextType; fXSDDescription.setNamespace(namespace); fXSDDescription.fEnclosedElementName = enclosingElement; fXSDDescription.fTriggeringComponent = triggeringComponent; fXSDDescription.fAttributes = attributes; if (fLocator != null) { fXSDDescription.setBaseSystemId(fLocator.getExpandedSystemId()); } Hashtable locationPairs = fLocationPairs; Object locationArray = locationPairs.get(namespace == null ? XMLSymbols.EMPTY_STRING : namespace); if (locationArray != null) { String[] temp = ((XMLSchemaLoader.LocationArray) locationArray).getLocationArray(); if (temp.length != 0) { setLocationHints(fXSDDescription, temp, grammar); } } if (grammar == null || fXSDDescription.fLocationHints != null) { boolean toParseSchema = true; if (grammar != null) { // use location hints instead locationPairs = EMPTY_TABLE; } // try to parse the grammar using location hints from that namespace.. try { XMLInputSource xis = XMLSchemaLoader.resolveDocument( fXSDDescription, locationPairs, fEntityResolver); if (grammar != null && fNamespaceGrowth) { try { // if we are dealing with a different schema location, then include the new schema // into the existing grammar if (grammar.getDocumentLocations().contains(XMLEntityManager.expandSystemId(xis.getSystemId(), xis.getBaseSystemId(), false))) { toParseSchema = false; } } catch (MalformedURIException e) { } } if (toParseSchema) { grammar = fSchemaLoader.loadSchema(fXSDDescription, xis, fLocationPairs); } } catch (IOException ex) { final String [] locationHints = fXSDDescription.getLocationHints(); fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "schema_reference.4", new Object[] { locationHints != null ? locationHints[0] : XMLSymbols.EMPTY_STRING }, XMLErrorReporter.SEVERITY_WARNING, ex); } } } return grammar; } //findSchemaGrammar private boolean hasSchemaComponent(SchemaGrammar grammar, short contextType, QName triggeringComponent) { if (grammar != null && triggeringComponent != null) { String localName = triggeringComponent.localpart; if (localName != null && localName.length() > 0) { switch (contextType) { case XSDDescription.CONTEXT_ELEMENT: return grammar.getElementDeclaration(localName) != null; case XSDDescription.CONTEXT_ATTRIBUTE: return grammar.getAttributeDeclaration(localName) != null; case XSDDescription.CONTEXT_XSITYPE: return grammar.getTypeDefinition(localName) != null; } } } return false; } private void setLocationHints(XSDDescription desc, String[] locations, SchemaGrammar grammar) { int length = locations.length; if (grammar == null) { fXSDDescription.fLocationHints = new String[length]; System.arraycopy(locations, 0, fXSDDescription.fLocationHints, 0, length); } else { setLocationHints(desc, locations, grammar.getDocumentLocations()); } } private void setLocationHints(XSDDescription desc, String[] locations, StringList docLocations) { int length = locations.length; String[] hints = new String[length]; int counter = 0; for (int i=0; i<length; i++) { if (!docLocations.contains(locations[i])) { hints[counter++] = locations[i]; } } if (counter > 0) { if (counter == length) { fXSDDescription.fLocationHints = hints; } else { fXSDDescription.fLocationHints = new String[counter]; System.arraycopy(hints, 0, fXSDDescription.fLocationHints, 0, counter); } } } private boolean isValidBuiltInTypeName(String localpart) { if (fSchemaVersion == Constants.SCHEMA_VERSION_1_0_EXTENDED) { if (localpart.equals("duration") || localpart.equals("yearMonthDuration") || localpart.equals("dayTimeDuration")) { return false; } } return true; } XSTypeDefinition getAndCheckXsiType(QName element, String xsiType, XMLAttributes attributes) { // This method also deals with clause 1.2.1.2 of the constraint // Validation Rule: Schema-Validity Assessment (Element) // Element Locally Valid (Element) // 4 If there is an attribute information item among the element information item's [attributes] whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is type, then all of the following must be true: // 4.1 The normalized value of that attribute information item must be valid with respect to the built-in QName simple type, as defined by String Valid (3.14.4); QName typeName = null; try { typeName = (QName) fQNameDV.validate(xsiType, fValidationState, null); } catch (InvalidDatatypeValueException e) { reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError( "cvc-elt.4.1", new Object[] { element.rawname, SchemaSymbols.URI_XSI + "," + SchemaSymbols.XSI_TYPE, xsiType }); return null; } // 4.2 The local name and namespace name (as defined in QName Interpretation (3.15.3)), of the actual value of that attribute information item must resolve to a type definition, as defined in QName resolution (Instance) (3.15.4) XSTypeDefinition type = null; // if the namespace is schema namespace, first try built-in types if (typeName.uri == SchemaSymbols.URI_SCHEMAFORSCHEMA) { if (isValidBuiltInTypeName(typeName.localpart)) { SchemaGrammar s4s = SchemaGrammar.getS4SGrammar(fSchemaVersion); type = s4s.getGlobalTypeDecl(typeName.localpart); } } // if it's not schema built-in types, then try to get a grammar if (type == null) { //try to find schema grammar by different means.... SchemaGrammar grammar = findSchemaGrammar( XSDDescription.CONTEXT_XSITYPE, typeName.uri, element, typeName, attributes); if (grammar != null) type = grammar.getGlobalTypeDecl(typeName.localpart); } // still couldn't find the type, report an error if (type == null) { reportSchemaError("cvc-elt.4.2", new Object[] { element.rawname, xsiType }); return null; } // if there is no current type, set this one as current. // and we don't need to do extra checking if (fCurrentType != null) { short block = XSConstants.DERIVATION_NONE; // 4.3 The local type definition must be validly derived from the {type definition} given the union of the {disallowed substitutions} and the {type definition}'s {prohibited substitutions}, as defined in Type Derivation OK (Complex) (3.4.6) (if it is a complex type definition), or given {disallowed substitutions} as defined in Type Derivation OK (Simple) (3.14.6) (if it is a simple type definition). // Note: It's possible to have fCurrentType be non-null and fCurrentElemDecl // be null, if the current type is set using the property "root-type-definition". // In that case, we don't disallow any substitutions. -PM if (fCurrentElemDecl != null) { block = fCurrentElemDecl.fBlock; } if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { block |= ((XSComplexTypeDecl) fCurrentType).fBlock; } if (!fXSConstraints.checkTypeDerivationOk(type, fCurrentType, block)) { reportSchemaError( "cvc-elt.4.3", new Object[] { element.rawname, xsiType, fCurrentType.getName()}); } } return type; } //getAndCheckXsiType boolean getXsiNil(QName element, String xsiNil) { // Element Locally Valid (Element) // 3 The appropriate case among the following must be true: // 3.1 If {nillable} is false, then there must be no attribute information item among the element information item's [attributes] whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is nil. if (fCurrentElemDecl != null && !fCurrentElemDecl.getNillable()) { reportSchemaError( "cvc-elt.3.1", new Object[] { element.rawname, SchemaSymbols.URI_XSI + "," + SchemaSymbols.XSI_NIL }); } // 3.2 If {nillable} is true and there is such an attribute information item and its actual value is true , then all of the following must be true: // 3.2.2 There must be no fixed {value constraint}. else { String value = XMLChar.trim(xsiNil); if (value.equals(SchemaSymbols.ATTVAL_TRUE) || value.equals(SchemaSymbols.ATTVAL_TRUE_1)) { if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { reportSchemaError( "cvc-elt.3.2.2", new Object[] { element.rawname, SchemaSymbols.URI_XSI + "," + SchemaSymbols.XSI_NIL }); } return true; } } return false; } boolean allowAttribute(XSWildcardDecl attrWildcard, QName name, SchemaGrammar grammar) { if (attrWildcard.allowQName(name)) { if (grammar == null || !attrWildcard.fDisallowedDefined) { return true; } return (grammar.getGlobalAttributeDecl(name.localpart) == null); } return false; } void processAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { if (DEBUG) { System.out.println("==>processAttributes: " + attributes.getLength()); } // whether we have seen a Wildcard ID. String wildcardIDName = null; // for each present attribute int attCount = attributes.getLength(); Augmentations augs = null; AttributePSVImpl attrPSVI = null; boolean isSimple = fCurrentType == null || fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE; XSObjectList attrUses = null; int useCount = 0; XSWildcardDecl attrWildcard = null; if (!isSimple) { attrUses = attrGrp.getAttributeUses(); useCount = attrUses.getLength(); attrWildcard = attrGrp.fAttributeWC; } // Element Locally Valid (Complex Type) // 3 For each attribute information item in the element information item's [attributes] excepting // those whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose // [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation, the appropriate // case among the following must be true: // get the corresponding attribute decl for (int index = 0; index < attCount; index++) { attributes.getName(index, fTempQName); if (DEBUG) { System.out.println("==>process attribute: " + fTempQName); } if (fAugPSVI || fIdConstraint) { augs = attributes.getAugmentations(index); attrPSVI = (AttributePSVImpl) augs.getItem(Constants.ATTRIBUTE_PSVI); if (attrPSVI != null) { attrPSVI.reset(); } else { attrPSVI = new AttributePSVImpl(); augs.putItem(Constants.ATTRIBUTE_PSVI, attrPSVI); } // PSVI attribute: validation context attrPSVI.fValidationContext = fValidationRoot; } // Element Locally Valid (Type) // 3.1.1 The element information item's [attributes] must be empty, excepting those // whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and // whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation. // for the 4 xsi attributes, get appropriate decl, and validate if (fTempQName.uri == SchemaSymbols.URI_XSI) { XSAttributeDecl attrDecl = null; if (fTempQName.localpart == SchemaSymbols.XSI_TYPE) { attrDecl = XSI_TYPE; } else if (fTempQName.localpart == SchemaSymbols.XSI_NIL) { attrDecl = XSI_NIL; } else if (fTempQName.localpart == SchemaSymbols.XSI_SCHEMALOCATION) { attrDecl = XSI_SCHEMALOCATION; } else if (fTempQName.localpart == SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION) { attrDecl = XSI_NONAMESPACESCHEMALOCATION; } if (attrDecl != null) { processOneAttribute(element, attributes, index, attrDecl, null, attrPSVI); continue; } } // for namespace attributes, no_validation/unknow_validity if (fTempQName.rawname == XMLSymbols.PREFIX_XMLNS || fTempQName.rawname.startsWith("xmlns:")) { continue; } // simple type doesn't allow any other attributes if (isSimple) { reportSchemaError( "cvc-type.3.1.1", new Object[] { element.rawname, fTempQName.rawname }); continue; } // it's not xmlns, and not xsi, then we need to find a decl for it XSAttributeUseImpl currUse = null, oneUse; for (int i = 0; i < useCount; i++) { oneUse = (XSAttributeUseImpl) attrUses.item(i); if (oneUse.fAttrDecl.fName == fTempQName.localpart && oneUse.fAttrDecl.fTargetNamespace == fTempQName.uri) { currUse = oneUse; break; } } // 3.2 otherwise all of the following must be true: // 3.2.1 There must be an {attribute wildcard}. // 3.2.2 The attribute information item must be valid with respect to it as defined in Item Valid (Wildcard) (3.10.4). // if failed, get it from wildcard if (currUse == null) { //if (attrWildcard == null) // reportSchemaError("cvc-complex-type.3.2.1", new Object[]{element.rawname, fTempQName.rawname}); SchemaGrammar grammar = (fSchemaVersion < Constants.SCHEMA_VERSION_1_1) ? null : findSchemaGrammar( XSDDescription.CONTEXT_ATTRIBUTE, fTempQName.uri, element, fTempQName, attributes); if (attrWildcard == null || !allowAttribute(attrWildcard, fTempQName, grammar)) { // so this attribute is not allowed reportSchemaError( "cvc-complex-type.3.2.2", new Object[] { element.rawname, fTempQName.rawname }); // We have seen an attribute that was not declared fNFullValidationDepth = fElementDepth; continue; } } XSAttributeDecl currDecl = null; if (currUse != null) { currDecl = currUse.fAttrDecl; } else { // which means it matches a wildcard // skip it if processContents is skip if (attrWildcard.fProcessContents == XSWildcardDecl.PC_SKIP) continue; //try to find grammar by different means... SchemaGrammar grammar = findSchemaGrammar( XSDDescription.CONTEXT_ATTRIBUTE, fTempQName.uri, element, fTempQName, attributes); if (grammar != null) { currDecl = grammar.getGlobalAttributeDecl(fTempQName.localpart); } // if can't find if (currDecl == null) { // if strict, report error if (attrWildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { reportSchemaError( "cvc-complex-type.3.2.2", new Object[] { element.rawname, fTempQName.rawname }); } // then continue to the next attribute continue; } else { // 5 Let [Definition:] the wild IDs be the set of all attribute information item to which clause 3.2 applied and whose validation resulted in a context-determined declaration of mustFind or no context-determined declaration at all, and whose [local name] and [namespace name] resolve (as defined by QName resolution (Instance) (3.15.4)) to an attribute declaration whose {type definition} is or is derived from ID. Then all of the following must be true: // 5.1 There must be no more than one item in wild IDs. // // Only applies to XML Schema 1.0 if (fSchemaVersion < Constants.SCHEMA_VERSION_1_1 && currDecl.fType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE && ((XSSimpleType) currDecl.fType).isIDType()) { if (wildcardIDName != null) { reportSchemaError( "cvc-complex-type.5.1", new Object[] { element.rawname, currDecl.fName, wildcardIDName }); } else wildcardIDName = currDecl.fName; } } } processOneAttribute(element, attributes, index, currDecl, currUse, attrPSVI); } // end of for (all attributes) // 5.2 If wild IDs is non-empty, there must not be any attribute uses among the {attribute uses} whose {attribute declaration}'s {type definition} is or is derived from ID. // // Only applies to XML Schema 1.0 // Since we do not set the wildcardIDName if it's 1.1, no need to explicitly check for the version if (!isSimple && attrGrp.fIDAttrName != null && wildcardIDName != null) { reportSchemaError( "cvc-complex-type.5.2", new Object[] { element.rawname, wildcardIDName, attrGrp.fIDAttrName }); } } //processAttributes void processOneAttribute( QName element, XMLAttributes attributes, int index, XSAttributeDecl currDecl, XSAttributeUseImpl currUse, AttributePSVImpl attrPSVI) { String attrValue = attributes.getValue(index); fXSIErrorReporter.pushContext(); // Attribute Locally Valid // For an attribute information item to be locally valid with respect to an attribute declaration all of the following must be true: // 1 The declaration must not be absent (see Missing Sub-components (5.3) for how this can fail to be the case). // 2 Its {type definition} must not be absent. // 3 The item's normalized value must be locally valid with respect to that {type definition} as per String Valid (3.14.4). // get simple type XSSimpleType attDV = currDecl.fType; Object actualValue = null; try { actualValue = attDV.validate(attrValue, fValidationState, fValidatedInfo); // additional check for assertions processing, for simple type having // variety 'union'. if (attDV.getVariety() == XSSimpleTypeDefinition.VARIETY_UNION) { if (XSTypeHelper.isAtomicValueValidForAnUnion(attDV.getMemberTypes(), attrValue, null)) { fisAtomicValueValid = false; } } // store the normalized value if (fNormalizeData) { attributes.setValue(index, fValidatedInfo.normalizedValue); } // PSVI: element notation if (attDV.getVariety() == XSSimpleType.VARIETY_ATOMIC && attDV.getPrimitiveKind() == XSSimpleType.PRIMITIVE_NOTATION) { QName qName = (QName) actualValue; SchemaGrammar grammar = fGrammarBucket.getGrammar(qName.uri); //REVISIT: is it possible for the notation to be in different namespace than the attribute //with which it is associated, CHECK !! <fof n1:att1 = "n2:notation1" ..> // should we give chance to the application to be able to retrieve a grammar - nb //REVISIT: what would be the triggering component here.. if it is attribute value that // triggered the loading of grammar ?? -nb if (grammar != null) { fNotation = grammar.getGlobalNotationDecl(qName.localpart); } } } catch (InvalidDatatypeValueException idve) { fisAtomicValueValid = false; reportSchemaError(idve.getKey(), idve.getArgs()); reportSchemaError( "cvc-attribute.3", new Object[] { element.rawname, fTempQName.rawname, attrValue, (attDV instanceof XSSimpleTypeDecl) ? ((XSSimpleTypeDecl) attDV).getTypeName() : attDV.getName()}); } // get the value constraint from use or decl // 4 The item's actual value must match the value of the {value constraint}, if it is present and fixed. // now check the value against the simpleType if (actualValue != null && currDecl.getConstraintType() == XSConstants.VC_FIXED) { if (!ValidatedInfo.isComparable(fValidatedInfo, currDecl.fDefault) || !actualValue.equals(currDecl.fDefault.actualValue)) { reportSchemaError( "cvc-attribute.4", new Object[] { element.rawname, fTempQName.rawname, attrValue, currDecl.fDefault.stringValue()}); } } // 3.1 If there is among the {attribute uses} an attribute use with an {attribute declaration} whose {name} matches the attribute information item's [local name] and whose {target namespace} is identical to the attribute information item's [namespace name] (where an absent {target namespace} is taken to be identical to a [namespace name] with no value), then the attribute information must be valid with respect to that attribute use as per Attribute Locally Valid (Use) (3.5.4). In this case the {attribute declaration} of that attribute use is the context-determined declaration for the attribute information item with respect to Schema-Validity Assessment (Attribute) (3.2.4) and Assessment Outcome (Attribute) (3.2.5). if (actualValue != null && currUse != null && currUse.fConstraintType == XSConstants.VC_FIXED) { if (!ValidatedInfo.isComparable(fValidatedInfo, currUse.fDefault) || !actualValue.equals(currUse.fDefault.actualValue)) { reportSchemaError( "cvc-complex-type.3.1", new Object[] { element.rawname, fTempQName.rawname, attrValue, currUse.fDefault.stringValue()}); } } if (fIdConstraint) { attrPSVI.fValue.copyFrom(fValidatedInfo); } if (fAugPSVI) { // PSVI: attribute declaration attrPSVI.fDeclaration = currDecl; // PSVI: attribute type attrPSVI.fTypeDecl = attDV; // PSVI: attribute normalized value // NOTE: we always store the normalized value, even if it's invlid, // because it might still be useful to the user. But when the it's // not valid, the normalized value is not trustable. attrPSVI.fValue.copyFrom(fValidatedInfo); // PSVI: validation attempted: attrPSVI.fValidationAttempted = AttributePSVI.VALIDATION_FULL; // We have seen an attribute that was declared. fNNoneValidationDepth = fElementDepth; String[] errors = fXSIErrorReporter.mergeContext(); // PSVI: error codes attrPSVI.fErrors = errors; // PSVI: validity attrPSVI.fValidity = (errors == null) ? AttributePSVI.VALIDITY_VALID : AttributePSVI.VALIDITY_INVALID; } } void addDefaultAttributes( QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // REVISIT: should we check prohibited attributes? // (2) report error for PROHIBITED attrs that are present (V_TAGc) // (3) add default attrs (FIXED and NOT_FIXED) // if (DEBUG) { System.out.println("==>addDefaultAttributes: " + element); } XSObjectList attrUses = attrGrp.getAttributeUses(); int useCount = attrUses.getLength(); XSAttributeUseImpl currUse; XSAttributeDecl currDecl; short constType; ValidatedInfo defaultValue; boolean isSpecified; QName attName; // for each attribute use for (int i = 0; i < useCount; i++) { currUse = (XSAttributeUseImpl) attrUses.item(i); currDecl = currUse.fAttrDecl; // get value constraint constType = currUse.fConstraintType; defaultValue = currUse.fDefault; if (constType == XSConstants.VC_NONE) { constType = currDecl.getConstraintType(); defaultValue = currDecl.fDefault; } // whether this attribute is specified isSpecified = attributes.getValue(currDecl.fTargetNamespace, currDecl.fName) != null; // Element Locally Valid (Complex Type) // 4 The {attribute declaration} of each attribute use in the {attribute uses} whose // {required} is true matches one of the attribute information items in the element // information item's [attributes] as per clause 3.1 above. if (currUse.fUse == SchemaSymbols.USE_REQUIRED) { if (!isSpecified) reportSchemaError( "cvc-complex-type.4", new Object[] { element.rawname, currDecl.fName }); } // if the attribute is not specified, then apply the value constraint if (!isSpecified && constType != XSConstants.VC_NONE) { // Apply extra checking rules (ID/IDREF/ENTITY) final XSSimpleType attDV = currDecl.fType; final boolean facetChecking = fValidationState.needFacetChecking(); try { fValidationState.setFacetChecking(false); attDV.validate(fValidationState, defaultValue); // additional check for assertions processing, for simple type having // variety 'union'. if (attDV.getVariety() == XSSimpleTypeDefinition.VARIETY_UNION) { if (XSTypeHelper.isAtomicValueValidForAnUnion(attDV.getMemberTypes(), null, defaultValue)) { fisAtomicValueValid = false; } } } catch (InvalidDatatypeValueException idve) { fisAtomicValueValid = false; reportSchemaError(idve.getKey(), idve.getArgs()); } fValidationState.setFacetChecking(facetChecking); attName = new QName(null, currDecl.fName, currDecl.fName, currDecl.fTargetNamespace); String normalized = (defaultValue != null) ? defaultValue.stringValue() : ""; int attrIndex; if (attributes instanceof XMLAttributesImpl) { XMLAttributesImpl attrs = (XMLAttributesImpl) attributes; attrIndex = attrs.getLength(); attrs.addAttributeNS(attName, "CDATA", normalized); } else { attrIndex = attributes.addAttribute(attName, "CDATA", normalized); } if (fAugPSVI) { // PSVI: attribute is "schema" specified Augmentations augs = attributes.getAugmentations(attrIndex); AttributePSVImpl attrPSVI = new AttributePSVImpl(); augs.putItem(Constants.ATTRIBUTE_PSVI, attrPSVI); attrPSVI.fDeclaration = currDecl; attrPSVI.fTypeDecl = currDecl.fType; attrPSVI.fValue.copyFrom(defaultValue); attrPSVI.fValidationContext = fValidationRoot; attrPSVI.fValidity = AttributePSVI.VALIDITY_VALID; attrPSVI.fValidationAttempted = AttributePSVI.VALIDATION_FULL; attrPSVI.fSpecified = true; } } } // for } // addDefaultAttributes /** * If there is not text content, and there is a * {value constraint} on the corresponding element decl, then return * an XMLString representing the default value. */ void processElementContent(QName element) { // 1 If the item is ?valid? with respect to an element declaration as per Element Locally Valid (Element) (?3.3.4) and the {value constraint} is present, but clause 3.2 of Element Locally Valid (Element) (?3.3.4) above is not satisfied and the item has no element or character information item [children], then schema. Furthermore, the post-schema-validation infoset has the canonical lexical representation of the {value constraint} value as the item's [schema normalized value] property. if (fCurrentElemDecl != null && fCurrentElemDecl.fDefault != null && !fSawText && !fSubElement && !fNil) { String strv = fCurrentElemDecl.fDefault.stringValue(); int bufLen = strv.length(); if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < bufLen) { fNormalizedStr.ch = new char[bufLen]; } strv.getChars(0, bufLen, fNormalizedStr.ch, 0); fNormalizedStr.offset = 0; fNormalizedStr.length = bufLen; fDefaultValue = fNormalizedStr; } // fixed values are handled later, after xsi:type determined. fValidatedInfo.normalizedValue = null; // Element Locally Valid (Element) // 3.2.1 The element information item must have no character or element information item [children]. if (fNil) { if (fSubElement || fSawText) { reportSchemaError( "cvc-elt.3.2.1", new Object[] { element.rawname, SchemaSymbols.URI_XSI + "," + SchemaSymbols.XSI_NIL }); } } this.fValidatedInfo.reset(); // 5 The appropriate case among the following must be true: // 5.1 If the declaration has a {value constraint}, the item has neither element nor character [children] and clause 3.2 has not applied, then all of the following must be true: if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() != XSConstants.VC_NONE && !fSubElement && !fSawText && !fNil) { // 5.1.1 If the actual type definition is a local type definition then the canonical lexical representation of the {value constraint} value must be a valid default for the actual type definition as defined in Element Default Valid (Immediate) (3.3.6). if (fCurrentType != fCurrentElemDecl.fType) { //REVISIT:we should pass ValidatedInfo here. if (fXSConstraints .ElementDefaultValidImmediate( fCurrentType, fCurrentElemDecl.fDefault.stringValue(), fState4XsiType, null) == null) reportSchemaError( "cvc-elt.5.1.1", new Object[] { element.rawname, fCurrentType.getName(), fCurrentElemDecl.fDefault.stringValue()}); } // 5.1.2 The element information item with the canonical lexical representation of the {value constraint} value used as its normalized value must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4). // REVISIT: don't use toString, but validateActualValue instead // use the fState4ApplyDefault elementLocallyValidType(element, fCurrentElemDecl.fDefault.stringValue()); } else { // The following method call also deal with clause 1.2.2 of the constraint // Validation Rule: Schema-Validity Assessment (Element) // 5.2 If the declaration has no {value constraint} or the item has either element or character [children] or clause 3.2 has applied, then all of the following must be true: // 5.2.1 The element information item must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4). Object actualValue = elementLocallyValidType(element, fBuffer); // 5.2.2 If there is a fixed {value constraint} and clause 3.2 has not applied, all of the following must be true: if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED && !fNil) { String content = fBuffer.toString(); // 5.2.2.1 The element information item must have no element information item [children]. if (fSubElement) reportSchemaError("cvc-elt.5.2.2.1", new Object[] { element.rawname }); // 5.2.2.2 The appropriate case among the following must be true: if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; // 5.2.2.2.1 If the {content type} of the actual type definition is mixed, then the initial value of the item must match the canonical lexical representation of the {value constraint} value. if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { // REVISIT: how to get the initial value, does whiteSpace count? if (!fCurrentElemDecl.fDefault.normalizedValue.equals(content)) reportSchemaError( "cvc-elt.5.2.2.2.1", new Object[] { element.rawname, content, fCurrentElemDecl.fDefault.normalizedValue }); } // 5.2.2.2.2 If the {content type} of the actual type definition is a simple type definition, then the actual value of the item must match the canonical lexical representation of the {value constraint} value. else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (actualValue != null && (!ValidatedInfo.isComparable(fValidatedInfo, fCurrentElemDecl.fDefault) || !actualValue.equals(fCurrentElemDecl.fDefault.actualValue))) { reportSchemaError( "cvc-elt.5.2.2.2.2", new Object[] { element.rawname, content, fCurrentElemDecl.fDefault.stringValue()}); } } } else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { if (actualValue != null && (!ValidatedInfo.isComparable(fValidatedInfo, fCurrentElemDecl.fDefault) || !actualValue.equals(fCurrentElemDecl.fDefault.actualValue))) { // REVISIT: the spec didn't mention this case: fixed // value with simple type reportSchemaError( "cvc-elt.5.2.2.2.2", new Object[] { element.rawname, content, fCurrentElemDecl.fDefault.stringValue()}); } } } } if (fDefaultValue == null && fNormalizeData && fDocumentHandler != null && fUnionType) { // for union types we need to send data because we delayed sending // this data when we received it in the characters() call. String content = fValidatedInfo.normalizedValue; if (content == null) content = fBuffer.toString(); int bufLen = content.length(); if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < bufLen) { fNormalizedStr.ch = new char[bufLen]; } content.getChars(0, bufLen, fNormalizedStr.ch, 0); fNormalizedStr.offset = 0; fNormalizedStr.length = bufLen; fDocumentHandler.characters(fNormalizedStr, null); } } // processElementContent Object elementLocallyValidType(QName element, Object textContent) { if (fCurrentType == null) return null; Object retValue = null; // Element Locally Valid (Type) // 3 The appropriate case among the following must be true: // 3.1 If the type definition is a simple type definition, then all of the following must be true: if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { // 3.1.2 The element information item must have no element information item [children]. if (fSubElement) reportSchemaError("cvc-type.3.1.2", new Object[] { element.rawname }); // 3.1.3 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the normalized value must be valid with respect to the type definition as defined by String Valid (3.14.4). if (!fNil) { XSSimpleType dv = (XSSimpleType) fCurrentType; try { if (!fNormalizeData || fUnionType) { fValidationState.setNormalizationRequired(true); } retValue = dv.validate(textContent, fValidationState, fValidatedInfo); // additional check for assertions processing, for simple type having // variety 'union'. if (dv.getVariety() == XSSimpleTypeDefinition.VARIETY_UNION) { if (XSTypeHelper.isAtomicValueValidForAnUnion(dv.getMemberTypes(), String.valueOf(textContent), null)) { fisAtomicValueValid = false; } } } catch (InvalidDatatypeValueException e) { fisAtomicValueValid = false; reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError( "cvc-type.3.1.3", new Object[] { element.rawname, textContent }); } } } else { // 3.2 If the type definition is a complex type definition, then the element information item must be valid with respect to the type definition as per Element Locally Valid (Complex Type) (3.4.4); retValue = elementLocallyValidComplexType(element, textContent); } return retValue; } // elementLocallyValidType Object elementLocallyValidComplexType(QName element, Object textContent) { Object actualValue = null; XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; // Element Locally Valid (Complex Type) // For an element information item to be locally valid with respect to a complex type definition all of the following must be true: // 1 {abstract} is false. // 2 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the appropriate case among the following must be true: if (!fNil) { // 2.1 If the {content type} is empty, then the element information item has no character or element information item [children]. if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_EMPTY && (fSubElement || fSawText)) { reportSchemaError("cvc-complex-type.2.1", new Object[] { element.rawname }); } // 2.2 If the {content type} is a simple type definition, then the element information item has no element information item [children], and the normalized value of the element information item is valid with respect to that simple type definition as defined by String Valid (3.14.4). else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (fSubElement) reportSchemaError("cvc-complex-type.2.2", new Object[] { element.rawname }); XSSimpleType dv = ctype.fXSSimpleType; try { if (!fNormalizeData || fUnionType) { fValidationState.setNormalizationRequired(true); } actualValue = dv.validate(textContent, fValidationState, fValidatedInfo); // additional check for assertions processing, for simple type having // variety 'union'. if (dv.getVariety() == XSSimpleTypeDefinition.VARIETY_UNION) { if (XSTypeHelper.isAtomicValueValidForAnUnion(dv.getMemberTypes(), String.valueOf(textContent), null)) { fisAtomicValueValid = false; } } } catch (InvalidDatatypeValueException e) { fisAtomicValueValid = false; reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError("cvc-complex-type.2.2", new Object[] { element.rawname }); } // REVISIT: eventually, this method should return the same actualValue as elementLocallyValidType... // obviously it'll return null when the content is complex. } // 2.3 If the {content type} is element-only, then the element information item has no character information item [children] other than those whose [character code] is defined as a white space in [XML 1.0 (Second Edition)]. else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) { if (fSawCharacters) { reportSchemaError("cvc-complex-type.2.3", new Object[] { element.rawname }); } } // 2.4 If the {content type} is element-only or mixed, then the sequence of the element information item's element information item [children], if any, taken in order, is valid with respect to the {content type}'s particle, as defined in Element Sequence Locally Valid (Particle) (3.9.4). if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT || ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { // if the current state is a valid state, check whether // it's one of the final states. if (DEBUG) { System.out.println(fCurrCMState); } if (fCurrCMState[0] >= 0 && !fCurrentCM.endContentModel(fCurrCMState)) { String expected = expectedStr(fCurrentCM.whatCanGoHere(fCurrCMState)); final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int count = occurenceInfo[2]; // Check if this is a violation of minOccurs if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.j", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.i", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } else { reportSchemaError("cvc-complex-type.2.4.b", new Object[] { element.rawname, expected }); } } else { reportSchemaError("cvc-complex-type.2.4.b", new Object[] { element.rawname, expected }); } } } } return actualValue; } // elementLocallyValidComplexType void processRootTypeQName(final javax.xml.namespace.QName rootTypeQName) { String rootTypeNamespace = rootTypeQName.getNamespaceURI(); if (rootTypeNamespace != null && rootTypeNamespace.equals(XMLConstants.NULL_NS_URI)) { rootTypeNamespace = null; } if (SchemaSymbols.URI_SCHEMAFORSCHEMA.equals(rootTypeNamespace)) { String rootLocalPart = rootTypeQName.getLocalPart(); if (isValidBuiltInTypeName(rootLocalPart)) { SchemaGrammar s4s = SchemaGrammar.getS4SGrammar(fSchemaVersion); fCurrentType = s4s.getGlobalTypeDecl(rootLocalPart); } } else { final SchemaGrammar grammarForRootType = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, rootTypeNamespace, null, null, null); if (grammarForRootType != null) { fCurrentType = grammarForRootType.getGlobalTypeDecl(rootTypeQName.getLocalPart()); } } if (fCurrentType == null) { String typeName = (rootTypeQName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) ? rootTypeQName.getLocalPart() : rootTypeQName.getPrefix()+":"+rootTypeQName.getLocalPart(); reportSchemaError("cvc-type.1", new Object[] {typeName}); } } // processRootTypeQName void processRootElementDeclQName(final javax.xml.namespace.QName rootElementDeclQName, final QName element) { String rootElementDeclNamespace = rootElementDeclQName.getNamespaceURI(); if (rootElementDeclNamespace != null && rootElementDeclNamespace.equals(XMLConstants.NULL_NS_URI)) { rootElementDeclNamespace = null; } final SchemaGrammar grammarForRootElement = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, rootElementDeclNamespace, null, null, null); if (grammarForRootElement != null) { fCurrentElemDecl = grammarForRootElement.getGlobalElementDecl(rootElementDeclQName.getLocalPart()); } if (fCurrentElemDecl == null) { String declName = (rootElementDeclQName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) ? rootElementDeclQName.getLocalPart() : rootElementDeclQName.getPrefix()+":"+rootElementDeclQName.getLocalPart(); reportSchemaError("cvc-elt.1.a", new Object[] {declName}); } else { checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } } // processRootElementDeclQName void checkElementMatchesRootElementDecl(final XSElementDecl rootElementDecl, final QName element) { // Report an error if the name of the element does // not match the name of the specified element declaration. if (element.localpart != rootElementDecl.fName || element.uri != rootElementDecl.fTargetNamespace) { reportSchemaError("cvc-elt.1.b", new Object[] {element.rawname, rootElementDecl.fName}); } } // checkElementMatchesRootElementDecl void reportSchemaError(String key, Object[] arguments) { if (fDoValidation) fXSIErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, key, arguments, XMLErrorReporter.SEVERITY_ERROR); } private String expectedStr(Vector expected) { StringBuffer ret = new StringBuffer("{"); int size = expected.size(); for (int i = 0; i < size; i++) { if (i > 0) ret.append(", "); ret.append(expected.elementAt(i).toString()); } ret.append('}'); return ret.toString(); } /**********************************/ // xpath matcher information /** * Stack of XPath matchers for identity constraints. * * @author Andy Clark, IBM */ protected static class XPathMatcherStack { // // Data // /** Active matchers. */ protected XPathMatcher[] fMatchers = new XPathMatcher[4]; /** Count of active matchers. */ protected int fMatchersCount; /** Offset stack for contexts. */ protected IntStack fContextStack = new IntStack(); // // Constructors // public XPathMatcherStack() { } // <init>() // // Public methods // /** Resets the XPath matcher stack. */ public void clear() { for (int i = 0; i < fMatchersCount; i++) { fMatchers[i] = null; } fMatchersCount = 0; fContextStack.clear(); } // clear() /** Returns the size of the stack. */ public int size() { return fContextStack.size(); } // size():int /** Returns the count of XPath matchers. */ public int getMatcherCount() { return fMatchersCount; } // getMatcherCount():int /** Adds a matcher. */ public void addMatcher(XPathMatcher matcher) { ensureMatcherCapacity(); fMatchers[fMatchersCount++] = matcher; } // addMatcher(XPathMatcher) /** Returns the XPath matcher at the specified index. */ public XPathMatcher getMatcherAt(int index) { return fMatchers[index]; } // getMatcherAt(index):XPathMatcher /** Pushes a new context onto the stack. */ public void pushContext() { fContextStack.push(fMatchersCount); } // pushContext() /** Pops a context off of the stack. */ public void popContext() { fMatchersCount = fContextStack.pop(); } // popContext() // // Private methods // /** Ensures the size of the matchers array. */ private void ensureMatcherCapacity() { if (fMatchersCount == fMatchers.length) { XPathMatcher[] array = new XPathMatcher[fMatchers.length * 2]; System.arraycopy(fMatchers, 0, array, 0, fMatchers.length); fMatchers = array; } } // ensureMatcherCapacity() } // class XPathMatcherStack // value store implementations /** * Value store implementation base class. There are specific subclasses * for handling unique, key, and keyref. * * @author Andy Clark, IBM */ protected abstract class ValueStoreBase implements ValueStore { // // Data // /** Identity constraint. */ protected IdentityConstraint fIdentityConstraint; protected int fFieldCount = 0; protected Field[] fFields = null; protected String fElementName; /** current data */ protected Object[] fLocalValues = null; protected short[] fLocalValueTypes = null; protected ShortList[] fLocalItemValueTypes = null; /** Current data value count. */ protected int fValuesCount; /** global data */ public final Vector fValues = new Vector(); public ShortVector fValueTypes = null; public Vector fItemValueTypes = null; private boolean fUseValueTypeVector = false; private int fValueTypesLength = 0; private short fValueType = 0; private boolean fUseItemValueTypeVector = false; private int fItemValueTypesLength = 0; private ShortList fItemValueType = null; /** buffer for error messages */ final StringBuffer fTempBuffer = new StringBuffer(); // // Constructors // /** Constructs a value store for the specified identity constraint. */ protected ValueStoreBase(IdentityConstraint identityConstraint, String elementName) { fElementName = elementName; fIdentityConstraint = identityConstraint; fFieldCount = fIdentityConstraint.getFieldCount(); fFields = new Field[fFieldCount]; fLocalValues = new Object[fFieldCount]; fLocalValueTypes = new short[fFieldCount]; fLocalItemValueTypes = new ShortList[fFieldCount]; for (int i = 0; i < fFieldCount; i++) { fFields[i] = fIdentityConstraint.getFieldAt(i); } } // <init>(IdentityConstraint) // // Public methods // // destroys this ValueStore; useful when, for instance, a // locally-scoped ID constraint is involved. public void clear() { fValuesCount = 0; fUseValueTypeVector = false; fValueTypesLength = 0; fValueType = 0; fUseItemValueTypeVector = false; fItemValueTypesLength = 0; fItemValueType = null; fValues.setSize(0); if (fValueTypes != null) { fValueTypes.clear(); } if (fItemValueTypes != null) { fItemValueTypes.setSize(0); } } // end clear():void // appends the contents of one ValueStore to those of us. public void append(ValueStoreBase newVal) { for (int i = 0; i < newVal.fValues.size(); i++) { fValues.addElement(newVal.fValues.elementAt(i)); } } // append(ValueStoreBase) /** Start scope for value store. */ public void startValueScope() { fValuesCount = 0; for (int i = 0; i < fFieldCount; i++) { fLocalValues[i] = null; fLocalValueTypes[i] = 0; fLocalItemValueTypes[i] = null; } } // startValueScope() /** Ends scope for value store. */ public void endValueScope() { if (fValuesCount == 0) { if (fIdentityConstraint.getCategory() == IdentityConstraint.IC_KEY) { String code = "AbsentKeyValue"; String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { fElementName, cName }); } return; } // Validation Rule: Identity-constraint Satisfied // 4.2 If the {identity-constraint category} is key, then all of the following must be true: // 4.2.1 The target node set and the qualified node set are equal, that is, every member of the // target node set is also a member of the qualified node set and vice versa. // // If the IDC is a key check whether we have all the fields. if (fValuesCount != fFieldCount) { if (fIdentityConstraint.getCategory() == IdentityConstraint.IC_KEY) { String code = "KeyNotEnoughValues"; UniqueOrKey key = (UniqueOrKey) fIdentityConstraint; String cName = key.getIdentityConstraintName(); reportSchemaError(code, new Object[] { fElementName, cName }); } return; } } // endValueScope() // This is needed to allow keyref's to look for matched keys // in the correct scope. Unique and Key may also need to // override this method for purposes of their own. // This method is called whenever the DocumentFragment // of an ID Constraint goes out of scope. public void endDocumentFragment() { } // endDocumentFragment():void /** * Signals the end of the document. This is where the specific * instances of value stores can verify the integrity of the * identity constraints. */ public void endDocument() { } // endDocument() // // ValueStore methods // /* reports an error if an element is matched * has nillable true and is matched by a key. */ public void reportError(String key, Object[] args) { reportSchemaError(key, args); } // reportError(String,Object[]) /** * Adds the specified value to the value store. * * @param field The field associated to the value. This reference * is used to ensure that each field only adds a value * once within a selection scope. * @param mayMatch a flag indiciating whether the field may be matched. * @param actualValue The value to add. * @param valueType Type of the value to add. * @param itemValueType If the value is a list, a list of types for each of the values in the list. */ public void addValue(Field field, boolean mayMatch, Object actualValue, short valueType, ShortList itemValueType) { int i; for (i = fFieldCount - 1; i > -1; i--) { if (fFields[i] == field) { break; } } // do we even know this field? if (i == -1) { String code = "UnknownField"; String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { field.toString(), fElementName, cName }); return; } if (!mayMatch) { String code = "FieldMultipleMatch"; String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { field.toString(), cName }); } else { fValuesCount++; } fLocalValues[i] = actualValue; fLocalValueTypes[i] = valueType; fLocalItemValueTypes[i] = itemValueType; if (fValuesCount == fFieldCount) { checkDuplicateValues(); // store values for (i = 0; i < fFieldCount; i++) { fValues.addElement(fLocalValues[i]); addValueType(fLocalValueTypes[i]); addItemValueType(fLocalItemValueTypes[i]); } } } // addValue(String,Field) /** * Sets the name of the element which holds the identity constraint * that is stored in this value store */ public void setElementName(String elementName) { fElementName = elementName; } /** * Returns the name of the element which holds the identity constraint * that is stored in this value store */ public String getElementName() { return fElementName; } // getElementName():String /** * Returns true if this value store contains the locally scoped value stores */ public boolean contains() { // REVISIT: we can improve performance by using hash codes, instead of // traversing global vector that could be quite large. int next = 0; final int size = fValues.size(); LOOP : for (int i = 0; i < size; i = next) { next = i + fFieldCount; for (int j = 0; j < fFieldCount; j++) { Object value1 = fLocalValues[j]; Object value2 = fValues.elementAt(i); short valueType1 = fLocalValueTypes[j]; short valueType2 = getValueTypeAt(i); if (value1 == null || value2 == null || valueType1 != valueType2 || !(value1.equals(value2))) { continue LOOP; } else if(valueType1 == XSConstants.LIST_DT || valueType1 == XSConstants.LISTOFUNION_DT) { ShortList list1 = fLocalItemValueTypes[j]; ShortList list2 = getItemValueTypeAt(i); if(list1 == null || list2 == null || !list1.equals(list2)) continue LOOP; } i++; } // found it return true; } // didn't find it return false; } // contains():boolean /** * Returns -1 if this value store contains the specified * values, otherwise the index of the first field in the * key sequence. */ public int contains(ValueStoreBase vsb) { final Vector values = vsb.fValues; final int size1 = values.size(); if (fFieldCount <= 1) { for (int i = 0; i < size1; ++i) { short val = vsb.getValueTypeAt(i); if (!valueTypeContains(val) || !fValues.contains(values.elementAt(i))) { return i; } else if(val == XSConstants.LIST_DT || val == XSConstants.LISTOFUNION_DT) { ShortList list1 = vsb.getItemValueTypeAt(i); if (!itemValueTypeContains(list1)) { return i; } } } } /** Handle n-tuples. **/ else { final int size2 = fValues.size(); /** Iterate over each set of fields. **/ OUTER: for (int i = 0; i < size1; i += fFieldCount) { /** Check whether this set is contained in the value store. **/ INNER: for (int j = 0; j < size2; j += fFieldCount) { for (int k = 0; k < fFieldCount; ++k) { final Object value1 = values.elementAt(i+k); final Object value2 = fValues.elementAt(j+k); final short valueType1 = vsb.getValueTypeAt(i+k); final short valueType2 = getValueTypeAt(j+k); if (value1 != value2 && (valueType1 != valueType2 || value1 == null || !value1.equals(value2))) { continue INNER; } else if(valueType1 == XSConstants.LIST_DT || valueType1 == XSConstants.LISTOFUNION_DT) { ShortList list1 = vsb.getItemValueTypeAt(i+k); ShortList list2 = getItemValueTypeAt(j+k); if (list1 == null || list2 == null || !list1.equals(list2)) { continue INNER; } } } continue OUTER; } return i; } } return -1; } // contains(Vector):Object // // Protected methods // protected void checkDuplicateValues() { // no-op } // duplicateValue(Hashtable) /** Returns a string of the specified values. */ protected String toString(Object[] values) { // no values int size = values.length; if (size == 0) { return ""; } fTempBuffer.setLength(0); // construct value string for (int i = 0; i < size; i++) { if (i > 0) { fTempBuffer.append(','); } fTempBuffer.append(values[i]); } return fTempBuffer.toString(); } // toString(Object[]):String /** Returns a string of the specified values. */ protected String toString(Vector values, int start, int length) { // no values if (length == 0) { return ""; } // one value if (length == 1) { return String.valueOf(values.elementAt(start)); } // construct value string StringBuffer str = new StringBuffer(); for (int i = 0; i < length; i++) { if (i > 0) { str.append(','); } str.append(values.elementAt(start + i)); } return str.toString(); } // toString(Vector,int,int):String // // Object methods // /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { s = s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { s = s.substring(index2 + 1); } return s + '[' + fIdentityConstraint + ']'; } // toString():String // // Private methods // private void addValueType(short type) { if (fUseValueTypeVector) { fValueTypes.add(type); } else if (fValueTypesLength++ == 0) { fValueType = type; } else if (fValueType != type) { fUseValueTypeVector = true; if (fValueTypes == null) { fValueTypes = new ShortVector(fValueTypesLength * 2); } for (int i = 1; i < fValueTypesLength; ++i) { fValueTypes.add(fValueType); } fValueTypes.add(type); } } private short getValueTypeAt(int index) { if (fUseValueTypeVector) { return fValueTypes.valueAt(index); } return fValueType; } private boolean valueTypeContains(short value) { if (fUseValueTypeVector) { return fValueTypes.contains(value); } return fValueType == value; } private void addItemValueType(ShortList itemValueType) { if (fUseItemValueTypeVector) { fItemValueTypes.add(itemValueType); } else if (fItemValueTypesLength++ == 0) { fItemValueType = itemValueType; } else if (!(fItemValueType == itemValueType || (fItemValueType != null && fItemValueType.equals(itemValueType)))) { fUseItemValueTypeVector = true; if (fItemValueTypes == null) { fItemValueTypes = new Vector(fItemValueTypesLength * 2); } for (int i = 1; i < fItemValueTypesLength; ++i) { fItemValueTypes.add(fItemValueType); } fItemValueTypes.add(itemValueType); } } private ShortList getItemValueTypeAt(int index) { if (fUseItemValueTypeVector) { return (ShortList) fItemValueTypes.elementAt(index); } return fItemValueType; } private boolean itemValueTypeContains(ShortList value) { if (fUseItemValueTypeVector) { return fItemValueTypes.contains(value); } return fItemValueType == value || (fItemValueType != null && fItemValueType.equals(value)); } } // class ValueStoreBase /** * Unique value store. * * @author Andy Clark, IBM */ protected class UniqueValueStore extends ValueStoreBase { // // Constructors // /** Constructs a unique value store. */ public UniqueValueStore(UniqueOrKey unique, String elementName) { super(unique, elementName); } // <init>(Unique) // // ValueStoreBase protected methods // /** * Called when a duplicate value is added. */ protected void checkDuplicateValues() { // is this value as a group duplicated? if (contains()) { String code = "DuplicateUnique"; String value = toString(fLocalValues); String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { value, fElementName, cName }); } } // duplicateValue(Hashtable) } // class UniqueValueStore /** * Key value store. * * @author Andy Clark, IBM */ protected class KeyValueStore extends ValueStoreBase { // REVISIT: Implement a more efficient storage mechanism. -Ac // // Constructors // /** Constructs a key value store. */ public KeyValueStore(UniqueOrKey key, String elementName) { super(key, elementName); } // <init>(Key) // // ValueStoreBase protected methods // /** * Called when a duplicate value is added. */ protected void checkDuplicateValues() { if (contains()) { String code = "DuplicateKey"; String value = toString(fLocalValues); String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { value, fElementName, cName }); } } // duplicateValue(Hashtable) } // class KeyValueStore /** * Key reference value store. * * @author Andy Clark, IBM */ protected class KeyRefValueStore extends ValueStoreBase { // // Data // /** Key value store. */ protected ValueStoreBase fKeyValueStore; // // Constructors // /** Constructs a key value store. */ public KeyRefValueStore(KeyRef keyRef, KeyValueStore keyValueStore, String elementName) { super(keyRef, elementName); fKeyValueStore = keyValueStore; } // <init>(KeyRef) // // ValueStoreBase methods // // end the value Scope; here's where we have to tie // up keyRef loose ends. public void endDocumentFragment() { // do all the necessary management... super.endDocumentFragment(); // verify references // get the key store corresponding (if it exists): fKeyValueStore = (ValueStoreBase) fValueStoreCache.fGlobalIDConstraintMap.get( ((KeyRef) fIdentityConstraint).getKey()); if (fKeyValueStore == null) { // report error String code = "KeyRefOutOfScope"; String value = fIdentityConstraint.toString(); reportSchemaError(code, new Object[] { value }); return; } int errorIndex = fKeyValueStore.contains(this); if (errorIndex != -1) { String code = "KeyNotFound"; String values = toString(fValues, errorIndex, fFieldCount); String name = fIdentityConstraint.getName(); reportSchemaError(code, new Object[] { name, values, fElementName }); } } // endDocumentFragment() /** End document. */ public void endDocument() { super.endDocument(); } // endDocument() } // class KeyRefValueStore // value store management /** * Value store cache. This class is used to store the values for * identity constraints. * * @author Andy Clark, IBM */ protected class ValueStoreCache { // // Data // final LocalIDKey fLocalId = new LocalIDKey(); // values stores /** stores all global Values stores. */ protected final ArrayList fValueStores = new ArrayList(); /** * Values stores associated to specific identity constraints. * This hashtable maps IdentityConstraints and * the 0-based element on which their selectors first matched to * a corresponding ValueStore. This should take care * of all cases, including where ID constraints with * descendant-or-self axes occur on recursively-defined * elements. */ protected final HashMap fIdentityConstraint2ValueStoreMap = new HashMap(); // sketch of algorithm: // - when a constraint is first encountered, its // values are stored in the (local) fIdentityConstraint2ValueStoreMap; // - Once it is validated (i.e., when it goes out of scope), // its values are merged into the fGlobalIDConstraintMap; // - as we encounter keyref's, we look at the global table to // validate them. // // The fGlobalIDMapStack has the following structure: // - validation always occurs against the fGlobalIDConstraintMap // (which comprises all the "eligible" id constraints); // When an endElement is found, this Hashtable is merged with the one // below in the stack. // When a start tag is encountered, we create a new // fGlobalIDConstraintMap. // i.e., the top of the fGlobalIDMapStack always contains // the preceding siblings' eligible id constraints; // the fGlobalIDConstraintMap contains descendants+self. // keyrefs can only match descendants+self. protected final Stack fGlobalMapStack = new Stack(); protected final HashMap fGlobalIDConstraintMap = new HashMap(); // // Constructors // /** Default constructor. */ public ValueStoreCache() { } // <init>() // // Public methods // /** Resets the identity constraint cache. */ public void startDocument() { fValueStores.clear(); fIdentityConstraint2ValueStoreMap.clear(); fGlobalIDConstraintMap.clear(); fGlobalMapStack.removeAllElements(); } // startDocument() // startElement: pushes the current fGlobalIDConstraintMap // onto fGlobalMapStack and clears fGlobalIDConstraint map. public void startElement() { // only clone the map when there are elements if (fGlobalIDConstraintMap.size() > 0) fGlobalMapStack.push(fGlobalIDConstraintMap.clone()); else fGlobalMapStack.push(null); fGlobalIDConstraintMap.clear(); } // startElement(void) /** endElement(): merges contents of fGlobalIDConstraintMap with the * top of fGlobalMapStack into fGlobalIDConstraintMap. */ public void endElement() { if (fGlobalMapStack.isEmpty()) { return; // must be an invalid doc! } HashMap oldMap = (HashMap) fGlobalMapStack.pop(); // return if there is no element if (oldMap == null) { return; } Iterator entries = oldMap.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); IdentityConstraint id = (IdentityConstraint) entry.getKey(); ValueStoreBase oldVal = (ValueStoreBase) entry.getValue(); if (oldVal != null) { ValueStoreBase currVal = (ValueStoreBase) fGlobalIDConstraintMap.get(id); if (currVal == null) { fGlobalIDConstraintMap.put(id, oldVal); } else if (currVal != oldVal) { currVal.append(oldVal); } } } } // endElement() /** * Initializes the value stores for the specified element * declaration. */ public void initValueStoresFor(XSElementDecl eDecl, FieldActivator activator) { // initialize value stores for unique fields IdentityConstraint[] icArray = eDecl.fIDConstraints; int icCount = eDecl.fIDCPos; for (int i = 0; i < icCount; i++) { switch (icArray[i].getCategory()) { case (IdentityConstraint.IC_UNIQUE) : // initialize value stores for unique fields UniqueOrKey unique = (UniqueOrKey) icArray[i]; LocalIDKey toHash = new LocalIDKey(unique, fElementDepth); UniqueValueStore uniqueValueStore = (UniqueValueStore) fIdentityConstraint2ValueStoreMap.get(toHash); if (uniqueValueStore == null) { uniqueValueStore = new UniqueValueStore(unique, eDecl.getName()); fIdentityConstraint2ValueStoreMap.put(toHash, uniqueValueStore); } else { uniqueValueStore.clear(); uniqueValueStore.setElementName(eDecl.getName()); } fValueStores.add(uniqueValueStore); activateSelectorFor(icArray[i]); break; case (IdentityConstraint.IC_KEY) : // initialize value stores for key fields UniqueOrKey key = (UniqueOrKey) icArray[i]; toHash = new LocalIDKey(key, fElementDepth); KeyValueStore keyValueStore = (KeyValueStore) fIdentityConstraint2ValueStoreMap.get(toHash); if (keyValueStore == null) { keyValueStore = new KeyValueStore(key, eDecl.getName()); fIdentityConstraint2ValueStoreMap.put(toHash, keyValueStore); } else { keyValueStore.clear(); keyValueStore.setElementName(eDecl.getName()); } fValueStores.add(keyValueStore); activateSelectorFor(icArray[i]); break; case (IdentityConstraint.IC_KEYREF) : // initialize value stores for keyRef fields KeyRef keyRef = (KeyRef) icArray[i]; toHash = new LocalIDKey(keyRef, fElementDepth); KeyRefValueStore keyRefValueStore = (KeyRefValueStore) fIdentityConstraint2ValueStoreMap.get(toHash); if (keyRefValueStore == null) { keyRefValueStore = new KeyRefValueStore(keyRef, null, eDecl.getName()); fIdentityConstraint2ValueStoreMap.put(toHash, keyRefValueStore); } else { keyRefValueStore.clear(); keyRefValueStore.setElementName(eDecl.getName()); } fValueStores.add(keyRefValueStore); activateSelectorFor(icArray[i]); break; } } } // initValueStoresFor(XSElementDecl) /** Returns the value store associated to the specified IdentityConstraint. */ public ValueStoreBase getValueStoreFor(IdentityConstraint id, int initialDepth) { fLocalId.fDepth = initialDepth; fLocalId.fId = id; return (ValueStoreBase) fIdentityConstraint2ValueStoreMap.get(fLocalId); } // getValueStoreFor(IdentityConstraint, int):ValueStoreBase /** Returns the global value store associated to the specified IdentityConstraint. */ public ValueStoreBase getGlobalValueStoreFor(IdentityConstraint id) { return (ValueStoreBase) fGlobalIDConstraintMap.get(id); } // getValueStoreFor(IdentityConstraint):ValueStoreBase // This method takes the contents of the (local) ValueStore // associated with id and moves them into the global // hashtable, if id is a <unique> or a <key>. // If it's a <keyRef>, then we leave it for later. public void transplant(IdentityConstraint id, int initialDepth) { fLocalId.fDepth = initialDepth; fLocalId.fId = id; ValueStoreBase newVals = (ValueStoreBase) fIdentityConstraint2ValueStoreMap.get(fLocalId); if (id.getCategory() == IdentityConstraint.IC_KEYREF) return; ValueStoreBase currVals = (ValueStoreBase) fGlobalIDConstraintMap.get(id); if (currVals != null) { currVals.append(newVals); fGlobalIDConstraintMap.put(id, currVals); } else fGlobalIDConstraintMap.put(id, newVals); } // transplant(id) /** Check identity constraints. */ public void endDocument() { int count = fValueStores.size(); for (int i = 0; i < count; i++) { ValueStoreBase valueStore = (ValueStoreBase) fValueStores.get(i); valueStore.endDocument(); } } // endDocument() // // Object methods // /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { return s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { return s.substring(index2 + 1); } return s; } // toString():String } // class ValueStoreCache // the purpose of this class is to enable IdentityConstraint,int // pairs to be used easily as keys in Hashtables. protected static final class LocalIDKey { public IdentityConstraint fId; public int fDepth; public LocalIDKey() { } public LocalIDKey(IdentityConstraint id, int depth) { fId = id; fDepth = depth; } // init(IdentityConstraint, int) // object method public int hashCode() { return fId.hashCode() + fDepth; } public boolean equals(Object localIDKey) { if (localIDKey instanceof LocalIDKey) { LocalIDKey lIDKey = (LocalIDKey) localIDKey; return (lIDKey.fId == fId && lIDKey.fDepth == fDepth); } return false; } } // class LocalIDKey /** * A simple vector for <code>short</code>s. */ protected static final class ShortVector { // // Data // /** Current length. */ private int fLength; /** Data. */ private short[] fData; // // Constructors // public ShortVector() {} public ShortVector(int initialCapacity) { fData = new short[initialCapacity]; } // // Public methods // /** Returns the length of the vector. */ public int length() { return fLength; } /** Adds the value to the vector. */ public void add(short value) { ensureCapacity(fLength + 1); fData[fLength++] = value; } /** Returns the short value at the specified position in the vector. */ public short valueAt(int position) { return fData[position]; } /** Clears the vector. */ public void clear() { fLength = 0; } /** Returns whether the short is contained in the vector. */ public boolean contains(short value) { for (int i = 0; i < fLength; ++i) { if (fData[i] == value) { return true; } } return false; } // // Private methods // /** Ensures capacity. */ private void ensureCapacity(int size) { if (fData == null) { fData = new short[8]; } else if (fData.length <= size) { short[] newdata = new short[fData.length * 2]; System.arraycopy(fData, 0, newdata, 0, fData.length); fData = newdata; } } } } // class XMLSchemaValidator
false
true
Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) { if (DEBUG) { System.out.println("==>handleStartElement: " + element); } // root element if (fElementDepth == -1 && fValidationManager.isGrammarFound()) { if (fSchemaType == null) { // schemaType is not specified // if a DTD grammar is found, we do the same thing as Dynamic: // if a schema grammar is found, validation is performed; // otherwise, skip the whole document. fSchemaDynamicValidation = true; } else { // [1] Either schemaType is DTD, and in this case validate/schema is turned off // [2] Validating against XML Schemas only // [a] dynamic validation is false: report error if SchemaGrammar is not found // [b] dynamic validation is true: if grammar is not found ignore. } } // get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, // parse them to get the grammars. But only do this if the grammar can grow. if (!fUseGrammarPoolOnly) { String sLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); //store the location hints.. we need to do it so that we can defer the loading of grammar until //there is a reference to a component from that namespace. To provide location hints to the //application for a namespace storeLocations(sLocation, nsLocation); } // if we are in the content of "skip", then just skip this element // REVISIT: is this the correct behaviour for ID constraints? -NG if (fSkipValidationDepth >= 0) { fElementDepth++; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // if we are not skipping this element, and there is a content model, // we try to find the corresponding decl object for this element. // the reason we move this part of code here is to make sure the // error reported here (if any) is stored within the parent element's // context, instead of that of the current element. Object decl = null; if (fCurrentCM != null) { decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler, this); // it could be an element decl or a wildcard decl if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; //REVISIT: is it the only case we will have particle = null? Vector next; if (ctype.fParticle != null && (next = fCurrentCM.whatCanGoHere(fCurrCMState)).size() > 0) { String expected = expectedStr(next); final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of minOccurs if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.h", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.g", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } // Check if this is a violation of maxOccurs else if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.e", new Object[] { element.rawname, expected, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { element.rawname, expected }); } } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { element.rawname, expected }); } } else { final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of maxOccurs if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.f", new Object[] { element.rawname, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } } } // if it's not the root element, we push the current states in the stacks if (fElementDepth != -1) { ensureStackCapacity(); fSubElementStack[fElementDepth] = true; fSubElement = false; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fNotationStack[fElementDepth] = fNotation; fTypeStack[fElementDepth] = fCurrentType; fStrictAssessStack[fElementDepth] = fStrictAssess; fCMStack[fElementDepth] = fCurrentCM; fCMStateStack[fElementDepth] = fCurrCMState; fSawTextStack[fElementDepth] = fSawText; fStringContent[fElementDepth] = fSawCharacters; } // increase the element depth after we've saved // all states for the parent element fElementDepth++; fCurrentElemDecl = null; XSWildcardDecl wildcard = null; fCurrentType = null; fStrictAssess = true; fNil = false; fNotation = null; // and the buffer to hold the value of the element fBuffer.setLength(0); fSawText = false; fSawCharacters = false; // check what kind of declaration the "decl" from // oneTransition() maps to if (decl != null) { if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl) decl; } else if (decl instanceof XSOpenContentDecl) { wildcard = (XSWildcardDecl) ((XSOpenContentDecl)decl).getWildcard(); } else { wildcard = (XSWildcardDecl) decl; } } // if the wildcard is skip, then return if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) { fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } if (fElementDepth == 0) { // 1.1.1.1 An element declaration was stipulated by the processor if (fRootElementDeclaration != null) { fCurrentElemDecl = fRootElementDeclaration; checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } else if (fRootElementDeclQName != null) { processRootElementDeclQName(fRootElementDeclQName, element); } // 1.2.1.1 A type definition was stipulated by the processor else if (fRootTypeDefinition != null) { fCurrentType = fRootTypeDefinition; } else if (fRootTypeQName != null) { processRootTypeQName(fRootTypeQName); } } // if there was no processor stipulated type if (fCurrentType == null) { // try again to get the element decl: // case 1: find declaration for root element // case 2: find declaration for element from another namespace if (fCurrentElemDecl == null) { // try to find schema grammar by different means.. SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, attributes); if (sGrammar != null) { fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } } if (fCurrentElemDecl != null) { // then get the type fCurrentType = fCurrentElemDecl.fType; } } //process type alternatives if (fTypeAlternativesChecking && fCurrentElemDecl != null) { XSTypeDefinition currentType = fTypeAlternativeValidator.getCurrentType(fCurrentElemDecl, element, attributes); if (currentType != null) { fCurrentType = currentType; } } // check if we should be ignoring xsi:type on this element if (fElementDepth == fIgnoreXSITypeDepth && fCurrentElemDecl == null) { fIgnoreXSITypeDepth++; } // process xsi:type attribute information String xsiType = null; if (fElementDepth >= fIgnoreXSITypeDepth) { xsiType = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_TYPE); } // if no decl/type found for the current element if (fCurrentType == null && xsiType == null) { // if this is the validation root, report an error, because // we can't find eith decl or type for this element // REVISIT: should we report error, or warning? if (fElementDepth == 0) { // for dynamic validation, skip the whole content, // because no grammar was found. if (fDynamicValidation || fSchemaDynamicValidation) { // no schema grammar was found, but it's either dynamic // validation, or another kind of grammar was found (DTD, // for example). The intended behavior here is to skip // the whole document. To improve performance, we try to // remove the validator from the pipeline, since it's not // supposed to do anything. if (fDocumentSource != null) { fDocumentSource.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) fDocumentHandler.setDocumentSource(fDocumentSource); // indicate that the validator was removed. fElementDepth = -2; return augs; } fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // We don't call reportSchemaError here, because the spec // doesn't think it's invalid not to be able to find a // declaration or type definition for an element. Xerces is // reporting it as an error for historical reasons, but in // PSVI, we shouldn't mark this element as invalid because // of this. - SG fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "cvc-elt.1.a", new Object[] { element.rawname }, XMLErrorReporter.SEVERITY_ERROR); } // if wildcard = strict, report error. // needs to be called before fXSIErrorReporter.pushContext() // so that the error belongs to the parent element. else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { // report error, because wilcard = strict reportSchemaError("cvc-complex-type.2.4.c", new Object[] { element.rawname }); } // no element decl or type found for this element. // Allowed by the spec, we can choose to either laxly assess this // element, or to skip it. Now we choose lax assessment. fCurrentType = SchemaGrammar.getXSAnyType(fSchemaVersion); fStrictAssess = false; fNFullValidationDepth = fElementDepth; // any type has mixed content, so we don't need to append buffer fAppendBuffer = false; // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); } else { // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); // get xsi:type if (xsiType != null) { XSTypeDefinition oldType = fCurrentType; fCurrentType = getAndCheckXsiType(element, xsiType, attributes); // If it fails, use the old type. Use anyType if ther is no old type. if (fCurrentType == null) { if (oldType == null) fCurrentType = SchemaGrammar.getXSAnyType(fSchemaVersion); else fCurrentType = oldType; } } fNNoneValidationDepth = fElementDepth; // if the element has a fixed value constraint, we need to append if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { fAppendBuffer = true; } // if the type is simple, we need to append else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { fAppendBuffer = true; } else { // if the type is simple content complex type, we need to append XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; fAppendBuffer = (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE); } } // Element Locally Valid (Element) // 2 Its {abstract} must be false. if (fCurrentElemDecl != null && fCurrentElemDecl.getAbstract()) reportSchemaError("cvc-elt.2", new Object[] { element.rawname }); // make the current element validation root if (fElementDepth == 0) { fValidationRoot = element.rawname; } // update normalization flags if (fNormalizeData) { // reset values fFirstChunk = true; fTrailing = false; fUnionType = false; fWhiteSpace = -1; } // Element Locally Valid (Type) // 2 Its {abstract} must be false. if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.getAbstract()) { reportSchemaError("cvc-type.2", new Object[] { element.rawname }); } if (fNormalizeData) { // find out if the content type is simple and if variety is union // to be able to do character normalization if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = ctype.fXSSimpleType.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } } } // normalization: simple type else if (fNormalizeData) { // if !union type XSSimpleType dv = (XSSimpleType) fCurrentType; if (dv.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = dv.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } // then try to get the content model fCurrentCM = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { fCurrentCM = ((XSComplexTypeDecl) fCurrentType).getContentModel(fCMBuilder); } // and get the initial content model state fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); // get information about xsi:nil String xsiNil = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NIL); // only deal with xsi:nil when there is an element declaration if (xsiNil != null && fCurrentElemDecl != null) fNil = getXsiNil(element, xsiNil); // now validate everything related with the attributes // first, get the attribute group XSAttributeGroupDecl attrGrp = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; attrGrp = ctype.getAttrGrp(); } if (fIDCChecking) { // activate identity constraints fValueStoreCache.startElement(); fMatcherStack.pushContext(); //if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0 && !fIgnoreIDC) { if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0) { fIdConstraint = true; // initialize when identity constrains are defined for the elem fValueStoreCache.initValueStoresFor(fCurrentElemDecl, this); } } processAttributes(element, attributes, attrGrp); // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // delegate to 'type alternative' validator subcomponent if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fTypeAlternativeValidator.handleStartElement(fCurrentElemDecl, attributes); } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement( element, attributes); } if (fAugPSVI) { augs = getEmptyAugs(augs); // PSVI: add validation context fCurrentPSVI.fValidationContext = fValidationRoot; // PSVI: add element declaration fCurrentPSVI.fDeclaration = fCurrentElemDecl; // PSVI: add element type fCurrentPSVI.fTypeDecl = fCurrentType; // PSVI: add notation attribute fCurrentPSVI.fNotation = fNotation; // PSVI: add nil fCurrentPSVI.fNil = fNil; } // delegate to assertions validator subcomponent if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fAssertionValidator.handleStartElement(element, attributes); } return augs; } // handleStartElement(QName,XMLAttributes,boolean)
Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) { if (DEBUG) { System.out.println("==>handleStartElement: " + element); } // root element if (fElementDepth == -1 && fValidationManager.isGrammarFound()) { if (fSchemaType == null) { // schemaType is not specified // if a DTD grammar is found, we do the same thing as Dynamic: // if a schema grammar is found, validation is performed; // otherwise, skip the whole document. fSchemaDynamicValidation = true; } else { // [1] Either schemaType is DTD, and in this case validate/schema is turned off // [2] Validating against XML Schemas only // [a] dynamic validation is false: report error if SchemaGrammar is not found // [b] dynamic validation is true: if grammar is not found ignore. } } // get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, // parse them to get the grammars. But only do this if the grammar can grow. if (!fUseGrammarPoolOnly) { String sLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); //store the location hints.. we need to do it so that we can defer the loading of grammar until //there is a reference to a component from that namespace. To provide location hints to the //application for a namespace storeLocations(sLocation, nsLocation); } // if we are in the content of "skip", then just skip this element // REVISIT: is this the correct behaviour for ID constraints? -NG if (fSkipValidationDepth >= 0) { fElementDepth++; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // if we are not skipping this element, and there is a content model, // we try to find the corresponding decl object for this element. // the reason we move this part of code here is to make sure the // error reported here (if any) is stored within the parent element's // context, instead of that of the current element. Object decl = null; if (fCurrentCM != null) { decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler, this); // it could be an element decl or a wildcard decl if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; //REVISIT: is it the only case we will have particle = null? Vector next; if (ctype.fParticle != null && (next = fCurrentCM.whatCanGoHere(fCurrCMState)).size() > 0) { String expected = expectedStr(next); final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); String elemExpandedQname = (element.uri != null) ? "{"+'"'+element.uri+'"'+":"+element.localpart+"}" : element.localpart; if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of minOccurs if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.h", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.g", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } // Check if this is a violation of maxOccurs else if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.e", new Object[] { element.rawname, expected, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of maxOccurs if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.f", new Object[] { element.rawname, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } } } // if it's not the root element, we push the current states in the stacks if (fElementDepth != -1) { ensureStackCapacity(); fSubElementStack[fElementDepth] = true; fSubElement = false; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fNotationStack[fElementDepth] = fNotation; fTypeStack[fElementDepth] = fCurrentType; fStrictAssessStack[fElementDepth] = fStrictAssess; fCMStack[fElementDepth] = fCurrentCM; fCMStateStack[fElementDepth] = fCurrCMState; fSawTextStack[fElementDepth] = fSawText; fStringContent[fElementDepth] = fSawCharacters; } // increase the element depth after we've saved // all states for the parent element fElementDepth++; fCurrentElemDecl = null; XSWildcardDecl wildcard = null; fCurrentType = null; fStrictAssess = true; fNil = false; fNotation = null; // and the buffer to hold the value of the element fBuffer.setLength(0); fSawText = false; fSawCharacters = false; // check what kind of declaration the "decl" from // oneTransition() maps to if (decl != null) { if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl) decl; } else if (decl instanceof XSOpenContentDecl) { wildcard = (XSWildcardDecl) ((XSOpenContentDecl)decl).getWildcard(); } else { wildcard = (XSWildcardDecl) decl; } } // if the wildcard is skip, then return if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) { fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } if (fElementDepth == 0) { // 1.1.1.1 An element declaration was stipulated by the processor if (fRootElementDeclaration != null) { fCurrentElemDecl = fRootElementDeclaration; checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } else if (fRootElementDeclQName != null) { processRootElementDeclQName(fRootElementDeclQName, element); } // 1.2.1.1 A type definition was stipulated by the processor else if (fRootTypeDefinition != null) { fCurrentType = fRootTypeDefinition; } else if (fRootTypeQName != null) { processRootTypeQName(fRootTypeQName); } } // if there was no processor stipulated type if (fCurrentType == null) { // try again to get the element decl: // case 1: find declaration for root element // case 2: find declaration for element from another namespace if (fCurrentElemDecl == null) { // try to find schema grammar by different means.. SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, attributes); if (sGrammar != null) { fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } } if (fCurrentElemDecl != null) { // then get the type fCurrentType = fCurrentElemDecl.fType; } } //process type alternatives if (fTypeAlternativesChecking && fCurrentElemDecl != null) { XSTypeDefinition currentType = fTypeAlternativeValidator.getCurrentType(fCurrentElemDecl, element, attributes); if (currentType != null) { fCurrentType = currentType; } } // check if we should be ignoring xsi:type on this element if (fElementDepth == fIgnoreXSITypeDepth && fCurrentElemDecl == null) { fIgnoreXSITypeDepth++; } // process xsi:type attribute information String xsiType = null; if (fElementDepth >= fIgnoreXSITypeDepth) { xsiType = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_TYPE); } // if no decl/type found for the current element if (fCurrentType == null && xsiType == null) { // if this is the validation root, report an error, because // we can't find eith decl or type for this element // REVISIT: should we report error, or warning? if (fElementDepth == 0) { // for dynamic validation, skip the whole content, // because no grammar was found. if (fDynamicValidation || fSchemaDynamicValidation) { // no schema grammar was found, but it's either dynamic // validation, or another kind of grammar was found (DTD, // for example). The intended behavior here is to skip // the whole document. To improve performance, we try to // remove the validator from the pipeline, since it's not // supposed to do anything. if (fDocumentSource != null) { fDocumentSource.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) fDocumentHandler.setDocumentSource(fDocumentSource); // indicate that the validator was removed. fElementDepth = -2; return augs; } fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // We don't call reportSchemaError here, because the spec // doesn't think it's invalid not to be able to find a // declaration or type definition for an element. Xerces is // reporting it as an error for historical reasons, but in // PSVI, we shouldn't mark this element as invalid because // of this. - SG fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "cvc-elt.1.a", new Object[] { element.rawname }, XMLErrorReporter.SEVERITY_ERROR); } // if wildcard = strict, report error. // needs to be called before fXSIErrorReporter.pushContext() // so that the error belongs to the parent element. else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { // report error, because wilcard = strict reportSchemaError("cvc-complex-type.2.4.c", new Object[] { element.rawname }); } // no element decl or type found for this element. // Allowed by the spec, we can choose to either laxly assess this // element, or to skip it. Now we choose lax assessment. fCurrentType = SchemaGrammar.getXSAnyType(fSchemaVersion); fStrictAssess = false; fNFullValidationDepth = fElementDepth; // any type has mixed content, so we don't need to append buffer fAppendBuffer = false; // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); } else { // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); // get xsi:type if (xsiType != null) { XSTypeDefinition oldType = fCurrentType; fCurrentType = getAndCheckXsiType(element, xsiType, attributes); // If it fails, use the old type. Use anyType if ther is no old type. if (fCurrentType == null) { if (oldType == null) fCurrentType = SchemaGrammar.getXSAnyType(fSchemaVersion); else fCurrentType = oldType; } } fNNoneValidationDepth = fElementDepth; // if the element has a fixed value constraint, we need to append if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { fAppendBuffer = true; } // if the type is simple, we need to append else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { fAppendBuffer = true; } else { // if the type is simple content complex type, we need to append XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; fAppendBuffer = (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE); } } // Element Locally Valid (Element) // 2 Its {abstract} must be false. if (fCurrentElemDecl != null && fCurrentElemDecl.getAbstract()) reportSchemaError("cvc-elt.2", new Object[] { element.rawname }); // make the current element validation root if (fElementDepth == 0) { fValidationRoot = element.rawname; } // update normalization flags if (fNormalizeData) { // reset values fFirstChunk = true; fTrailing = false; fUnionType = false; fWhiteSpace = -1; } // Element Locally Valid (Type) // 2 Its {abstract} must be false. if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.getAbstract()) { reportSchemaError("cvc-type.2", new Object[] { element.rawname }); } if (fNormalizeData) { // find out if the content type is simple and if variety is union // to be able to do character normalization if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = ctype.fXSSimpleType.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } } } // normalization: simple type else if (fNormalizeData) { // if !union type XSSimpleType dv = (XSSimpleType) fCurrentType; if (dv.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = dv.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } // then try to get the content model fCurrentCM = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { fCurrentCM = ((XSComplexTypeDecl) fCurrentType).getContentModel(fCMBuilder); } // and get the initial content model state fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); // get information about xsi:nil String xsiNil = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NIL); // only deal with xsi:nil when there is an element declaration if (xsiNil != null && fCurrentElemDecl != null) fNil = getXsiNil(element, xsiNil); // now validate everything related with the attributes // first, get the attribute group XSAttributeGroupDecl attrGrp = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; attrGrp = ctype.getAttrGrp(); } if (fIDCChecking) { // activate identity constraints fValueStoreCache.startElement(); fMatcherStack.pushContext(); //if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0 && !fIgnoreIDC) { if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0) { fIdConstraint = true; // initialize when identity constrains are defined for the elem fValueStoreCache.initValueStoresFor(fCurrentElemDecl, this); } } processAttributes(element, attributes, attrGrp); // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // delegate to 'type alternative' validator subcomponent if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fTypeAlternativeValidator.handleStartElement(fCurrentElemDecl, attributes); } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement( element, attributes); } if (fAugPSVI) { augs = getEmptyAugs(augs); // PSVI: add validation context fCurrentPSVI.fValidationContext = fValidationRoot; // PSVI: add element declaration fCurrentPSVI.fDeclaration = fCurrentElemDecl; // PSVI: add element type fCurrentPSVI.fTypeDecl = fCurrentType; // PSVI: add notation attribute fCurrentPSVI.fNotation = fNotation; // PSVI: add nil fCurrentPSVI.fNil = fNil; } // delegate to assertions validator subcomponent if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { fAssertionValidator.handleStartElement(element, attributes); } return augs; } // handleStartElement(QName,XMLAttributes,boolean)
diff --git a/src/annahack/utils/DiceSet.java b/src/annahack/utils/DiceSet.java index 6e59c89..13c6060 100644 --- a/src/annahack/utils/DiceSet.java +++ b/src/annahack/utils/DiceSet.java @@ -1,125 +1,125 @@ package annahack.utils; import java.util.ArrayList; public class DiceSet { private double average, stdDev; private int min, max; private ArrayList<Dice> dice=new ArrayList<Dice>(); /** * Constructs and calculates DiceSet * @param takes a string in the form of "2d6+8d12+4 (constant must be at end)" * @throws BadDiceException */ public DiceSet(String d) throws BadDiceException { String[] a=d.split("\\+"); min=0; max=0; int add=0; if(!a[a.length-1].contains("d")) { add=Integer.parseInt(a[a.length-1]); min+=add; max+=add; String[] temp=new String[a.length-1]; for(int i=0; i<a.length-1; i++) { temp[i]=a[i]; } a=temp; } int rolls=1; for(int i=0; i<a.length; i++) { dice.add(new Dice(a[i])); } for(int i=0; i<dice.size(); i++) { for(int k=0; k<dice.get(i).getNum(); k++) { min+=1; max+=dice.get(i).getMax(); rolls*=dice.get(i).getMax(); } } int[] bins = new int[max+1]; //It will be easier this way, I swear bins[add] = 1; //Begin Dirty Hack (a la Chris) for(int i=0; i<dice.size(); i++) { for(int j=0; j<dice.get(i).getNum(); j++) { int[] temp = new int[max+1]; for(int k=1; k<=dice.get(i).getMax(); k++) { for(int aa = 0; aa < max+1-k;aa++) { temp[aa+k] += bins[aa]; } } bins = temp; } } //End Dirty Hack int sum=0; for(int i=0; i<bins.length; i++) { sum+=bins[i]*i; } average=(double)sum/rolls; //It's Standard Deviation time double dsum=0.0; for(int i=0; i<bins.length; i++) { dsum+=(Math.pow(i-average,2)*bins[i]); } - stdDev=Math.sqrt(dsum/(rolls-1)); + stdDev=Math.sqrt(dsum/(rolls)); } /** * * @return minimum possible roll */ public int getMin() { return min; } /** * * @return maximum possible roll */ public int getMax() { return max; } /** * * @return average roll */ public double getAverage() { return average; } /** * * @return standard deviation */ public double getStdDev() { return stdDev; } }
true
true
public DiceSet(String d) throws BadDiceException { String[] a=d.split("\\+"); min=0; max=0; int add=0; if(!a[a.length-1].contains("d")) { add=Integer.parseInt(a[a.length-1]); min+=add; max+=add; String[] temp=new String[a.length-1]; for(int i=0; i<a.length-1; i++) { temp[i]=a[i]; } a=temp; } int rolls=1; for(int i=0; i<a.length; i++) { dice.add(new Dice(a[i])); } for(int i=0; i<dice.size(); i++) { for(int k=0; k<dice.get(i).getNum(); k++) { min+=1; max+=dice.get(i).getMax(); rolls*=dice.get(i).getMax(); } } int[] bins = new int[max+1]; //It will be easier this way, I swear bins[add] = 1; //Begin Dirty Hack (a la Chris) for(int i=0; i<dice.size(); i++) { for(int j=0; j<dice.get(i).getNum(); j++) { int[] temp = new int[max+1]; for(int k=1; k<=dice.get(i).getMax(); k++) { for(int aa = 0; aa < max+1-k;aa++) { temp[aa+k] += bins[aa]; } } bins = temp; } } //End Dirty Hack int sum=0; for(int i=0; i<bins.length; i++) { sum+=bins[i]*i; } average=(double)sum/rolls; //It's Standard Deviation time double dsum=0.0; for(int i=0; i<bins.length; i++) { dsum+=(Math.pow(i-average,2)*bins[i]); } stdDev=Math.sqrt(dsum/(rolls-1)); }
public DiceSet(String d) throws BadDiceException { String[] a=d.split("\\+"); min=0; max=0; int add=0; if(!a[a.length-1].contains("d")) { add=Integer.parseInt(a[a.length-1]); min+=add; max+=add; String[] temp=new String[a.length-1]; for(int i=0; i<a.length-1; i++) { temp[i]=a[i]; } a=temp; } int rolls=1; for(int i=0; i<a.length; i++) { dice.add(new Dice(a[i])); } for(int i=0; i<dice.size(); i++) { for(int k=0; k<dice.get(i).getNum(); k++) { min+=1; max+=dice.get(i).getMax(); rolls*=dice.get(i).getMax(); } } int[] bins = new int[max+1]; //It will be easier this way, I swear bins[add] = 1; //Begin Dirty Hack (a la Chris) for(int i=0; i<dice.size(); i++) { for(int j=0; j<dice.get(i).getNum(); j++) { int[] temp = new int[max+1]; for(int k=1; k<=dice.get(i).getMax(); k++) { for(int aa = 0; aa < max+1-k;aa++) { temp[aa+k] += bins[aa]; } } bins = temp; } } //End Dirty Hack int sum=0; for(int i=0; i<bins.length; i++) { sum+=bins[i]*i; } average=(double)sum/rolls; //It's Standard Deviation time double dsum=0.0; for(int i=0; i<bins.length; i++) { dsum+=(Math.pow(i-average,2)*bins[i]); } stdDev=Math.sqrt(dsum/(rolls)); }
diff --git a/src/com/evervoid/network/EverMessageHandler.java b/src/com/evervoid/network/EverMessageHandler.java index b4f6d32..998e3b3 100644 --- a/src/com/evervoid/network/EverMessageHandler.java +++ b/src/com/evervoid/network/EverMessageHandler.java @@ -1,227 +1,233 @@ package com.evervoid.network; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.evervoid.server.EverMessageSendingException; import com.jme3.network.connection.Client; import com.jme3.network.connection.Server; import com.jme3.network.events.MessageAdapter; import com.jme3.network.message.Message; import com.jme3.network.serializing.Serializer; /** * Handles deconstruction and reconstruction of EverMessages. */ public class EverMessageHandler extends MessageAdapter { private class Postman extends Thread { private final Client aDestination; private final EverMessage aMessage; private Postman(final Client destination, final EverMessage message) { aDestination = destination; aMessage = message; } @Override public void run() { try { send(); } catch (final EverMessageSendingException e) { // Do nothing, can't notify back anymore at this point } } private boolean send() throws EverMessageSendingException { final List<PartialMessage> messages = aMessage.getMessages(); int partIndex = 1; final int parts = messages.size(); for (final PartialMessage part : messages) { try { sPartialMessageLogger.info(getSide() + "EverMessageHandler sending to " + aDestination + ", part " + partIndex + "/" + parts); aDestination.send(part); + if (partIndex != parts) { // If it's not the last message + Thread.sleep(100); // Wait a bit + } } catch (final IOException e) { throw new EverMessageSendingException(aDestination); } catch (final NullPointerException e) { // Happens when inner client (inside the jME classes) doesn't get removed properly. throw new EverMessageSendingException(aDestination); } + catch (final InterruptedException e) { + // Not going to happen + } partIndex++; } return true; } } private static final Logger sPartialMessageLogger = Logger.getLogger(EverMessageHandler.class.getName()); private Client aClient = null; private final boolean aClientSide; private final Set<EverMessageListener> aListeners = new HashSet<EverMessageListener>(); private final Map<String, EverMessageBuilder> aMessages = new HashMap<String, EverMessageBuilder>(); public EverMessageHandler(final Client client) { sPartialMessageLogger.setLevel(Level.ALL); aClientSide = true; aClient = client; sPartialMessageLogger.info(getSide() + "EverMessageHandler initializing"); Serializer.registerClass(ByteMessage.class); Serializer.registerClass(PartialMessage.class); client.addMessageListener(this, PartialMessage.class); } public EverMessageHandler(final Server server) { sPartialMessageLogger.setLevel(Level.ALL); aClientSide = false; sPartialMessageLogger.info(getSide() + "EverMessageHandler initializing"); Serializer.registerClass(ByteMessage.class); Serializer.registerClass(PartialMessage.class); server.addMessageListener(this, PartialMessage.class); } public void addMessageListener(final EverMessageListener listener) { aListeners.add(listener); sPartialMessageLogger.info(getSide() + "EverMessageHandler has a new EverMessageListener: " + listener); } private void deleteBuilder(final PartialMessage message) { aMessages.remove(message.getHash()); } /** * @param message * The message to get a builder for * @return The builder associated with the given message */ private EverMessageBuilder getBuilder(final PartialMessage message) { final String hash = message.getHash(); if (!aMessages.containsKey(hash)) { final EverMessageBuilder builder = new EverMessageBuilder(message.getType(), message.getTotalParts()); aMessages.put(hash, builder); return builder; } return aMessages.get(hash); } /** * Just there to help logging * * @return "Client-side" or "Server-side" */ private String getSide() { if (aClientSide) { return "Client-side "; } return "Server-side "; } @Override public void messageReceived(final Message message) { final PartialMessage msg = (PartialMessage) message; sPartialMessageLogger.info(getSide() + "EverMessageHandler received a new PartialMessage from " + message.getClient() + ": " + msg); final EverMessageBuilder builder = getBuilder(msg); builder.addPart(msg); final EverMessage finalMsg = builder.getMessage(); if (finalMsg == null) { sPartialMessageLogger.info("PartialMessage is not enough to complete the full EverMessage."); return; } sPartialMessageLogger.info("PartialMessage is enough to complete the full EverMessage from " + message.getClient() + ": " + finalMsg); deleteBuilder(msg); for (final EverMessageListener listener : aListeners) { listener.messageReceived(finalMsg); } } /** * (Server-side) Split and send an EverMessage to a Client * * @param destination * The client to send to * @param message * The EverMessage to send * @return True on success, false on failure * @throws EverMessageSendingException * When message sending fails */ public boolean send(final Client destination, final EverMessage message) throws EverMessageSendingException { return send(destination, message, false); } /** * (Server-side) Split and send an EverMessage to a Client * * @param destination * The client to send to * @param message * The EverMessage to send * @param async * Whether to send asynchronously or not. If true, exceptions will not be thrown. * @return True on success or when asynchronous, false on failure * @throws EverMessageSendingException * When message sending fails */ public boolean send(final Client destination, final EverMessage message, final boolean async) throws EverMessageSendingException { final Postman postman = new Postman(destination, message); if (async) { postman.start(); return true; } return postman.send(); } /** * (Client-side) Split and send an EverMessage to the server * * @param message * The message to send * @return True on success, false on failure * @throws EverMessageSendingException * When message fails to deliver */ public boolean send(final EverMessage message) throws EverMessageSendingException { return send(message, false); } /** * (Client-side) Split and send an EverMessage to the server * * @param message * The message to send * @param async * Whether to send asynchronously or not. If true, exceptions will not be thrown. * @return True on success, false on failure * @throws EverMessageSendingException * When message fails to deliver */ public boolean send(final EverMessage message, final boolean async) throws EverMessageSendingException { return send(aClient, message, async); } }
false
true
private boolean send() throws EverMessageSendingException { final List<PartialMessage> messages = aMessage.getMessages(); int partIndex = 1; final int parts = messages.size(); for (final PartialMessage part : messages) { try { sPartialMessageLogger.info(getSide() + "EverMessageHandler sending to " + aDestination + ", part " + partIndex + "/" + parts); aDestination.send(part); } catch (final IOException e) { throw new EverMessageSendingException(aDestination); } catch (final NullPointerException e) { // Happens when inner client (inside the jME classes) doesn't get removed properly. throw new EverMessageSendingException(aDestination); } partIndex++; } return true; }
private boolean send() throws EverMessageSendingException { final List<PartialMessage> messages = aMessage.getMessages(); int partIndex = 1; final int parts = messages.size(); for (final PartialMessage part : messages) { try { sPartialMessageLogger.info(getSide() + "EverMessageHandler sending to " + aDestination + ", part " + partIndex + "/" + parts); aDestination.send(part); if (partIndex != parts) { // If it's not the last message Thread.sleep(100); // Wait a bit } } catch (final IOException e) { throw new EverMessageSendingException(aDestination); } catch (final NullPointerException e) { // Happens when inner client (inside the jME classes) doesn't get removed properly. throw new EverMessageSendingException(aDestination); } catch (final InterruptedException e) { // Not going to happen } partIndex++; } return true; }
diff --git a/spring-integration-core/src/test/java/org/springframework/integration/bus/FixedDelayConsumerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/bus/FixedDelayConsumerTests.java index dd61bf74fc..74f1204bc5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/bus/FixedDelayConsumerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/bus/FixedDelayConsumerTests.java @@ -1,108 +1,108 @@ /* * Copyright 2002-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.bus; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import org.springframework.integration.channel.PointToPointChannel; import org.springframework.integration.endpoint.GenericMessageEndpoint; import org.springframework.integration.endpoint.MessageEndpoint; import org.springframework.integration.message.Message; import org.springframework.integration.message.GenericMessage; /** * @author Mark Fisher */ public class FixedDelayConsumerTests { @Test public void testAllSentMessagesAreReceivedWithinTimeLimit() throws Exception { int messagesToSend = 20; final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(messagesToSend); PointToPointChannel channel = new PointToPointChannel(); MessageEndpoint endpoint = new GenericMessageEndpoint() { public void messageReceived(Message message) { counter.incrementAndGet(); latch.countDown(); } }; MessageBus bus = new MessageBus(); bus.registerChannel("testChannel", channel); bus.registerEndpoint("testEndpoint", endpoint); ConsumerPolicy policy = new ConsumerPolicy(); policy.setConcurrency(1); policy.setMaxConcurrency(1); policy.setMaxMessagesPerTask(1); policy.setFixedRate(true); policy.setPeriod(10); Subscription subscription = new Subscription(); subscription.setChannel("testChannel"); subscription.setEndpoint("testEndpoint"); subscription.setPolicy(policy); bus.activateSubscription(subscription); bus.start(); for (int i = 0; i < messagesToSend; i++) { channel.send(new GenericMessage<String>(1, "test " + (i+1))); } latch.await(500, TimeUnit.MILLISECONDS); assertEquals(messagesToSend, counter.get()); } @Test public void testTimedOutMessagesAreNotReceived() throws Exception { int messagesToSend = 20; final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(messagesToSend); PointToPointChannel channel = new PointToPointChannel(); MessageEndpoint endpoint = new GenericMessageEndpoint() { public void messageReceived(Message message) { counter.incrementAndGet(); latch.countDown(); } }; MessageBus bus = new MessageBus(); bus.registerChannel("testChannel", channel); bus.registerEndpoint("testEndpoint", endpoint); ConsumerPolicy policy = new ConsumerPolicy(); policy.setConcurrency(1); policy.setMaxConcurrency(1); policy.setMaxMessagesPerTask(1); policy.setFixedRate(true); policy.setPeriod(10); Subscription subscription = new Subscription(); subscription.setChannel("testChannel"); subscription.setEndpoint("testEndpoint"); subscription.setPolicy(policy); bus.activateSubscription(subscription); bus.start(); for (int i = 0; i < messagesToSend; i++) { channel.send(new GenericMessage<String>(1, "test " + (i+1))); } latch.await(80, TimeUnit.MILLISECONDS); - System.out.println("count: " + counter.get()); - assertTrue(counter.get() < 10); - assertTrue(counter.get() > 7); + int count = counter.get(); + assertTrue("received " + count + ", expected less than 10", counter.get() < 10); + assertTrue("received " + count + ", expected more than 7", counter.get() > 7); } }
true
true
public void testTimedOutMessagesAreNotReceived() throws Exception { int messagesToSend = 20; final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(messagesToSend); PointToPointChannel channel = new PointToPointChannel(); MessageEndpoint endpoint = new GenericMessageEndpoint() { public void messageReceived(Message message) { counter.incrementAndGet(); latch.countDown(); } }; MessageBus bus = new MessageBus(); bus.registerChannel("testChannel", channel); bus.registerEndpoint("testEndpoint", endpoint); ConsumerPolicy policy = new ConsumerPolicy(); policy.setConcurrency(1); policy.setMaxConcurrency(1); policy.setMaxMessagesPerTask(1); policy.setFixedRate(true); policy.setPeriod(10); Subscription subscription = new Subscription(); subscription.setChannel("testChannel"); subscription.setEndpoint("testEndpoint"); subscription.setPolicy(policy); bus.activateSubscription(subscription); bus.start(); for (int i = 0; i < messagesToSend; i++) { channel.send(new GenericMessage<String>(1, "test " + (i+1))); } latch.await(80, TimeUnit.MILLISECONDS); System.out.println("count: " + counter.get()); assertTrue(counter.get() < 10); assertTrue(counter.get() > 7); }
public void testTimedOutMessagesAreNotReceived() throws Exception { int messagesToSend = 20; final AtomicInteger counter = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(messagesToSend); PointToPointChannel channel = new PointToPointChannel(); MessageEndpoint endpoint = new GenericMessageEndpoint() { public void messageReceived(Message message) { counter.incrementAndGet(); latch.countDown(); } }; MessageBus bus = new MessageBus(); bus.registerChannel("testChannel", channel); bus.registerEndpoint("testEndpoint", endpoint); ConsumerPolicy policy = new ConsumerPolicy(); policy.setConcurrency(1); policy.setMaxConcurrency(1); policy.setMaxMessagesPerTask(1); policy.setFixedRate(true); policy.setPeriod(10); Subscription subscription = new Subscription(); subscription.setChannel("testChannel"); subscription.setEndpoint("testEndpoint"); subscription.setPolicy(policy); bus.activateSubscription(subscription); bus.start(); for (int i = 0; i < messagesToSend; i++) { channel.send(new GenericMessage<String>(1, "test " + (i+1))); } latch.await(80, TimeUnit.MILLISECONDS); int count = counter.get(); assertTrue("received " + count + ", expected less than 10", counter.get() < 10); assertTrue("received " + count + ", expected more than 7", counter.get() > 7); }
diff --git a/web-core/src/test/java/com/silverpeas/profile/web/UserProfileTestResources.java b/web-core/src/test/java/com/silverpeas/profile/web/UserProfileTestResources.java index 6f8a00428d..cc2bf598ac 100644 --- a/web-core/src/test/java/com/silverpeas/profile/web/UserProfileTestResources.java +++ b/web-core/src/test/java/com/silverpeas/profile/web/UserProfileTestResources.java @@ -1,442 +1,442 @@ /* * Copyright (C) 2000 - 2012 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection withWriter Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.profile.web; import com.silverpeas.profile.web.mock.RelationShipServiceMock; import com.silverpeas.socialnetwork.relationShip.RelationShip; import com.silverpeas.socialnetwork.relationShip.RelationShipService; import com.silverpeas.web.TestResources; import com.stratelia.webactiv.beans.admin.*; import java.sql.SQLException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Named; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import static org.mockito.Matchers.*; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; /** * The resources to use in the test on the UserProfileResource REST service. Theses objects manage * in a single place all the resources required to perform correctly unit tests on the * UserProfileResource published operations. */ @Named(TestResources.TEST_RESOURCES_NAME) public class UserProfileTestResources extends TestResources { public static final String JAVA_PACKAGE = "com.silverpeas.profile.web"; public static final String SPRING_CONTEXT = "spring-profile-webservice.xml"; public static final String USER_PROFILE_PATH = "/profile/users"; public static final String GROUP_PROFILE_PATH = "/profile/groups"; @Inject private RelationShipServiceMock relationShipServiceMock; private Set<String> domainIds = new HashSet<String>(); /** * Allocates the resources required by the unit tests. */ @PostConstruct public void allocate() { prepareSeveralUsers(); prepareSeveralGroups(); putUsersInGroups(); } public UserDetail[] getAllExistingUsers() { UserDetail[] users = getOrganizationControllerMock().getAllUsers(); if (users == null) { users = new UserDetail[0]; } return users; } @Deprecated public void whenSearchGroupsThenReturn(final Group[] groups) { OrganizationController mock = getOrganizationControllerMock(); String[] groupIds = getGroupIds(groups); when(mock.searchGroupsIds(anyBoolean(), anyString(), any(String[].class), any(Group.class))). thenReturn(groupIds); doAnswer(new Answer<Group[]>() { @Override public Group[] answer(InvocationOnMock invocation) throws Throwable { Group[] emptyGroup = new Group[0]; String[] passedGroupIds = (String[]) invocation.getArguments()[0]; String[] groupIds = getGroupIds(groups); if (passedGroupIds.length == groupIds.length) { if (Arrays.asList(passedGroupIds).containsAll(Arrays.asList(groupIds))) { return groups; } } return emptyGroup; } }).when(mock).getGroups(any(String[].class)); } public void whenSearchGroupsByCriteriaThenReturn(final Group[] groups) { OrganizationController mock = getOrganizationControllerMock(); doAnswer(new Answer<Group[]>() { @Override public Group[] answer(InvocationOnMock invocation) throws Throwable { return groups; } }).when(mock).searchGroups(any(GroupsSearchCriteria.class)); } public void whenSearchUsersByCriteriaThenReturn(final UserDetailsSearchCriteria criteria, final UserDetail[] users) { OrganizationController mock = getOrganizationControllerMock(); doAnswer(new Answer<UserDetail[]>() { @Override public UserDetail[] answer(InvocationOnMock invocation) throws Throwable { UserDetail[] emptyUsers = new UserDetail[0]; UserDetailsSearchCriteria passedCriteria = (UserDetailsSearchCriteria) invocation.getArguments()[0]; if (criteria.isCriterionOnComponentInstanceIdSet() && passedCriteria. isCriterionOnComponentInstanceIdSet()) { if (!criteria.getCriterionOnComponentInstanceId().equals(passedCriteria. getCriterionOnComponentInstanceId())) { return emptyUsers; } } else if ((!criteria.isCriterionOnComponentInstanceIdSet() && passedCriteria. isCriterionOnComponentInstanceIdSet()) || (criteria. isCriterionOnComponentInstanceIdSet() && !passedCriteria. isCriterionOnComponentInstanceIdSet())) { return emptyUsers; } if (criteria.isCriterionOnDomainIdSet() && passedCriteria.isCriterionOnDomainIdSet()) { if (!criteria.getCriterionOnDomainId().equals(passedCriteria.getCriterionOnDomainId())) { return emptyUsers; } } else if ((!criteria.isCriterionOnDomainIdSet() && passedCriteria.isCriterionOnDomainIdSet()) || (criteria.isCriterionOnDomainIdSet() && !passedCriteria.isCriterionOnDomainIdSet())) { return emptyUsers; } if (criteria.isCriterionOnGroupIdsSet() && passedCriteria.isCriterionOnGroupIdsSet()) { if (!Arrays.equals(criteria.getCriterionOnGroupIds(), passedCriteria.getCriterionOnGroupIds())) { return emptyUsers; } } else if ((!criteria.isCriterionOnGroupIdsSet() && passedCriteria.isCriterionOnGroupIdsSet()) || (criteria.isCriterionOnGroupIdsSet() && !passedCriteria.isCriterionOnGroupIdsSet())) { return emptyUsers; } if (criteria.isCriterionOnNameSet() && passedCriteria.isCriterionOnNameSet()) { if (!criteria.getCriterionOnName().equals(passedCriteria.getCriterionOnName())) { return emptyUsers; } } else if ((!criteria.isCriterionOnNameSet() && passedCriteria.isCriterionOnNameSet()) || (criteria.isCriterionOnNameSet() && !passedCriteria.isCriterionOnNameSet())) { return emptyUsers; } - if (criteria.isCriterionOnRoleIdsSet() && passedCriteria.isCriterionOnRoleIdsSet()) { - List<String> roles = Arrays.asList(criteria.getCriterionOnRoleIds()); - List<String> passedRoles = Arrays.asList(passedCriteria.getCriterionOnRoleIds()); + if (criteria.isCriterionOnRoleNamesSet() && passedCriteria.isCriterionOnRoleNamesSet()) { + List<String> roles = Arrays.asList(criteria.getCriterionOnRoleNames()); + List<String> passedRoles = Arrays.asList(passedCriteria.getCriterionOnRoleNames()); if (roles.size() != passedRoles.size() || !roles.containsAll(passedRoles)) { return emptyUsers; } - } else if ((!criteria.isCriterionOnRoleIdsSet() - && passedCriteria.isCriterionOnRoleIdsSet()) || (criteria.isCriterionOnRoleIdsSet() - && !passedCriteria.isCriterionOnRoleIdsSet())) { + } else if ((!criteria.isCriterionOnRoleNamesSet() + && passedCriteria.isCriterionOnRoleNamesSet()) || (criteria.isCriterionOnRoleNamesSet() + && !passedCriteria.isCriterionOnRoleNamesSet())) { return emptyUsers; } if (criteria.isCriterionOnUserIdsSet() && passedCriteria.isCriterionOnUserIdsSet()) { List<String> userIds = Arrays.asList(criteria.getCriterionOnUserIds()); List<String> passedUserIds = Arrays.asList(passedCriteria.getCriterionOnUserIds()); if (userIds.size() != passedUserIds.size() || !userIds.containsAll(passedUserIds)) { return emptyUsers; } } else if ((!criteria.isCriterionOnUserIdsSet() && passedCriteria.isCriterionOnUserIdsSet()) || (criteria.isCriterionOnUserIdsSet() && !passedCriteria.isCriterionOnUserIdsSet())) { return emptyUsers; } return users; } }).when(mock).searchUsers(any(UserDetailsSearchCriteria.class)); } public UserDetail[] getAllExistingUsersInDomain(String domainId) { List<UserDetail> usersInDomain = new ArrayList<UserDetail>(); UserDetail[] existingUsers = getAllExistingUsers(); for (UserDetail aUser : existingUsers) { if (aUser.getDomainId().equals(domainId)) { usersInDomain.add(aUser); } } return usersInDomain.toArray(new UserDetail[usersInDomain.size()]); } public Group[] getAllExistingRootGroups() { Group[] groups = getOrganizationControllerMock().getAllRootGroups(); if (groups == null) { groups = new Group[0]; } return groups; } public Group[] getAllExistingRootGroupsInDomain(String domainId) { List<Group> rootGroupsInDomain = new ArrayList<Group>(); Group[] existingGroups = getAllExistingRootGroups(); for (Group aGroup : existingGroups) { if (aGroup.getDomainId().equals(domainId)) { rootGroupsInDomain.add(aGroup); } } return rootGroupsInDomain.toArray(new Group[rootGroupsInDomain.size()]); } public Group[] getAllRootGroupsAccessibleFromDomain(String domainId) { List<Group> groups = new ArrayList<Group>(); groups.addAll(Arrays.asList(getAllExistingRootGroupsInDomain(domainId))); groups.addAll(Arrays.asList(getAllExistingRootGroupsInDomain("-1"))); return groups.toArray(new Group[groups.size()]); } public Group getGroupById(String groupId) { return getOrganizationControllerMock().getGroup(groupId); } public List<String> getAllDomainIds() { return new ArrayList<String>(domainIds); } public List<String> getAllDomainIdsExceptedSilverpeasOne() { List<String> otherDomainIds = new ArrayList<String>(domainIds.size() - 1); for (String aDomainId : domainIds) { if (!aDomainId.equals("0")) { otherDomainIds.add(aDomainId); } } return otherDomainIds; } /** * Gets randomly an existing user detail among the available resources for tests. * * @return a user detail. */ public UserDetail anExistingUser() { UserDetail[] allUsers = getOrganizationControllerMock().getAllUsers(); return allUsers[new Random().nextInt(allUsers.length)]; } public UserDetail anExistingUserNotInSilverpeasDomain() { UserDetail user; do { user = anExistingUser(); } while ("0".equals(user.getDomainId())); return user; } /** * Gets randomly an existing group among the available resources for tests. * * @return a group. */ public Group anExistingGroup() { Group[] allGroups = getOrganizationControllerMock().getAllGroups(); return allGroups[new Random().nextInt(allGroups.length)]; } public Group anExistingRootGroup() { Group group = null; do { group = anExistingGroup(); } while (!group.isRoot()); return group; } /** * Gets a group that isn't in an internal domain. * * @return a group in a domain other than internal one. */ public Group getAGroupNotInAnInternalDomain() { Group group = anExistingGroup(); while (group.getDomainId().equals("-1")) { group = anExistingGroup(); } return group; } public UserDetail[] getRelationShipsOfUser(String userId) { UserDetail[] users = getAllExistingUsers(); UserDetail[] contacts = new UserDetail[users.length - 1]; List<RelationShip> relationships = new ArrayList<RelationShip>(users.length - 1); int currentUserId = Integer.valueOf(userId); int i = 0; for (UserDetail aUser : users) { if (!aUser.getId().equals(userId)) { contacts[i++] = aUser; relationships.add(new RelationShip(Integer.valueOf(aUser.getId()), currentUserId, 1, new Date(), currentUserId)); } } RelationShipService mock = relationShipServiceMock.getMockedRelationShipService(); try { when(mock.getAllMyRelationShips(currentUserId)).thenReturn(relationships); } catch (SQLException ex) { Logger.getLogger(UserProfileTestResources.class.getName()).log(Level.SEVERE, null, ex); } return contacts; } @Override public UserDetail registerUser(UserDetail user) { UserDetail[] existingUsers = getAllExistingUsers(); UserDetail[] actualUsers = Arrays.copyOf(existingUsers, existingUsers.length + 1); actualUsers[actualUsers.length - 1] = user; OrganizationController mock = getOrganizationControllerMock(); when(mock.getAllUsers()).thenReturn(actualUsers); return super.registerUser(user); } private void prepareSeveralUsers() { for (int i = 0; i < 5; i++) { String suffix = String.valueOf(10 + i); String domainId = (i == 0 ? "0" : (i < 3 ? "1" : "2")); domainIds.add(domainId); registerUser(aUser("Toto" + suffix, "Foo" + suffix, suffix, domainId)); } } private UserDetail aUser(String firstName, String lastName, String id, String domainId) { UserDetail user = new UserDetail(); user.setFirstName(firstName); user.setLastName(lastName); user.setId(id); user.setDomainId(domainId); return user; } private void prepareSeveralGroups() { registerSomeGroups(aGroup("Groupe 1", "1", null, "-1"), aGroup("Groupe 2", "2", null, "-1"), aGroup("Groupe 3", "3", null, "0"), aGroup("Groupe 4 - 3", "4", "3", "0"), aGroup("Groupe 5 - 4", "5", "4", "0"), aGroup("Groupe 6", "6", null, "1"), aGroup("Groupe 7 - 6", "7", "6", "1"), aGroup("Groupe 8 - 6", "8", "6", "1"), aGroup("Groupe 9 - 7", "9", "7", "1")); } private void putUsersInGroups() { OrganizationController mock = getOrganizationControllerMock(); Group[] groups = mock.getAllGroups(); for (Group group : groups) { when(mock.getAllUsersOfGroup(group.getId())).thenReturn(new UserDetail[0]); group.setTotalNbUsers(1); } Group internalGroup = mock.getGroup("1"); UserDetail[] users = getAllExistingUsers(); internalGroup.setUserIds(getUserIds(users)); internalGroup.setTotalNbUsers(users.length); for (int i = 0; i <= 1; i++) { String domainId = String.valueOf(i); users = getAllExistingUsersInDomain(domainId); if (users != null) { groups = getAllExistingRootGroupsInDomain(domainId); groups[0].setUserIds(getUserIds(users)); when(mock.getAllUsersOfGroup(groups[0].getId())).thenReturn(users); for (int j = 1; j < groups.length; j++) { when(mock.getAllUsersOfGroup(groups[j].getId())).thenReturn(new UserDetail[0]); } } } } private void registerSomeGroups(final Group... someGroups) { OrganizationController mock = getOrganizationControllerMock(); List<Group> rootGroups = new ArrayList<Group>(); for (int i = 0; i < someGroups.length; i++) { when(mock.getGroup(someGroups[i].getId())).thenReturn(someGroups[i]); if (someGroups[i].isRoot()) { rootGroups.add(someGroups[i]); } Domain domain = mock.getDomain(someGroups[i].getDomainId()); if (domain == null) { domain = new Domain(); domain.setId(someGroups[i].getDomainId()); domain.setName("Domaine " + someGroups[i].getDomainId()); when(mock.getDomain(someGroups[i].getDomainId())).thenReturn(domain); } } when(mock.getAllRootGroups()).thenReturn(rootGroups.toArray(new Group[rootGroups.size()])); when(mock.getAllGroups()).thenReturn(someGroups); for (Group group : someGroups) { if (!group.isRoot()) { Group[] subgroups = mock.getAllSubGroups(group.getSuperGroupId()); if (subgroups == null) { subgroups = new Group[1]; } else { subgroups = Arrays.copyOf(subgroups, subgroups.length + 1); } subgroups[subgroups.length - 1] = group; when(mock.getAllSubGroups(group.getSuperGroupId())).thenReturn(subgroups); } Group[] subgroups = mock.getAllSubGroups(group.getId()); if (subgroups == null) { when(mock.getAllSubGroups(group.getId())).thenReturn(new Group[0]); } } } private Group aGroup(String name, String id, String fatherId, String domainId) { Group group = new Group(); group.setName(name); group.setDescription("This is the group " + name); group.setSuperGroupId(fatherId); group.setId(id); group.setDomainId(domainId); return group; } public String[] getUserIds(final UserDetail... users) { String[] ids = new String[users.length]; for (int i = 0; i < users.length; i++) { ids[i] = users[i].getId(); } return ids; } public String[] getGroupIds(final Group... groups) { String[] ids = new String[groups.length]; for (int i = 0; i < groups.length; i++) { ids[i] = groups[i].getId(); } return ids; } }
false
true
public void whenSearchUsersByCriteriaThenReturn(final UserDetailsSearchCriteria criteria, final UserDetail[] users) { OrganizationController mock = getOrganizationControllerMock(); doAnswer(new Answer<UserDetail[]>() { @Override public UserDetail[] answer(InvocationOnMock invocation) throws Throwable { UserDetail[] emptyUsers = new UserDetail[0]; UserDetailsSearchCriteria passedCriteria = (UserDetailsSearchCriteria) invocation.getArguments()[0]; if (criteria.isCriterionOnComponentInstanceIdSet() && passedCriteria. isCriterionOnComponentInstanceIdSet()) { if (!criteria.getCriterionOnComponentInstanceId().equals(passedCriteria. getCriterionOnComponentInstanceId())) { return emptyUsers; } } else if ((!criteria.isCriterionOnComponentInstanceIdSet() && passedCriteria. isCriterionOnComponentInstanceIdSet()) || (criteria. isCriterionOnComponentInstanceIdSet() && !passedCriteria. isCriterionOnComponentInstanceIdSet())) { return emptyUsers; } if (criteria.isCriterionOnDomainIdSet() && passedCriteria.isCriterionOnDomainIdSet()) { if (!criteria.getCriterionOnDomainId().equals(passedCriteria.getCriterionOnDomainId())) { return emptyUsers; } } else if ((!criteria.isCriterionOnDomainIdSet() && passedCriteria.isCriterionOnDomainIdSet()) || (criteria.isCriterionOnDomainIdSet() && !passedCriteria.isCriterionOnDomainIdSet())) { return emptyUsers; } if (criteria.isCriterionOnGroupIdsSet() && passedCriteria.isCriterionOnGroupIdsSet()) { if (!Arrays.equals(criteria.getCriterionOnGroupIds(), passedCriteria.getCriterionOnGroupIds())) { return emptyUsers; } } else if ((!criteria.isCriterionOnGroupIdsSet() && passedCriteria.isCriterionOnGroupIdsSet()) || (criteria.isCriterionOnGroupIdsSet() && !passedCriteria.isCriterionOnGroupIdsSet())) { return emptyUsers; } if (criteria.isCriterionOnNameSet() && passedCriteria.isCriterionOnNameSet()) { if (!criteria.getCriterionOnName().equals(passedCriteria.getCriterionOnName())) { return emptyUsers; } } else if ((!criteria.isCriterionOnNameSet() && passedCriteria.isCriterionOnNameSet()) || (criteria.isCriterionOnNameSet() && !passedCriteria.isCriterionOnNameSet())) { return emptyUsers; } if (criteria.isCriterionOnRoleIdsSet() && passedCriteria.isCriterionOnRoleIdsSet()) { List<String> roles = Arrays.asList(criteria.getCriterionOnRoleIds()); List<String> passedRoles = Arrays.asList(passedCriteria.getCriterionOnRoleIds()); if (roles.size() != passedRoles.size() || !roles.containsAll(passedRoles)) { return emptyUsers; } } else if ((!criteria.isCriterionOnRoleIdsSet() && passedCriteria.isCriterionOnRoleIdsSet()) || (criteria.isCriterionOnRoleIdsSet() && !passedCriteria.isCriterionOnRoleIdsSet())) { return emptyUsers; } if (criteria.isCriterionOnUserIdsSet() && passedCriteria.isCriterionOnUserIdsSet()) { List<String> userIds = Arrays.asList(criteria.getCriterionOnUserIds()); List<String> passedUserIds = Arrays.asList(passedCriteria.getCriterionOnUserIds()); if (userIds.size() != passedUserIds.size() || !userIds.containsAll(passedUserIds)) { return emptyUsers; } } else if ((!criteria.isCriterionOnUserIdsSet() && passedCriteria.isCriterionOnUserIdsSet()) || (criteria.isCriterionOnUserIdsSet() && !passedCriteria.isCriterionOnUserIdsSet())) { return emptyUsers; } return users; } }).when(mock).searchUsers(any(UserDetailsSearchCriteria.class)); }
public void whenSearchUsersByCriteriaThenReturn(final UserDetailsSearchCriteria criteria, final UserDetail[] users) { OrganizationController mock = getOrganizationControllerMock(); doAnswer(new Answer<UserDetail[]>() { @Override public UserDetail[] answer(InvocationOnMock invocation) throws Throwable { UserDetail[] emptyUsers = new UserDetail[0]; UserDetailsSearchCriteria passedCriteria = (UserDetailsSearchCriteria) invocation.getArguments()[0]; if (criteria.isCriterionOnComponentInstanceIdSet() && passedCriteria. isCriterionOnComponentInstanceIdSet()) { if (!criteria.getCriterionOnComponentInstanceId().equals(passedCriteria. getCriterionOnComponentInstanceId())) { return emptyUsers; } } else if ((!criteria.isCriterionOnComponentInstanceIdSet() && passedCriteria. isCriterionOnComponentInstanceIdSet()) || (criteria. isCriterionOnComponentInstanceIdSet() && !passedCriteria. isCriterionOnComponentInstanceIdSet())) { return emptyUsers; } if (criteria.isCriterionOnDomainIdSet() && passedCriteria.isCriterionOnDomainIdSet()) { if (!criteria.getCriterionOnDomainId().equals(passedCriteria.getCriterionOnDomainId())) { return emptyUsers; } } else if ((!criteria.isCriterionOnDomainIdSet() && passedCriteria.isCriterionOnDomainIdSet()) || (criteria.isCriterionOnDomainIdSet() && !passedCriteria.isCriterionOnDomainIdSet())) { return emptyUsers; } if (criteria.isCriterionOnGroupIdsSet() && passedCriteria.isCriterionOnGroupIdsSet()) { if (!Arrays.equals(criteria.getCriterionOnGroupIds(), passedCriteria.getCriterionOnGroupIds())) { return emptyUsers; } } else if ((!criteria.isCriterionOnGroupIdsSet() && passedCriteria.isCriterionOnGroupIdsSet()) || (criteria.isCriterionOnGroupIdsSet() && !passedCriteria.isCriterionOnGroupIdsSet())) { return emptyUsers; } if (criteria.isCriterionOnNameSet() && passedCriteria.isCriterionOnNameSet()) { if (!criteria.getCriterionOnName().equals(passedCriteria.getCriterionOnName())) { return emptyUsers; } } else if ((!criteria.isCriterionOnNameSet() && passedCriteria.isCriterionOnNameSet()) || (criteria.isCriterionOnNameSet() && !passedCriteria.isCriterionOnNameSet())) { return emptyUsers; } if (criteria.isCriterionOnRoleNamesSet() && passedCriteria.isCriterionOnRoleNamesSet()) { List<String> roles = Arrays.asList(criteria.getCriterionOnRoleNames()); List<String> passedRoles = Arrays.asList(passedCriteria.getCriterionOnRoleNames()); if (roles.size() != passedRoles.size() || !roles.containsAll(passedRoles)) { return emptyUsers; } } else if ((!criteria.isCriterionOnRoleNamesSet() && passedCriteria.isCriterionOnRoleNamesSet()) || (criteria.isCriterionOnRoleNamesSet() && !passedCriteria.isCriterionOnRoleNamesSet())) { return emptyUsers; } if (criteria.isCriterionOnUserIdsSet() && passedCriteria.isCriterionOnUserIdsSet()) { List<String> userIds = Arrays.asList(criteria.getCriterionOnUserIds()); List<String> passedUserIds = Arrays.asList(passedCriteria.getCriterionOnUserIds()); if (userIds.size() != passedUserIds.size() || !userIds.containsAll(passedUserIds)) { return emptyUsers; } } else if ((!criteria.isCriterionOnUserIdsSet() && passedCriteria.isCriterionOnUserIdsSet()) || (criteria.isCriterionOnUserIdsSet() && !passedCriteria.isCriterionOnUserIdsSet())) { return emptyUsers; } return users; } }).when(mock).searchUsers(any(UserDetailsSearchCriteria.class)); }
diff --git a/src/main/java/org/exolab/castor/builder/DescriptorSourceFactory.java b/src/main/java/org/exolab/castor/builder/DescriptorSourceFactory.java index 7e0222fa..bbfb43c7 100644 --- a/src/main/java/org/exolab/castor/builder/DescriptorSourceFactory.java +++ b/src/main/java/org/exolab/castor/builder/DescriptorSourceFactory.java @@ -1,795 +1,795 @@ /** * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided * that the following conditions are met: * * 1. Redistributions of source code must retain copyright * statements and notices. Redistributions must also contain a * copy of this document. * * 2. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * 3. The name "Exolab" must not be used to endorse or promote * products derived from this Software without prior written * permission of Intalio, Inc. For written permission, * please contact [email protected]. * * 4. Products derived from this Software may not be called "Exolab" * nor may "Exolab" appear in their names without prior written * permission of Intalio, Inc. Exolab is a registered * trademark of Intalio, Inc. * * 5. Due credit should be given to the Exolab Project * (http://www.exolab.org/). * * THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Copyright 1999-2004 (C) Intalio, Inc. All Rights Reserved. * * This file was originally developed by Keith Visco during the * course of employment at Intalio Inc. * All portions of this file developed by Keith Visco after Jan 19 2005 are * Copyright (C) 2005 Keith Visco. All Rights Reserverd. * * $Id$ */ package org.exolab.castor.builder; import org.exolab.castor.builder.types.XSClass; import org.exolab.castor.builder.types.XSList; import org.exolab.castor.builder.types.XSType; import org.exolab.castor.builder.util.DescriptorJClass; import org.exolab.castor.xml.JavaNaming; import org.exolab.javasource.JArrayType; import org.exolab.javasource.JClass; import org.exolab.javasource.JConstructor; import org.exolab.javasource.JField; import org.exolab.javasource.JModifiers; import org.exolab.javasource.JSourceCode; import org.exolab.javasource.JType; /** * A factory for creating the source code of descriptor classes * * @author <a href="mailto:keith AT kvisco DOT com">Keith Visco</a> * @version $Revision$ $Date: 2006-04-13 07:37:49 -0600 (Thu, 13 Apr 2006) $ */ public class DescriptorSourceFactory { /** * GeneralizedFieldHandler */ private static final JClass GENERALIZED_FIELD_HANDLER_CLASS = new JClass("org.exolab.castor.mapping.GeneralizedFieldHandler"); private static final String DESCRIPTOR_NAME = "Descriptor"; private static final String FIELD_VALIDATOR_NAME = "fieldValidator"; /** * The BuilderConfiguration instance */ private BuilderConfiguration _config = null; /** * Creates a new DescriptorSourceFactory with the given configuration * * @param config the BuilderConfiguration instance */ public DescriptorSourceFactory(final BuilderConfiguration config) { if (config == null) { String err = "The argument 'config' must not be null."; throw new IllegalArgumentException(err); } _config = config; } //-- DescriptorSourceFactory /** * Creates the Source code of a MarshalInfo for a given XML Schema element * declaration * * @param classInfo * the XML Schema element declaration * @return the JClass representing the MarshalInfo source code */ public JClass createSource(final ClassInfo classInfo) { JSourceCode jsc = null; JClass jClass = classInfo.getJClass(); String className = jClass.getName(); String localClassName = jClass.getLocalName(); DescriptorJClass classDesc = new DescriptorJClass(_config, className + DESCRIPTOR_NAME, jClass); //-- get handle to default constuctor JConstructor cons = classDesc.getConstructor(0); jsc = cons.getSourceCode(); //-- Set namespace prefix String nsPrefix = classInfo.getNamespacePrefix(); if ((nsPrefix != null) && (nsPrefix.length() > 0)) { jsc.add("nsPrefix = \""); jsc.append(nsPrefix); jsc.append("\";"); } //-- Set namespace URI String nsURI = classInfo.getNamespaceURI(); if ((nsURI != null) && (nsURI.length() > 0)) { jsc.add("nsURI = \""); jsc.append(nsURI); jsc.append("\";"); } //-- set XML Name String xmlName = classInfo.getNodeName(); if (xmlName != null) { jsc.add("xmlName = \""); jsc.append(xmlName); jsc.append("\";"); } //-- set Element Definition flag boolean elementDefinition = classInfo.isElementDefinition(); jsc.add("elementDefinition = "); jsc.append(new Boolean(elementDefinition).toString()); jsc.append(";"); //-- set grouping compositor if (classInfo.isChoice()) { jsc.add(""); jsc.add("//-- set grouping compositor"); jsc.add("setCompositorAsChoice();"); } else if (classInfo.isSequence()) { jsc.add(""); jsc.add("//-- set grouping compositor"); jsc.add("setCompositorAsSequence();"); } //-- To prevent compiler warnings...make sure //-- we don't declare temp variables if field count is 0; if (classInfo.getFieldCount() == 0) { return classDesc; } //-- declare temp variables jsc.add("org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;"); jsc.add("org.exolab.castor.mapping.FieldHandler handler = null;"); jsc.add("org.exolab.castor.xml.FieldValidator fieldValidator = null;"); //-- handle content if (classInfo.allowContent()) { createDescriptor(classDesc, classInfo.getTextField(), localClassName, null, jsc); } ClassInfo base = classInfo.getBaseClass(); FieldInfo[] atts = classInfo.getAttributeFields(); //--------------------------------/ //- Create attribute descriptors -/ //--------------------------------/ jsc.add("//-- initialize attribute descriptors"); jsc.add(""); for (int i = 0; i < atts.length; i++) { FieldInfo member = atts[i]; //-- skip transient members if (member.isTransient()) { continue; } if (base != null && base.getAttributeField(member.getNodeName()) != null) { createRestrictedDescriptor(member, jsc); } else { createDescriptor(classDesc, member, localClassName, nsURI, jsc); } } //------------------------------/ //- Create element descriptors -/ //------------------------------/ FieldInfo[] elements = classInfo.getElementFields(); jsc.add("//-- initialize element descriptors"); jsc.add(""); for (int i = 0; i < elements.length; i++) { FieldInfo member = elements[i]; //-- skip transient members if (member.isTransient()) { continue; } if (base != null && base.getElementField(member.getNodeName()) != null) { createRestrictedDescriptor(member, jsc); } else { createDescriptor(classDesc, member, localClassName, nsURI, jsc); } } return classDesc; } //-- createSource //-------------------/ //- Private Methods -/ //-------------------/ /** * Create special code for handling a member that is a restriction. * This will only change the Validation Code * @param member the restricted member for which we generate the restriction handling. * @param jsc the source code to which we append the validation code. */ private static void createRestrictedDescriptor(final FieldInfo member, final JSourceCode jsc) { jsc.add("desc = (org.exolab.castor.xml.util.XMLFieldDescriptorImpl) getFieldDescriptor(\""); jsc.append(member.getNodeName()); jsc.append("\""); jsc.append(", nsURI"); if (member.getNodeType() == XMLInfo.ELEMENT_TYPE) { jsc.append(", org.exolab.castor.xml.NodeType.Element);"); } else if (member.getNodeType() == XMLInfo.ATTRIBUTE_TYPE) { jsc.append(", org.exolab.castor.xml.NodeType.Attribute);"); } else { jsc.append("org.exolab.castor.xml.NodeType.Text);"); } //--modify the validation code validationCode(member, jsc); } /** * Creates a specific descriptor for a given member (whether an attribute or * an element) represented by a given Class name. * * @param classDesc * JClass-equivalent descriptor for this Descriptor class * @param member * the member for which to create a descriptor * @param localClassName * unqualified (no package) name of this class * @param nsURI * namespace URI * @param jsc * the source code to which we'll add this descriptor */ private void createDescriptor(final DescriptorJClass classDesc, final FieldInfo member, final String localClassName, String nsURI, final JSourceCode jsc) { XSType xsType = member.getSchemaType(); boolean any = false; boolean isElement = (member.getNodeType() == XMLInfo.ELEMENT_TYPE); boolean isAttribute = (member.getNodeType() == XMLInfo.ATTRIBUTE_TYPE); boolean isText = (member.getNodeType() == XMLInfo.TEXT_TYPE); jsc.add("//-- "); jsc.append(member.getName()); //-- a hack, I know, I will change later (kv) if (member.getName().equals("_anyObject")) { any = true; } if (xsType.getType() == XSType.COLLECTION) { //Attributes can handle COLLECTION type for NMTOKENS or IDREFS for instance xsType = ((CollectionInfo) member).getContent().getSchemaType(); } //-- Resolve how the node name parameter to the XMLFieldDescriptorImpl constructor is supplied String nodeName = member.getNodeName(); String nodeNameParam = null; if ((nodeName != null) && (!isText)) { //-- By default the node name parameter is a literal string nodeNameParam = "\"" + nodeName + "\""; if (_config.classDescFieldNames()) { //-- The node name parameter is a reference to a public static final nodeNameParam = member.getNodeName().toUpperCase(); //-- Expose node name as public static final (reused by XMLFieldDescriptorImpl) JModifiers publicStaticFinal = new JModifiers(); publicStaticFinal.makePublic(); publicStaticFinal.setStatic(true); publicStaticFinal.setFinal(true); JField jField = new JField(SGTypes.String, nodeNameParam); jField.setModifiers(publicStaticFinal); jField.setInitString("\"" + nodeName + "\""); classDesc.addMember(jField); } } //-- Generate code to new XMLFieldDescriptorImpl instance jsc.add("desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl("); jsc.append(classType(xsType.getJType())); jsc.append(", \""); jsc.append(member.getName()); jsc.append("\", "); if (nodeNameParam != null) { jsc.append(nodeNameParam); } else if (isText) { jsc.append("\"PCDATA\""); } else { jsc.append("(String)null"); } if (isElement) { jsc.append(", org.exolab.castor.xml.NodeType.Element);"); } else if (isAttribute) { jsc.append(", org.exolab.castor.xml.NodeType.Attribute);"); } else if (isText) { jsc.append(", org.exolab.castor.xml.NodeType.Text);"); } switch (xsType.getType()) { case XSType.STRING_TYPE : jsc.add("desc.setImmutable(true);"); break; //only for attributes case XSType.IDREF_TYPE : jsc.add("desc.setReference(true);"); break; case XSType.ID_TYPE : jsc.add("this.identity = desc;"); break; case XSType.QNAME_TYPE : jsc.add("desc.setSchemaType(\"QName\");"); /***********************/ default : break; } //switch //-- handler access methods if (member.getXMLFieldHandler() != null) { String handler = member.getXMLFieldHandler(); jsc.add("handler = new " + handler + "();"); jsc.add("//-- test for generalized field handler"); jsc.add("if (handler instanceof "); jsc.append(GENERALIZED_FIELD_HANDLER_CLASS.getName()); jsc.append(")"); jsc.add("{"); jsc.indent(); jsc.add("//-- save reference to user-specified handler"); jsc.add(GENERALIZED_FIELD_HANDLER_CLASS.getName()); jsc.append(" gfh = ("); jsc.append(GENERALIZED_FIELD_HANDLER_CLASS.getName()); jsc.append(")handler;"); createXMLFieldHandler(member, xsType, localClassName, jsc, true); jsc.add("gfh.setFieldHandler(handler);"); jsc.add("handler = gfh;"); jsc.unindent(); jsc.add("}"); } else { createXMLFieldHandler(member, xsType, localClassName, jsc, false); addSpecialHandlerLogic(member, xsType, jsc); } jsc.add("desc.setHandler(handler);"); //-- container if (member.isContainer()) { jsc.add("desc.setContainer(true);"); String className = xsType.getName(); //set the class descriptor //Try to prevent endless loop. Note: we only compare the localClassName. //If the packages are different an error can happen here if (className.equals(localClassName)) { jsc.add("desc.setClassDescriptor(this);"); } else { jsc.add("desc.setClassDescriptor(new " + className + DESCRIPTOR_NAME + "());"); } } //-- Handle namespaces //-- FieldInfo namespace has higher priority than ClassInfo namespace. nsURI = member.getNamespaceURI(); if (nsURI != null) { jsc.add("desc.setNameSpaceURI(\""); jsc.append(nsURI); jsc.append("\");"); } if (any && member.getNamespaceURI() == null) { nsURI = null; } //-- required if (member.isRequired()) { jsc.add("desc.setRequired(true);"); } //-- nillable if (member.isNillable()) { jsc.add("desc.setNillable(true);"); } //-- if any it can match all the names if (any) { jsc.add("desc.setMatches(\"*\");"); } //-- mark as multi or single valued for elements if (isElement || isAttribute) { jsc.add("desc.setMultivalued(" + member.isMultivalued()); jsc.append(");"); } jsc.add("addFieldDescriptor(desc);"); jsc.add(""); //-- Add Validation Code validationCode(member, jsc); } //--CreateDescriptor /** * Creates the XMLFieldHandler for the given FieldInfo. * * @param member * the member for which to create an XMLFieldHandler * @param xsType the XSType (XML Schema Type) of this field * @param localClassName * unqualified (no package) name of this class * @param jsc * the source code to which we'll add this XMLFieldHandler * @param forGeneralizedHandler Whether to generate a generalized field handler */ private void createXMLFieldHandler(final FieldInfo member, final XSType xsType, final String localClassName, final JSourceCode jsc, final boolean forGeneralizedHandler) { boolean any = false; boolean isEnumerated = false; //-- a hack, I know, I will change later (kv) if (member.getName().equals("_anyObject")) { any = true; } if (xsType.getType() == XSType.CLASS) { isEnumerated = ((XSClass) xsType).isEnumerated(); } jsc.add("handler = new org.exolab.castor.xml.XMLFieldHandler() {"); jsc.indent(); //-- getValue(Object) method if (_config.useJava50()) { jsc.add("@Override"); } jsc.add("public java.lang.Object getValue( java.lang.Object object ) "); jsc.indent(); jsc.add("throws IllegalStateException"); jsc.unindent(); jsc.add("{"); jsc.indent(); jsc.add(localClassName); jsc.append(" target = ("); jsc.append(localClassName); jsc.append(") object;"); //-- handle primitives if ((!xsType.isEnumerated()) && xsType.getJType().isPrimitive() && (!member.isMultivalued())) { jsc.add("if(!target." + member.getHasMethodName() + "())"); jsc.indent(); jsc.add("return null;"); jsc.unindent(); } //-- Return field value jsc.add("return "); String value = "target." + member.getReadMethodName() + "()"; if (member.isMultivalued()) { jsc.append(value); //--Be careful : different for attributes } else { jsc.append(xsType.createToJavaObjectCode(value)); } jsc.append(";"); jsc.unindent(); jsc.add("}"); //--end of getValue(Object) method boolean isAttribute = (member.getNodeType() == XMLInfo.ATTRIBUTE_TYPE); boolean isContent = (member.getNodeType() == XMLInfo.TEXT_TYPE); //-- setValue(Object, Object) method if (_config.useJava50()) { jsc.add("@Override"); } jsc.add("public void setValue( java.lang.Object object, java.lang.Object value) "); jsc.indent(); jsc.add("throws IllegalStateException, IllegalArgumentException"); jsc.unindent(); jsc.add("{"); jsc.indent(); jsc.add("try {"); jsc.indent(); jsc.add(localClassName); jsc.append(" target = ("); jsc.append(localClassName); jsc.append(") object;"); //-- check for null primitives if (xsType.isPrimitive() && !_config.usePrimitiveWrapper()) { if ((!member.isRequired()) && (!xsType.isEnumerated()) && (!member.isMultivalued())) { jsc.add("// if null, use delete method for optional primitives "); jsc.add("if (value == null) {"); jsc.indent(); jsc.add("target."); jsc.append(member.getDeleteMethodName()); jsc.append("();"); jsc.add("return;"); jsc.unindent(); jsc.add("}"); } else { jsc.add("// ignore null values for non optional primitives"); jsc.add("if (value == null) return;"); jsc.add(""); } } //if primitive jsc.add("target."); jsc.append(member.getWriteMethodName()); jsc.append("( "); if (xsType.isPrimitive() && !_config.usePrimitiveWrapper()) { jsc.append(xsType.createFromJavaObjectCode("value")); } else if (any) { jsc.append(" value "); } else { jsc.append("("); jsc.append(xsType.getJType().toString()); //special handling for the type package //when we are dealing with attributes //This is a temporary solution since we need to handle //the 'types' in specific handlers in the future //i.e add specific FieldHandler in org.exolab.castor.xml.handlers //dateTime is not concerned by the following since it is directly //handle by DateFieldHandler if ((isAttribute | isContent) && xsType.isDateTime() && xsType.getType() != XSType.DATETIME_TYPE) { jsc.append(".parse"); jsc.append(JavaNaming.toJavaClassName(xsType.getName())); jsc.append("((String) value))"); } else { jsc.append(") value"); } } jsc.append(");"); jsc.unindent(); jsc.add("}"); jsc.add("catch (java.lang.Exception ex) {"); jsc.indent(); jsc.add("throw new IllegalStateException(ex.toString());"); jsc.unindent(); jsc.add("}"); jsc.unindent(); jsc.add("}"); //--end of setValue(Object, Object) method //-- reset method (handle collections only) if (member.isMultivalued()) { CollectionInfo cInfo = (CollectionInfo) member; // FieldInfo content = cInfo.getContent(); jsc.add("public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException {"); jsc.indent(); jsc.add("try {"); jsc.indent(); jsc.add(localClassName); jsc.append(" target = ("); jsc.append(localClassName); jsc.append(") object;"); String cName = JavaNaming.toJavaClassName(cInfo.getElementName()); - if (cInfo instanceof CollectionInfoJ2) { - jsc.add("target.clear" + cName + "();"); - } else { +// if (cInfo instanceof CollectionInfoJ2) { +// jsc.add("target.clear" + cName + "();"); +// } else { jsc.add("target.removeAll" + cName + "();"); - } +// } jsc.unindent(); jsc.add("} catch (java.lang.Exception ex) {"); jsc.indent(); jsc.add("throw new IllegalStateException(ex.toString());"); jsc.unindent(); jsc.add("}"); jsc.unindent(); jsc.add("}"); } //-- end of reset method createNewInstanceMethodForXMLFieldHandler(member, xsType, jsc, forGeneralizedHandler, any, isEnumerated); jsc.unindent(); jsc.add("};"); } //--end of XMLFieldHandler /** * Creates the newInstance() method of the corresponsing XMLFieldHandler. * @param member The member element. * @param xsType The XSType instance * @param jsc The source code to which to append the 'newInstance' method. * @param forGeneralizedHandler Whether to generate a generalized field handler * @param any Whether to create a newInstance() method for <xs:any> * @param isEnumerated Whether to create a newInstance() method for an enumeration. */ private void createNewInstanceMethodForXMLFieldHandler( final FieldInfo member, final XSType xsType, final JSourceCode jsc, final boolean forGeneralizedHandler, final boolean any, final boolean isEnumerated) { boolean isAbstract = false; // Commented out according to CASTOR-1340 // if (member.getDeclaringClassInfo() != null) { // isAbstract = member.getDeclaringClassInfo().isAbstract(); // } // check whether class of member is declared as abstract if (member.getSchemaType() != null && member.getSchemaType().getJType() instanceof JClass) { JClass jClass = (JClass) member.getSchemaType().getJType(); isAbstract = jClass.getModifiers().isAbstract(); } if (!isAbstract && xsType.getJType() instanceof JClass) { JClass jClass = (JClass) xsType.getJType(); isAbstract = jClass.getModifiers().isAbstract(); } if (!isAbstract && member.getSchemaType() instanceof XSList) { XSList xsList = (XSList) member.getSchemaType(); if (xsList.getContentType().getJType() instanceof JClass) { JClass componentType = (JClass) xsList.getContentType().getJType(); if (componentType.getModifiers().isAbstract()) { isAbstract = componentType.getModifiers().isAbstract(); } } } if (_config.useJava50()) { jsc.add("@Override"); jsc.add("@SuppressWarnings(\"unused\")"); } jsc.add("public java.lang.Object newInstance( java.lang.Object parent ) {"); jsc.indent(); jsc.add("return "); if (any || forGeneralizedHandler || isEnumerated || xsType.isPrimitive() || xsType.getJType() instanceof JArrayType || (xsType.getType() == XSType.STRING_TYPE) || isAbstract) { jsc.append("null;"); } else { jsc.append(xsType.newInstanceCode()); } jsc.unindent(); jsc.add("}"); } /** * Adds additional logic or wrappers around the core handler for special * types such as dates, enumerated types, collections, etc. * * @param member the member for which extra special handler logic may be created * @param xsType the field type for which extra special handler logic may be created * @param jsc the java source code to which this will be written */ private void addSpecialHandlerLogic(final FieldInfo member, final XSType xsType, final JSourceCode jsc) { if (xsType.isEnumerated()) { jsc.add("handler = new org.exolab.castor.xml.handlers.EnumFieldHandler("); jsc.append(classType(xsType.getJType())); jsc.append(", handler);"); jsc.add("desc.setImmutable(true);"); } else if (xsType.getType() == XSType.DATETIME_TYPE) { jsc.add("handler = new org.exolab.castor.xml.handlers.DateFieldHandler("); jsc.append("handler);"); jsc.add("desc.setImmutable(true);"); } else if (xsType.getType() == XSType.DECIMAL_TYPE) { jsc.add("desc.setImmutable(true);"); } else if (member.getSchemaType().getType() == XSType.COLLECTION) { //-- Handle special Collection Types such as NMTOKENS and IDREFS switch (xsType.getType()) { case XSType.NMTOKEN_TYPE: case XSType.NMTOKENS_TYPE: //-- use CollectionFieldHandler jsc.add("handler = new org.exolab.castor.xml.handlers.CollectionFieldHandler("); jsc.append("handler, new org.exolab.castor.xml.validators.NameValidator("); jsc.append("org.exolab.castor.xml.validators.NameValidator.NMTOKEN));"); break; case XSType.QNAME_TYPE: //-- use CollectionFieldHandler jsc.add("handler = new org.exolab.castor.xml.handlers.CollectionFieldHandler("); jsc.append("handler, null);"); break; case XSType.IDREF_TYPE: case XSType.IDREFS_TYPE: //-- uses special code in UnmarshalHandler //-- see UnmarshalHandler#processIDREF jsc.add("desc.setMultivalued("); jsc.append("" + member.isMultivalued()); jsc.append(");"); break; default: break; } } } //-- addSpecialHandlerLogic /** * Creates the validation code for a given member. This code will be * appended to the given JSourceCode. * * @param member * the member for which to create the validation code. * @param jsc * the JSourceCode to fill in. */ private static void validationCode(final FieldInfo member, final JSourceCode jsc) { if (member == null || jsc == null) { return; } jsc.add("//-- validation code for: "); jsc.append(member.getName()); String validator = member.getValidator(); if (validator != null && validator.length() > 0) { jsc.add("fieldValidator = new " + validator + "();"); } else { jsc.add("fieldValidator = new org.exolab.castor.xml.FieldValidator();"); //-- a hack, I know, I will change later if (member.getName().equals("_anyObject")) { jsc.add("desc.setValidator(fieldValidator);"); return; } XSType xsType = member.getSchemaType(); //--handle collections if ((xsType.getType() == XSType.COLLECTION)) { XSList xsList = (XSList) xsType; jsc.add("fieldValidator.setMinOccurs("); jsc.append(Integer.toString(xsList.getMinimumSize())); jsc.append(");"); if (xsList.getMaximumSize() > 0) { jsc.add("fieldValidator.setMaxOccurs("); jsc.append(Integer.toString(xsList.getMaximumSize())); jsc.append(");"); } xsType = ((CollectionInfo) member).getContent().getSchemaType(); //special handling for NMTOKEN if (xsType.getType() == XSType.NMTOKEN_TYPE) { return; } } else if (member.isRequired()) { jsc.add("fieldValidator.setMinOccurs(1);"); } jsc.add("{ //-- local scope"); jsc.indent(); xsType.validationCode(jsc, member.getFixedValue(), FIELD_VALIDATOR_NAME); jsc.unindent(); jsc.add("}"); } jsc.add("desc.setValidator(fieldValidator);"); } /** * Returns the Class type (as a String) for the given XSType. * @param jType the JType whose Class type will be returned * @return the Class type (as a String) for the given XSType. */ private static String classType(final JType jType) { if (jType.isPrimitive()) { return jType.getWrapperName() + ".TYPE"; } return jType.toString() + ".class"; } //-- classType } //-- DescriptorSourceFactory
false
true
private void createXMLFieldHandler(final FieldInfo member, final XSType xsType, final String localClassName, final JSourceCode jsc, final boolean forGeneralizedHandler) { boolean any = false; boolean isEnumerated = false; //-- a hack, I know, I will change later (kv) if (member.getName().equals("_anyObject")) { any = true; } if (xsType.getType() == XSType.CLASS) { isEnumerated = ((XSClass) xsType).isEnumerated(); } jsc.add("handler = new org.exolab.castor.xml.XMLFieldHandler() {"); jsc.indent(); //-- getValue(Object) method if (_config.useJava50()) { jsc.add("@Override"); } jsc.add("public java.lang.Object getValue( java.lang.Object object ) "); jsc.indent(); jsc.add("throws IllegalStateException"); jsc.unindent(); jsc.add("{"); jsc.indent(); jsc.add(localClassName); jsc.append(" target = ("); jsc.append(localClassName); jsc.append(") object;"); //-- handle primitives if ((!xsType.isEnumerated()) && xsType.getJType().isPrimitive() && (!member.isMultivalued())) { jsc.add("if(!target." + member.getHasMethodName() + "())"); jsc.indent(); jsc.add("return null;"); jsc.unindent(); } //-- Return field value jsc.add("return "); String value = "target." + member.getReadMethodName() + "()"; if (member.isMultivalued()) { jsc.append(value); //--Be careful : different for attributes } else { jsc.append(xsType.createToJavaObjectCode(value)); } jsc.append(";"); jsc.unindent(); jsc.add("}"); //--end of getValue(Object) method boolean isAttribute = (member.getNodeType() == XMLInfo.ATTRIBUTE_TYPE); boolean isContent = (member.getNodeType() == XMLInfo.TEXT_TYPE); //-- setValue(Object, Object) method if (_config.useJava50()) { jsc.add("@Override"); } jsc.add("public void setValue( java.lang.Object object, java.lang.Object value) "); jsc.indent(); jsc.add("throws IllegalStateException, IllegalArgumentException"); jsc.unindent(); jsc.add("{"); jsc.indent(); jsc.add("try {"); jsc.indent(); jsc.add(localClassName); jsc.append(" target = ("); jsc.append(localClassName); jsc.append(") object;"); //-- check for null primitives if (xsType.isPrimitive() && !_config.usePrimitiveWrapper()) { if ((!member.isRequired()) && (!xsType.isEnumerated()) && (!member.isMultivalued())) { jsc.add("// if null, use delete method for optional primitives "); jsc.add("if (value == null) {"); jsc.indent(); jsc.add("target."); jsc.append(member.getDeleteMethodName()); jsc.append("();"); jsc.add("return;"); jsc.unindent(); jsc.add("}"); } else { jsc.add("// ignore null values for non optional primitives"); jsc.add("if (value == null) return;"); jsc.add(""); } } //if primitive jsc.add("target."); jsc.append(member.getWriteMethodName()); jsc.append("( "); if (xsType.isPrimitive() && !_config.usePrimitiveWrapper()) { jsc.append(xsType.createFromJavaObjectCode("value")); } else if (any) { jsc.append(" value "); } else { jsc.append("("); jsc.append(xsType.getJType().toString()); //special handling for the type package //when we are dealing with attributes //This is a temporary solution since we need to handle //the 'types' in specific handlers in the future //i.e add specific FieldHandler in org.exolab.castor.xml.handlers //dateTime is not concerned by the following since it is directly //handle by DateFieldHandler if ((isAttribute | isContent) && xsType.isDateTime() && xsType.getType() != XSType.DATETIME_TYPE) { jsc.append(".parse"); jsc.append(JavaNaming.toJavaClassName(xsType.getName())); jsc.append("((String) value))"); } else { jsc.append(") value"); } } jsc.append(");"); jsc.unindent(); jsc.add("}"); jsc.add("catch (java.lang.Exception ex) {"); jsc.indent(); jsc.add("throw new IllegalStateException(ex.toString());"); jsc.unindent(); jsc.add("}"); jsc.unindent(); jsc.add("}"); //--end of setValue(Object, Object) method //-- reset method (handle collections only) if (member.isMultivalued()) { CollectionInfo cInfo = (CollectionInfo) member; // FieldInfo content = cInfo.getContent(); jsc.add("public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException {"); jsc.indent(); jsc.add("try {"); jsc.indent(); jsc.add(localClassName); jsc.append(" target = ("); jsc.append(localClassName); jsc.append(") object;"); String cName = JavaNaming.toJavaClassName(cInfo.getElementName()); if (cInfo instanceof CollectionInfoJ2) { jsc.add("target.clear" + cName + "();"); } else { jsc.add("target.removeAll" + cName + "();"); } jsc.unindent(); jsc.add("} catch (java.lang.Exception ex) {"); jsc.indent(); jsc.add("throw new IllegalStateException(ex.toString());"); jsc.unindent(); jsc.add("}"); jsc.unindent(); jsc.add("}"); } //-- end of reset method createNewInstanceMethodForXMLFieldHandler(member, xsType, jsc, forGeneralizedHandler, any, isEnumerated); jsc.unindent(); jsc.add("};"); } //--end of XMLFieldHandler
private void createXMLFieldHandler(final FieldInfo member, final XSType xsType, final String localClassName, final JSourceCode jsc, final boolean forGeneralizedHandler) { boolean any = false; boolean isEnumerated = false; //-- a hack, I know, I will change later (kv) if (member.getName().equals("_anyObject")) { any = true; } if (xsType.getType() == XSType.CLASS) { isEnumerated = ((XSClass) xsType).isEnumerated(); } jsc.add("handler = new org.exolab.castor.xml.XMLFieldHandler() {"); jsc.indent(); //-- getValue(Object) method if (_config.useJava50()) { jsc.add("@Override"); } jsc.add("public java.lang.Object getValue( java.lang.Object object ) "); jsc.indent(); jsc.add("throws IllegalStateException"); jsc.unindent(); jsc.add("{"); jsc.indent(); jsc.add(localClassName); jsc.append(" target = ("); jsc.append(localClassName); jsc.append(") object;"); //-- handle primitives if ((!xsType.isEnumerated()) && xsType.getJType().isPrimitive() && (!member.isMultivalued())) { jsc.add("if(!target." + member.getHasMethodName() + "())"); jsc.indent(); jsc.add("return null;"); jsc.unindent(); } //-- Return field value jsc.add("return "); String value = "target." + member.getReadMethodName() + "()"; if (member.isMultivalued()) { jsc.append(value); //--Be careful : different for attributes } else { jsc.append(xsType.createToJavaObjectCode(value)); } jsc.append(";"); jsc.unindent(); jsc.add("}"); //--end of getValue(Object) method boolean isAttribute = (member.getNodeType() == XMLInfo.ATTRIBUTE_TYPE); boolean isContent = (member.getNodeType() == XMLInfo.TEXT_TYPE); //-- setValue(Object, Object) method if (_config.useJava50()) { jsc.add("@Override"); } jsc.add("public void setValue( java.lang.Object object, java.lang.Object value) "); jsc.indent(); jsc.add("throws IllegalStateException, IllegalArgumentException"); jsc.unindent(); jsc.add("{"); jsc.indent(); jsc.add("try {"); jsc.indent(); jsc.add(localClassName); jsc.append(" target = ("); jsc.append(localClassName); jsc.append(") object;"); //-- check for null primitives if (xsType.isPrimitive() && !_config.usePrimitiveWrapper()) { if ((!member.isRequired()) && (!xsType.isEnumerated()) && (!member.isMultivalued())) { jsc.add("// if null, use delete method for optional primitives "); jsc.add("if (value == null) {"); jsc.indent(); jsc.add("target."); jsc.append(member.getDeleteMethodName()); jsc.append("();"); jsc.add("return;"); jsc.unindent(); jsc.add("}"); } else { jsc.add("// ignore null values for non optional primitives"); jsc.add("if (value == null) return;"); jsc.add(""); } } //if primitive jsc.add("target."); jsc.append(member.getWriteMethodName()); jsc.append("( "); if (xsType.isPrimitive() && !_config.usePrimitiveWrapper()) { jsc.append(xsType.createFromJavaObjectCode("value")); } else if (any) { jsc.append(" value "); } else { jsc.append("("); jsc.append(xsType.getJType().toString()); //special handling for the type package //when we are dealing with attributes //This is a temporary solution since we need to handle //the 'types' in specific handlers in the future //i.e add specific FieldHandler in org.exolab.castor.xml.handlers //dateTime is not concerned by the following since it is directly //handle by DateFieldHandler if ((isAttribute | isContent) && xsType.isDateTime() && xsType.getType() != XSType.DATETIME_TYPE) { jsc.append(".parse"); jsc.append(JavaNaming.toJavaClassName(xsType.getName())); jsc.append("((String) value))"); } else { jsc.append(") value"); } } jsc.append(");"); jsc.unindent(); jsc.add("}"); jsc.add("catch (java.lang.Exception ex) {"); jsc.indent(); jsc.add("throw new IllegalStateException(ex.toString());"); jsc.unindent(); jsc.add("}"); jsc.unindent(); jsc.add("}"); //--end of setValue(Object, Object) method //-- reset method (handle collections only) if (member.isMultivalued()) { CollectionInfo cInfo = (CollectionInfo) member; // FieldInfo content = cInfo.getContent(); jsc.add("public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException {"); jsc.indent(); jsc.add("try {"); jsc.indent(); jsc.add(localClassName); jsc.append(" target = ("); jsc.append(localClassName); jsc.append(") object;"); String cName = JavaNaming.toJavaClassName(cInfo.getElementName()); // if (cInfo instanceof CollectionInfoJ2) { // jsc.add("target.clear" + cName + "();"); // } else { jsc.add("target.removeAll" + cName + "();"); // } jsc.unindent(); jsc.add("} catch (java.lang.Exception ex) {"); jsc.indent(); jsc.add("throw new IllegalStateException(ex.toString());"); jsc.unindent(); jsc.add("}"); jsc.unindent(); jsc.add("}"); } //-- end of reset method createNewInstanceMethodForXMLFieldHandler(member, xsType, jsc, forGeneralizedHandler, any, isEnumerated); jsc.unindent(); jsc.add("};"); } //--end of XMLFieldHandler
diff --git a/waterken/server/src/org/waterken/server/Serve.java b/waterken/server/src/org/waterken/server/Serve.java index 937c5f3b..cfbe552d 100644 --- a/waterken/server/src/org/waterken/server/Serve.java +++ b/waterken/server/src/org/waterken/server/Serve.java @@ -1,178 +1,178 @@ // Copyright 2005-2007 Waterken Inc. under the terms of the MIT X license // found at http://www.opensource.org/licenses/mit-license.html package org.waterken.server; import static org.joe_e.file.Filesystem.file; import static org.waterken.io.MediaType.MIME; import java.io.File; import java.io.InputStream; import java.io.PrintStream; import java.lang.reflect.Type; import java.net.DatagramSocket; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.security.SecureRandom; import java.util.Enumeration; import org.joe_e.array.ByteArray; import org.joe_e.array.PowerlessArray; import org.joe_e.file.Filesystem; import org.ref_send.Variable; import org.ref_send.promise.eventual.Eventual; import org.ref_send.promise.eventual.Task; import org.waterken.dns.Resource; import org.waterken.dns.udp.NameServer; import org.waterken.http.Server; import org.waterken.http.mirror.Mirror; import org.waterken.http.trace.Trace; import org.waterken.jos.JODB; import org.waterken.net.http.HTTPD; import org.waterken.remote.http.AMP; import org.waterken.remote.http.Browser; import org.waterken.remote.mux.Mux; import org.waterken.syntax.json.JSONDeserializer; import org.waterken.thread.Concurrent; /** * Starts the server. */ final class Serve { private Serve() {} /** * @param args command line arguments */ static public void main(String[] args) throws Exception { // Initialize the static state. final File home = new File("").getAbsoluteFile(); final File www = file(home, "www"); final File db = file(home, JODB.dbDirName); final File keys = new File(home, "keys.jks"); // Extract the arguments. int i = 0; int backlog = 100; int maxAge = 0; int soTimeout = 60 * 1000; if (args.length == 0) { // the default arguments if none are specified if (keys.isFile()) { args = new String[] { "http=80", "https=443" }; } else { args = new String[] { "http=8080" }; } } else { // Pop any server arguments. for (; i != args.length; ++i) { if (args[i].startsWith("backlog=")) { backlog = Integer.parseInt(args[i].substring(9)); } else if (args[i].startsWith("max-age=")) { maxAge = Integer.parseInt(args[i].substring(8)); } else if (args[i].startsWith("so-timeout=")) { soTimeout = Integer.parseInt(args[i].substring(11)); } else { // Assume this is the start of the service list. break; } } } // Summarize the configuration information. final PrintStream err = System.err; err.println("Home directory: <" + home + ">"); err.println("Files served with Cache-Control: max-age=" + maxAge); err.println("Using server socket backlog: " + backlog); err.println("Using connection socket timeout: " + soTimeout + " ms"); // Configure the server. final Server server = Trace.make(Mux.make(db, new AMP(), Mirror.make(maxAge, www, MIME))); // Start the inbound network services. for (; i != args.length; ++i) { final String service = args[i]; final int eq = service.indexOf('='); final String protocol = service.substring(0, eq); final int port = Integer.parseInt(service.substring(eq + 1)); final Runnable listener; if ("http".equals(protocol)) { Proxy.protocols.put("http", Loopback.client(80)); listener = new TCP(err, new ThreadGroup(service), "http", HTTPD.make("http", server, Proxy.thread), soTimeout, new ServerSocket(port, backlog, Loopback.addr)); } else if ("https".equals(protocol)) { final Credentials credentials=SSL.keystore("TLS",keys,"nopass"); Proxy.protocols.put("https", SSL.client(443, credentials)); final ServerSocket listen = credentials.getContext(). getServerSocketFactory().createServerSocket(port, backlog); listener = new TCP(err, new ThreadGroup(service), "https", HTTPD.make("https",server,Proxy.thread), soTimeout, listen); } else if ("dns".equals(protocol)) { listener = new UDP(err, "dns", NameServer.make(file(db, "dns")), new DatagramSocket(port)); } else { err.println("Unrecognized protocol: " + protocol); return; } // run the corresponding daemon new Thread(listener, service).start(); } // update the DNS final File ip = new File("ip.json"); if (ip.isFile()) { // find the ip address. Inet4Address addr = null; for (final Enumeration<NetworkInterface> j = NetworkInterface.getNetworkInterfaces(); j.hasMoreElements();) { final NetworkInterface x = j.nextElement(); for (final Enumeration<InetAddress> k = x.getInetAddresses(); - j.hasMoreElements();) { + k.hasMoreElements();) { final InetAddress a = k.nextElement(); if (a instanceof Inet4Address && !a.isLoopbackAddress()) { addr = (Inet4Address)a; break; } } } - if (null == addr) { return; } - final Inet4Address outer = addr; + final InetAddress outer = null != addr ? addr : Loopback.addr; // notify the DNS nameserver final ClassLoader code = GenKey.class.getClassLoader(); final Browser browser = Browser.make( new Proxy(), new SecureRandom(), code, Concurrent.loop(Thread.currentThread().getThreadGroup(), "enqueue")); final Eventual _ = browser._; _.enqueue.run(new Task() { @SuppressWarnings("unchecked") public void run() throws Exception { final InputStream in = Filesystem.read(ip); final Type type = Variable.class; final Variable update = (Variable)new JSONDeserializer(). run("", browser.connect, code, in, PowerlessArray.array(type)).get(0); in.close(); + System.err.println("Updating DNS to: " + + outer.getHostAddress() + "..."); final ByteArray a = ByteArray.array(outer.getAddress()); - System.err.println("Updating DNS to: " + a + "..."); update.put(new Resource(Resource.A, Resource.IN, 0, a)); } }); } } }
false
true
static public void main(String[] args) throws Exception { // Initialize the static state. final File home = new File("").getAbsoluteFile(); final File www = file(home, "www"); final File db = file(home, JODB.dbDirName); final File keys = new File(home, "keys.jks"); // Extract the arguments. int i = 0; int backlog = 100; int maxAge = 0; int soTimeout = 60 * 1000; if (args.length == 0) { // the default arguments if none are specified if (keys.isFile()) { args = new String[] { "http=80", "https=443" }; } else { args = new String[] { "http=8080" }; } } else { // Pop any server arguments. for (; i != args.length; ++i) { if (args[i].startsWith("backlog=")) { backlog = Integer.parseInt(args[i].substring(9)); } else if (args[i].startsWith("max-age=")) { maxAge = Integer.parseInt(args[i].substring(8)); } else if (args[i].startsWith("so-timeout=")) { soTimeout = Integer.parseInt(args[i].substring(11)); } else { // Assume this is the start of the service list. break; } } } // Summarize the configuration information. final PrintStream err = System.err; err.println("Home directory: <" + home + ">"); err.println("Files served with Cache-Control: max-age=" + maxAge); err.println("Using server socket backlog: " + backlog); err.println("Using connection socket timeout: " + soTimeout + " ms"); // Configure the server. final Server server = Trace.make(Mux.make(db, new AMP(), Mirror.make(maxAge, www, MIME))); // Start the inbound network services. for (; i != args.length; ++i) { final String service = args[i]; final int eq = service.indexOf('='); final String protocol = service.substring(0, eq); final int port = Integer.parseInt(service.substring(eq + 1)); final Runnable listener; if ("http".equals(protocol)) { Proxy.protocols.put("http", Loopback.client(80)); listener = new TCP(err, new ThreadGroup(service), "http", HTTPD.make("http", server, Proxy.thread), soTimeout, new ServerSocket(port, backlog, Loopback.addr)); } else if ("https".equals(protocol)) { final Credentials credentials=SSL.keystore("TLS",keys,"nopass"); Proxy.protocols.put("https", SSL.client(443, credentials)); final ServerSocket listen = credentials.getContext(). getServerSocketFactory().createServerSocket(port, backlog); listener = new TCP(err, new ThreadGroup(service), "https", HTTPD.make("https",server,Proxy.thread), soTimeout, listen); } else if ("dns".equals(protocol)) { listener = new UDP(err, "dns", NameServer.make(file(db, "dns")), new DatagramSocket(port)); } else { err.println("Unrecognized protocol: " + protocol); return; } // run the corresponding daemon new Thread(listener, service).start(); } // update the DNS final File ip = new File("ip.json"); if (ip.isFile()) { // find the ip address. Inet4Address addr = null; for (final Enumeration<NetworkInterface> j = NetworkInterface.getNetworkInterfaces(); j.hasMoreElements();) { final NetworkInterface x = j.nextElement(); for (final Enumeration<InetAddress> k = x.getInetAddresses(); j.hasMoreElements();) { final InetAddress a = k.nextElement(); if (a instanceof Inet4Address && !a.isLoopbackAddress()) { addr = (Inet4Address)a; break; } } } if (null == addr) { return; } final Inet4Address outer = addr; // notify the DNS nameserver final ClassLoader code = GenKey.class.getClassLoader(); final Browser browser = Browser.make( new Proxy(), new SecureRandom(), code, Concurrent.loop(Thread.currentThread().getThreadGroup(), "enqueue")); final Eventual _ = browser._; _.enqueue.run(new Task() { @SuppressWarnings("unchecked") public void run() throws Exception { final InputStream in = Filesystem.read(ip); final Type type = Variable.class; final Variable update = (Variable)new JSONDeserializer(). run("", browser.connect, code, in, PowerlessArray.array(type)).get(0); in.close(); final ByteArray a = ByteArray.array(outer.getAddress()); System.err.println("Updating DNS to: " + a + "..."); update.put(new Resource(Resource.A, Resource.IN, 0, a)); } }); } }
static public void main(String[] args) throws Exception { // Initialize the static state. final File home = new File("").getAbsoluteFile(); final File www = file(home, "www"); final File db = file(home, JODB.dbDirName); final File keys = new File(home, "keys.jks"); // Extract the arguments. int i = 0; int backlog = 100; int maxAge = 0; int soTimeout = 60 * 1000; if (args.length == 0) { // the default arguments if none are specified if (keys.isFile()) { args = new String[] { "http=80", "https=443" }; } else { args = new String[] { "http=8080" }; } } else { // Pop any server arguments. for (; i != args.length; ++i) { if (args[i].startsWith("backlog=")) { backlog = Integer.parseInt(args[i].substring(9)); } else if (args[i].startsWith("max-age=")) { maxAge = Integer.parseInt(args[i].substring(8)); } else if (args[i].startsWith("so-timeout=")) { soTimeout = Integer.parseInt(args[i].substring(11)); } else { // Assume this is the start of the service list. break; } } } // Summarize the configuration information. final PrintStream err = System.err; err.println("Home directory: <" + home + ">"); err.println("Files served with Cache-Control: max-age=" + maxAge); err.println("Using server socket backlog: " + backlog); err.println("Using connection socket timeout: " + soTimeout + " ms"); // Configure the server. final Server server = Trace.make(Mux.make(db, new AMP(), Mirror.make(maxAge, www, MIME))); // Start the inbound network services. for (; i != args.length; ++i) { final String service = args[i]; final int eq = service.indexOf('='); final String protocol = service.substring(0, eq); final int port = Integer.parseInt(service.substring(eq + 1)); final Runnable listener; if ("http".equals(protocol)) { Proxy.protocols.put("http", Loopback.client(80)); listener = new TCP(err, new ThreadGroup(service), "http", HTTPD.make("http", server, Proxy.thread), soTimeout, new ServerSocket(port, backlog, Loopback.addr)); } else if ("https".equals(protocol)) { final Credentials credentials=SSL.keystore("TLS",keys,"nopass"); Proxy.protocols.put("https", SSL.client(443, credentials)); final ServerSocket listen = credentials.getContext(). getServerSocketFactory().createServerSocket(port, backlog); listener = new TCP(err, new ThreadGroup(service), "https", HTTPD.make("https",server,Proxy.thread), soTimeout, listen); } else if ("dns".equals(protocol)) { listener = new UDP(err, "dns", NameServer.make(file(db, "dns")), new DatagramSocket(port)); } else { err.println("Unrecognized protocol: " + protocol); return; } // run the corresponding daemon new Thread(listener, service).start(); } // update the DNS final File ip = new File("ip.json"); if (ip.isFile()) { // find the ip address. Inet4Address addr = null; for (final Enumeration<NetworkInterface> j = NetworkInterface.getNetworkInterfaces(); j.hasMoreElements();) { final NetworkInterface x = j.nextElement(); for (final Enumeration<InetAddress> k = x.getInetAddresses(); k.hasMoreElements();) { final InetAddress a = k.nextElement(); if (a instanceof Inet4Address && !a.isLoopbackAddress()) { addr = (Inet4Address)a; break; } } } final InetAddress outer = null != addr ? addr : Loopback.addr; // notify the DNS nameserver final ClassLoader code = GenKey.class.getClassLoader(); final Browser browser = Browser.make( new Proxy(), new SecureRandom(), code, Concurrent.loop(Thread.currentThread().getThreadGroup(), "enqueue")); final Eventual _ = browser._; _.enqueue.run(new Task() { @SuppressWarnings("unchecked") public void run() throws Exception { final InputStream in = Filesystem.read(ip); final Type type = Variable.class; final Variable update = (Variable)new JSONDeserializer(). run("", browser.connect, code, in, PowerlessArray.array(type)).get(0); in.close(); System.err.println("Updating DNS to: " + outer.getHostAddress() + "..."); final ByteArray a = ByteArray.array(outer.getAddress()); update.put(new Resource(Resource.A, Resource.IN, 0, a)); } }); } }
diff --git a/workflow/src/main/java/org/apache/oodt/cas/workflow/engine/IterativeWorkflowProcessorThread.java b/workflow/src/main/java/org/apache/oodt/cas/workflow/engine/IterativeWorkflowProcessorThread.java index cc9a9374e..7385d4059 100644 --- a/workflow/src/main/java/org/apache/oodt/cas/workflow/engine/IterativeWorkflowProcessorThread.java +++ b/workflow/src/main/java/org/apache/oodt/cas/workflow/engine/IterativeWorkflowProcessorThread.java @@ -1,591 +1,592 @@ /** * 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.oodt.cas.workflow.engine; //OODT imports import org.apache.oodt.cas.resource.structs.Job; import org.apache.oodt.cas.resource.structs.exceptions.JobExecutionException; import org.apache.oodt.cas.resource.system.XmlRpcResourceManagerClient; import org.apache.oodt.cas.workflow.instrepo.WorkflowInstanceRepository; import org.apache.oodt.cas.workflow.metadata.CoreMetKeys; import org.apache.oodt.cas.workflow.structs.TaskJobInput; import org.apache.oodt.cas.workflow.structs.WorkflowInstance; import org.apache.oodt.cas.workflow.structs.WorkflowStatus; import org.apache.oodt.cas.workflow.structs.WorkflowTask; import org.apache.oodt.cas.workflow.structs.WorkflowTaskConfiguration; import org.apache.oodt.cas.workflow.structs.WorkflowTaskInstance; import org.apache.oodt.cas.workflow.structs.WorkflowCondition; import org.apache.oodt.cas.workflow.structs.WorkflowConditionInstance; import org.apache.oodt.cas.workflow.structs.exceptions.InstanceRepositoryException; import org.apache.oodt.cas.workflow.util.GenericWorkflowObjectFactory; import org.apache.oodt.cas.metadata.Metadata; import org.apache.oodt.commons.util.DateConvert; //JDK imports import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * An instance of the {@link WorkflowProcessorThread} that processes through an * iterative {@link WorkflowInstance}. This class keeps an <code>Iterator</code> * that allows it to move from one end of a sequential {@link Workflow} * processing pipeline to another. This class should only be used to process * science pipeline style {@link Workflow}s, i.e., those which resemble an * iterative processing pipelines, with no forks, or concurrent task executions. * * @author mattmann * @version $Revision$ * */ public class IterativeWorkflowProcessorThread implements WorkflowStatus, CoreMetKeys, Runnable { /* the default queue name if we're using resmgr job submission */ private static final String DEFAULT_QUEUE_NAME = "high"; /* an iterator representing the current task that we are on in the workflow */ private Iterator taskIterator = null; /* the workflow instance that this processor thread is processing */ private WorkflowInstance workflowInst = null; /* should our workflow processor thread start running? */ private boolean running = false; /* * the amount of seconds to wait inbetween checking for task pre-condition * satisfaction */ private long waitForConditionSatisfy = -1; /* our instance repository used to persist workflow instance info */ private WorkflowInstanceRepository instanceRepository = null; /* * our client to a resource manager: if null, local task execution will be * performed */ private XmlRpcResourceManagerClient rClient = null; /* polling wait for res mgr */ private long pollingWaitTime = 10L; /* * should our workflow processor thread pause, and not move onto the next * task? */ private boolean pause = false; /* our log stream */ private static Logger LOG = Logger .getLogger(IterativeWorkflowProcessorThread.class.getName()); private Map CONDITION_CACHE = new HashMap(); /* the parent workflow manager url that executed this processor thread */ private URL wmgrParentUrl = null; /* the currently executing jobId if we're using the resource manager */ private String currentJobId = null; public IterativeWorkflowProcessorThread(WorkflowInstance wInst, WorkflowInstanceRepository instRep, URL wParentUrl) { workflowInst = wInst; taskIterator = workflowInst.getWorkflow().getTasks().iterator(); this.instanceRepository = instRep; /* start out the gates running */ running = true; /* * get the amount of wait time inbetween checking for task pre-condition * satisfaction */ waitForConditionSatisfy = Long.getLong( "org.apache.oodt.cas.workflow.engine.preConditionWaitTime", 10) .longValue(); pollingWaitTime = Long.getLong( "org.apache.oodt.cas.workflow.engine.resourcemgr.pollingWaitTime", 10) .longValue(); wmgrParentUrl = wParentUrl; } /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ public void run() { /* * okay, we got into the run method, mark the start date time for the * workflow instance here */ String startDateTimeIsoStr = DateConvert.isoFormat(new Date()); workflowInst.setStartDateTimeIsoStr(startDateTimeIsoStr); // persist it persistWorkflowInstance(); while (running && taskIterator.hasNext()) { if (pause) { LOG.log(Level.FINE, "IterativeWorkflowProcessorThread: Skipping execution: Paused: CurrentTask: " + getTaskNameById(workflowInst.getCurrentTaskId())); continue; } WorkflowTask task = (WorkflowTask) taskIterator.next(); workflowInst.setCurrentTaskId(task.getTaskId()); // now persist it persistWorkflowInstance(); // check to see if req met fields are present // if they aren't, set the status to METERROR, and then fail if (!checkTaskRequiredMetadata(task, this.workflowInst.getSharedContext())) { this.workflowInst.setStatus(METADATA_MISSING); persistWorkflowInstance(); // now break out of this run loop return; } // this is where the pre-conditions come in // only execute the below code when it's passed all of its // pre-conditions if (task.getConditions() != null) { while (!satisfied(task.getConditions(), task.getTaskId()) && !isStopped()) { // if we're not paused, go ahead and pause us now if (!isPaused()) { pause(); } LOG.log(Level.FINEST, "Pre-conditions for task: " + task.getTaskName() + " unsatisfied: waiting: " + waitForConditionSatisfy + " seconds before checking again."); try { Thread.currentThread().sleep(waitForConditionSatisfy * 1000); } catch (InterruptedException ignore) { } // check to see if we've been resumed, if so, break // the loop and start if (!isPaused()) { break; } } // check to see if we've been killed if (isStopped()) { break; } // un pause us (if needed) if (isPaused()) { resume(); } } // task execution LOG.log( Level.FINEST, "IterativeWorkflowProcessorThread: Executing task: " + task.getTaskName()); WorkflowTaskInstance taskInstance = GenericWorkflowObjectFactory .getTaskObjectFromClassName(task.getTaskInstanceClassName()); // add the TaskId and the JobId and ProcessingNode // TODO: unfake the JobId workflowInst.getSharedContext() .replaceMetadata(TASK_ID, task.getTaskId()); workflowInst.getSharedContext().replaceMetadata(WORKFLOW_INST_ID, workflowInst.getId()); workflowInst.getSharedContext().replaceMetadata(JOB_ID, workflowInst.getId()); workflowInst.getSharedContext().replaceMetadata(PROCESSING_NODE, getHostname()); workflowInst.getSharedContext().replaceMetadata(WORKFLOW_MANAGER_URL, this.wmgrParentUrl.toString()); if (rClient != null) { // build up the Job // and the Job Input Job taskJob = new Job(); taskJob.setName(task.getTaskId()); taskJob .setJobInstanceClassName("org.apache.oodt.cas.workflow.structs.TaskJob"); taskJob .setJobInputClassName("org.apache.oodt.cas.workflow.structs.TaskJobInput"); - taskJob.setLoadValue(new Integer(2)); + taskJob.setLoadValue(task.getTaskConfig().getProperty(TASK_LOAD) != null ? + Integer.parseInt(task.getTaskConfig().getProperty(TASK_LOAD)):new Integer(2)); taskJob .setQueueName(task.getTaskConfig().getProperty(QUEUE_NAME) != null ? task .getTaskConfig().getProperty(QUEUE_NAME) : DEFAULT_QUEUE_NAME); TaskJobInput in = new TaskJobInput(); in.setDynMetadata(workflowInst.getSharedContext()); in.setTaskConfig(task.getTaskConfig()); in.setWorkflowTaskInstanceClassName(task.getTaskInstanceClassName()); workflowInst.setStatus(RESMGR_SUBMIT); persistWorkflowInstance(); try { // this is * NOT * a blocking operation so when it returns // the job may not actually have finished executing // so we go into a waiting/sleep behavior using the passed // back job id to wait until the job has actually finished // executing this.currentJobId = rClient.submitJob(taskJob, in); while (!safeCheckJobComplete(this.currentJobId) && !isStopped()) { // sleep for 5 seconds then come back // and check again try { Thread.currentThread().sleep(pollingWaitTime * 1000); } catch (InterruptedException ignore) { } } // okay job is done: TODO: fix this hack // the task update time was set remotely // by remote task, so let's read it now // from the instRepo (which will have the updated // time) if (isStopped()) { // this means that this workflow was killed, so // gracefully exit break; } WorkflowInstance updatedInst = null; try { updatedInst = instanceRepository .getWorkflowInstanceById(workflowInst.getId()); workflowInst = updatedInst; } catch (InstanceRepositoryException e) { e.printStackTrace(); LOG.log(Level.WARNING, "Unable to get " + "updated workflow " + "instance record " + "when executing remote job: Message: " + e.getMessage()); } } catch (JobExecutionException e) { LOG.log(Level.WARNING, "Job execution exception using resource manager to execute job: Message: " + e.getMessage()); } } else { // we started, so mark it workflowInst.setStatus(STARTED); // go ahead and persist the workflow instance, after we // save the current task start date time String currentTaskIsoStartDateTimeStr = DateConvert .isoFormat(new Date()); workflowInst .setCurrentTaskStartDateTimeIsoStr(currentTaskIsoStartDateTimeStr); workflowInst.setCurrentTaskEndDateTimeIsoStr(null); /* * clear this out * until it's ready */ persistWorkflowInstance(); executeTaskLocally(taskInstance, workflowInst.getSharedContext(), task.getTaskConfig(), task.getTaskName()); String currentTaskIsoEndDateTimeStr = DateConvert.isoFormat(new Date()); workflowInst .setCurrentTaskEndDateTimeIsoStr(currentTaskIsoEndDateTimeStr); persistWorkflowInstance(); } LOG.log( Level.FINEST, "IterativeWorkflowProcessorThread: Completed task: " + task.getTaskName()); } LOG.log(Level.FINEST, "IterativeWorkflowProcessorThread: Completed workflow: " + workflowInst.getWorkflow().getName()); if (!isStopped()) { stop(); } } public WorkflowInstance getWorkflowInstance() { return workflowInst; } public synchronized void stop() { running = false; // if the resource manager is active // then kill the current job there if (this.rClient != null && this.currentJobId != null) { if (!this.rClient.killJob(this.currentJobId)) { LOG.log(Level.WARNING, "Attempt to kill " + "current resmgr job: [" + this.currentJobId + "]: failed"); } } workflowInst.setStatus(FINISHED); String isoEndDateTimeStr = DateConvert.isoFormat(new Date()); workflowInst.setEndDateTimeIsoStr(isoEndDateTimeStr); persistWorkflowInstance(); } public synchronized void resume() { pause = false; workflowInst.setStatus(STARTED); persistWorkflowInstance(); } public synchronized void pause() { pause = true; workflowInst.setStatus(PAUSED); persistWorkflowInstance(); } /** * @return True if the WorkflowInstance managed by this processor is paused. */ public boolean isPaused() { return pause == true; } public boolean isStopped() { return !running; } /** * @return Returns the fCurrentTaskId. */ public String getCurrentTaskId() { return workflowInst.getCurrentTaskId(); } /** * @param workflowInst * The fWorkflowInst to set. */ public void setWorkflowInst(WorkflowInstance workflowInst) { this.workflowInst = workflowInst; } /** * @return Returns the waitForConditionSatisfy. */ public long getWaitforConditionSatisfy() { return waitForConditionSatisfy; } /** * @param waitforConditionSatisfy * The waitForConditionSatisfy to set. */ public void setWaitforConditionSatisfy(long waitforConditionSatisfy) { this.waitForConditionSatisfy = waitforConditionSatisfy; } /** * @return the instRep */ public WorkflowInstanceRepository getInstanceRepository() { return instanceRepository; } /** * @param instRep * the instRep to set */ public void setInstanceRepository(WorkflowInstanceRepository instRep) { this.instanceRepository = instRep; } /** * @return the rClient */ public XmlRpcResourceManagerClient getRClient() { return rClient; } /** * @param client * the rClient to set */ public void setRClient(XmlRpcResourceManagerClient client) { rClient = client; if (rClient != null) { LOG.log(Level.INFO, "Resource Manager Job Submission enabled to: [" + rClient.getResMgrUrl() + "]"); } } /** * @return the wmgrParentUrl */ public URL getWmgrParentUrl() { return wmgrParentUrl; } /** * @param wmgrParentUrl * the wmgrParentUrl to set */ public void setWmgrParentUrl(URL wmgrParentUrl) { this.wmgrParentUrl = wmgrParentUrl; } private boolean checkTaskRequiredMetadata(WorkflowTask task, Metadata dynMetadata) { if (task.getRequiredMetFields() == null || (task.getRequiredMetFields() != null && task.getRequiredMetFields() .size() == 0)) { LOG.log(Level.INFO, "Task: [" + task.getTaskName() + "] has no required metadata fields"); return true; /* no required metadata, so we're fine */ } for (Iterator i = task.getRequiredMetFields().iterator(); i.hasNext();) { String reqField = (String) i.next(); if (!dynMetadata.containsKey(reqField)) { LOG.log(Level.SEVERE, "Checking metadata key: [" + reqField + "] for task: [" + task.getTaskName() + "]: failed: aborting workflow"); return false; } } LOG.log(Level.INFO, "All required metadata fields present for task: [" + task.getTaskName() + "]"); return true; } private String getTaskNameById(String taskId) { for (Iterator i = workflowInst.getWorkflow().getTasks().iterator(); i .hasNext();) { WorkflowTask task = (WorkflowTask) i.next(); if (task.getTaskId().equals(taskId)) { return task.getTaskName(); } } return null; } private boolean satisfied(List conditionList, String taskId) { for (Iterator i = conditionList.iterator(); i.hasNext();) { WorkflowCondition c = (WorkflowCondition) i.next(); WorkflowConditionInstance cInst = null; // see if we've already cached this condition instance if (CONDITION_CACHE.get(taskId) != null) { HashMap conditionMap = (HashMap) CONDITION_CACHE.get(taskId); /* * okay we have some conditions cached for this task, see if we have the * one we need */ if (conditionMap.get(c.getConditionId()) != null) { cInst = (WorkflowConditionInstance) conditionMap.get(c .getConditionId()); } /* if not, then go ahead and create it and cache it */ else { cInst = GenericWorkflowObjectFactory .getConditionObjectFromClassName(c .getConditionInstanceClassName()); conditionMap.put(c.getConditionId(), cInst); } } /* no conditions cached yet, so set everything up */ else { HashMap conditionMap = new HashMap(); cInst = GenericWorkflowObjectFactory.getConditionObjectFromClassName(c .getConditionInstanceClassName()); conditionMap.put(c.getConditionId(), cInst); CONDITION_CACHE.put(taskId, conditionMap); } // actually perform the evaluation if (!cInst.evaluate(workflowInst.getSharedContext(), c.getTaskConfig())) { return false; } } return true; } private String getHostname() { try { // Get hostname by textual representation of IP address InetAddress addr = InetAddress.getLocalHost(); // Get the host name String hostname = addr.getHostName(); return hostname; } catch (UnknownHostException e) { } return null; } private void persistWorkflowInstance() { try { instanceRepository.updateWorkflowInstance(workflowInst); } catch (InstanceRepositoryException e) { LOG.log(Level.WARNING, "Exception persisting workflow instance: [" + workflowInst.getId() + "]: Message: " + e.getMessage()); } } private void executeTaskLocally(WorkflowTaskInstance instance, Metadata met, WorkflowTaskConfiguration cfg, String taskName) { try { LOG.log(Level.INFO, "Executing task: [" + taskName + "] locally"); instance.run(met, cfg); } catch (Exception e) { e.printStackTrace(); LOG.log(Level.WARNING, "Exception executing task: [" + taskName + "] locally: Message: " + e.getMessage()); } } private boolean safeCheckJobComplete(String jobId) { try { return rClient.isJobComplete(jobId); } catch (Exception e) { LOG.log(Level.WARNING, "Exception checking completion status for job: [" + jobId + "]: Messsage: " + e.getMessage()); return false; } } }
true
true
public void run() { /* * okay, we got into the run method, mark the start date time for the * workflow instance here */ String startDateTimeIsoStr = DateConvert.isoFormat(new Date()); workflowInst.setStartDateTimeIsoStr(startDateTimeIsoStr); // persist it persistWorkflowInstance(); while (running && taskIterator.hasNext()) { if (pause) { LOG.log(Level.FINE, "IterativeWorkflowProcessorThread: Skipping execution: Paused: CurrentTask: " + getTaskNameById(workflowInst.getCurrentTaskId())); continue; } WorkflowTask task = (WorkflowTask) taskIterator.next(); workflowInst.setCurrentTaskId(task.getTaskId()); // now persist it persistWorkflowInstance(); // check to see if req met fields are present // if they aren't, set the status to METERROR, and then fail if (!checkTaskRequiredMetadata(task, this.workflowInst.getSharedContext())) { this.workflowInst.setStatus(METADATA_MISSING); persistWorkflowInstance(); // now break out of this run loop return; } // this is where the pre-conditions come in // only execute the below code when it's passed all of its // pre-conditions if (task.getConditions() != null) { while (!satisfied(task.getConditions(), task.getTaskId()) && !isStopped()) { // if we're not paused, go ahead and pause us now if (!isPaused()) { pause(); } LOG.log(Level.FINEST, "Pre-conditions for task: " + task.getTaskName() + " unsatisfied: waiting: " + waitForConditionSatisfy + " seconds before checking again."); try { Thread.currentThread().sleep(waitForConditionSatisfy * 1000); } catch (InterruptedException ignore) { } // check to see if we've been resumed, if so, break // the loop and start if (!isPaused()) { break; } } // check to see if we've been killed if (isStopped()) { break; } // un pause us (if needed) if (isPaused()) { resume(); } } // task execution LOG.log( Level.FINEST, "IterativeWorkflowProcessorThread: Executing task: " + task.getTaskName()); WorkflowTaskInstance taskInstance = GenericWorkflowObjectFactory .getTaskObjectFromClassName(task.getTaskInstanceClassName()); // add the TaskId and the JobId and ProcessingNode // TODO: unfake the JobId workflowInst.getSharedContext() .replaceMetadata(TASK_ID, task.getTaskId()); workflowInst.getSharedContext().replaceMetadata(WORKFLOW_INST_ID, workflowInst.getId()); workflowInst.getSharedContext().replaceMetadata(JOB_ID, workflowInst.getId()); workflowInst.getSharedContext().replaceMetadata(PROCESSING_NODE, getHostname()); workflowInst.getSharedContext().replaceMetadata(WORKFLOW_MANAGER_URL, this.wmgrParentUrl.toString()); if (rClient != null) { // build up the Job // and the Job Input Job taskJob = new Job(); taskJob.setName(task.getTaskId()); taskJob .setJobInstanceClassName("org.apache.oodt.cas.workflow.structs.TaskJob"); taskJob .setJobInputClassName("org.apache.oodt.cas.workflow.structs.TaskJobInput"); taskJob.setLoadValue(new Integer(2)); taskJob .setQueueName(task.getTaskConfig().getProperty(QUEUE_NAME) != null ? task .getTaskConfig().getProperty(QUEUE_NAME) : DEFAULT_QUEUE_NAME); TaskJobInput in = new TaskJobInput(); in.setDynMetadata(workflowInst.getSharedContext()); in.setTaskConfig(task.getTaskConfig()); in.setWorkflowTaskInstanceClassName(task.getTaskInstanceClassName()); workflowInst.setStatus(RESMGR_SUBMIT); persistWorkflowInstance(); try { // this is * NOT * a blocking operation so when it returns // the job may not actually have finished executing // so we go into a waiting/sleep behavior using the passed // back job id to wait until the job has actually finished // executing this.currentJobId = rClient.submitJob(taskJob, in); while (!safeCheckJobComplete(this.currentJobId) && !isStopped()) { // sleep for 5 seconds then come back // and check again try { Thread.currentThread().sleep(pollingWaitTime * 1000); } catch (InterruptedException ignore) { } } // okay job is done: TODO: fix this hack // the task update time was set remotely // by remote task, so let's read it now // from the instRepo (which will have the updated // time) if (isStopped()) { // this means that this workflow was killed, so // gracefully exit break; } WorkflowInstance updatedInst = null; try { updatedInst = instanceRepository .getWorkflowInstanceById(workflowInst.getId()); workflowInst = updatedInst; } catch (InstanceRepositoryException e) { e.printStackTrace(); LOG.log(Level.WARNING, "Unable to get " + "updated workflow " + "instance record " + "when executing remote job: Message: " + e.getMessage()); } } catch (JobExecutionException e) { LOG.log(Level.WARNING, "Job execution exception using resource manager to execute job: Message: " + e.getMessage()); } } else { // we started, so mark it workflowInst.setStatus(STARTED); // go ahead and persist the workflow instance, after we // save the current task start date time String currentTaskIsoStartDateTimeStr = DateConvert .isoFormat(new Date()); workflowInst .setCurrentTaskStartDateTimeIsoStr(currentTaskIsoStartDateTimeStr); workflowInst.setCurrentTaskEndDateTimeIsoStr(null); /* * clear this out * until it's ready */ persistWorkflowInstance(); executeTaskLocally(taskInstance, workflowInst.getSharedContext(), task.getTaskConfig(), task.getTaskName()); String currentTaskIsoEndDateTimeStr = DateConvert.isoFormat(new Date()); workflowInst .setCurrentTaskEndDateTimeIsoStr(currentTaskIsoEndDateTimeStr); persistWorkflowInstance(); } LOG.log( Level.FINEST, "IterativeWorkflowProcessorThread: Completed task: " + task.getTaskName()); } LOG.log(Level.FINEST, "IterativeWorkflowProcessorThread: Completed workflow: " + workflowInst.getWorkflow().getName()); if (!isStopped()) { stop(); } }
public void run() { /* * okay, we got into the run method, mark the start date time for the * workflow instance here */ String startDateTimeIsoStr = DateConvert.isoFormat(new Date()); workflowInst.setStartDateTimeIsoStr(startDateTimeIsoStr); // persist it persistWorkflowInstance(); while (running && taskIterator.hasNext()) { if (pause) { LOG.log(Level.FINE, "IterativeWorkflowProcessorThread: Skipping execution: Paused: CurrentTask: " + getTaskNameById(workflowInst.getCurrentTaskId())); continue; } WorkflowTask task = (WorkflowTask) taskIterator.next(); workflowInst.setCurrentTaskId(task.getTaskId()); // now persist it persistWorkflowInstance(); // check to see if req met fields are present // if they aren't, set the status to METERROR, and then fail if (!checkTaskRequiredMetadata(task, this.workflowInst.getSharedContext())) { this.workflowInst.setStatus(METADATA_MISSING); persistWorkflowInstance(); // now break out of this run loop return; } // this is where the pre-conditions come in // only execute the below code when it's passed all of its // pre-conditions if (task.getConditions() != null) { while (!satisfied(task.getConditions(), task.getTaskId()) && !isStopped()) { // if we're not paused, go ahead and pause us now if (!isPaused()) { pause(); } LOG.log(Level.FINEST, "Pre-conditions for task: " + task.getTaskName() + " unsatisfied: waiting: " + waitForConditionSatisfy + " seconds before checking again."); try { Thread.currentThread().sleep(waitForConditionSatisfy * 1000); } catch (InterruptedException ignore) { } // check to see if we've been resumed, if so, break // the loop and start if (!isPaused()) { break; } } // check to see if we've been killed if (isStopped()) { break; } // un pause us (if needed) if (isPaused()) { resume(); } } // task execution LOG.log( Level.FINEST, "IterativeWorkflowProcessorThread: Executing task: " + task.getTaskName()); WorkflowTaskInstance taskInstance = GenericWorkflowObjectFactory .getTaskObjectFromClassName(task.getTaskInstanceClassName()); // add the TaskId and the JobId and ProcessingNode // TODO: unfake the JobId workflowInst.getSharedContext() .replaceMetadata(TASK_ID, task.getTaskId()); workflowInst.getSharedContext().replaceMetadata(WORKFLOW_INST_ID, workflowInst.getId()); workflowInst.getSharedContext().replaceMetadata(JOB_ID, workflowInst.getId()); workflowInst.getSharedContext().replaceMetadata(PROCESSING_NODE, getHostname()); workflowInst.getSharedContext().replaceMetadata(WORKFLOW_MANAGER_URL, this.wmgrParentUrl.toString()); if (rClient != null) { // build up the Job // and the Job Input Job taskJob = new Job(); taskJob.setName(task.getTaskId()); taskJob .setJobInstanceClassName("org.apache.oodt.cas.workflow.structs.TaskJob"); taskJob .setJobInputClassName("org.apache.oodt.cas.workflow.structs.TaskJobInput"); taskJob.setLoadValue(task.getTaskConfig().getProperty(TASK_LOAD) != null ? Integer.parseInt(task.getTaskConfig().getProperty(TASK_LOAD)):new Integer(2)); taskJob .setQueueName(task.getTaskConfig().getProperty(QUEUE_NAME) != null ? task .getTaskConfig().getProperty(QUEUE_NAME) : DEFAULT_QUEUE_NAME); TaskJobInput in = new TaskJobInput(); in.setDynMetadata(workflowInst.getSharedContext()); in.setTaskConfig(task.getTaskConfig()); in.setWorkflowTaskInstanceClassName(task.getTaskInstanceClassName()); workflowInst.setStatus(RESMGR_SUBMIT); persistWorkflowInstance(); try { // this is * NOT * a blocking operation so when it returns // the job may not actually have finished executing // so we go into a waiting/sleep behavior using the passed // back job id to wait until the job has actually finished // executing this.currentJobId = rClient.submitJob(taskJob, in); while (!safeCheckJobComplete(this.currentJobId) && !isStopped()) { // sleep for 5 seconds then come back // and check again try { Thread.currentThread().sleep(pollingWaitTime * 1000); } catch (InterruptedException ignore) { } } // okay job is done: TODO: fix this hack // the task update time was set remotely // by remote task, so let's read it now // from the instRepo (which will have the updated // time) if (isStopped()) { // this means that this workflow was killed, so // gracefully exit break; } WorkflowInstance updatedInst = null; try { updatedInst = instanceRepository .getWorkflowInstanceById(workflowInst.getId()); workflowInst = updatedInst; } catch (InstanceRepositoryException e) { e.printStackTrace(); LOG.log(Level.WARNING, "Unable to get " + "updated workflow " + "instance record " + "when executing remote job: Message: " + e.getMessage()); } } catch (JobExecutionException e) { LOG.log(Level.WARNING, "Job execution exception using resource manager to execute job: Message: " + e.getMessage()); } } else { // we started, so mark it workflowInst.setStatus(STARTED); // go ahead and persist the workflow instance, after we // save the current task start date time String currentTaskIsoStartDateTimeStr = DateConvert .isoFormat(new Date()); workflowInst .setCurrentTaskStartDateTimeIsoStr(currentTaskIsoStartDateTimeStr); workflowInst.setCurrentTaskEndDateTimeIsoStr(null); /* * clear this out * until it's ready */ persistWorkflowInstance(); executeTaskLocally(taskInstance, workflowInst.getSharedContext(), task.getTaskConfig(), task.getTaskName()); String currentTaskIsoEndDateTimeStr = DateConvert.isoFormat(new Date()); workflowInst .setCurrentTaskEndDateTimeIsoStr(currentTaskIsoEndDateTimeStr); persistWorkflowInstance(); } LOG.log( Level.FINEST, "IterativeWorkflowProcessorThread: Completed task: " + task.getTaskName()); } LOG.log(Level.FINEST, "IterativeWorkflowProcessorThread: Completed workflow: " + workflowInst.getWorkflow().getName()); if (!isStopped()) { stop(); } }
diff --git a/java/src/sorting/HeapSort.java b/java/src/sorting/HeapSort.java index e002c2e..cff6019 100644 --- a/java/src/sorting/HeapSort.java +++ b/java/src/sorting/HeapSort.java @@ -1,22 +1,22 @@ package sorting; import java.util.Comparator; import exceptions.EmptyHeapException; public class HeapSort { public static <T> T[] heapSort(T[] array, Comparator<T> comparator) { Heap<T> heap = new SimpleHeapImpl<T>(array, comparator); for (int index = array.length - 1; !heap.isEmpty(); index--) { try { array[index] = heap.pop(); } catch (EmptyHeapException e) { - // This should never occur; + // This should never occur throw new RuntimeException(e); } } return array; } }
true
true
public static <T> T[] heapSort(T[] array, Comparator<T> comparator) { Heap<T> heap = new SimpleHeapImpl<T>(array, comparator); for (int index = array.length - 1; !heap.isEmpty(); index--) { try { array[index] = heap.pop(); } catch (EmptyHeapException e) { // This should never occur; throw new RuntimeException(e); } } return array; }
public static <T> T[] heapSort(T[] array, Comparator<T> comparator) { Heap<T> heap = new SimpleHeapImpl<T>(array, comparator); for (int index = array.length - 1; !heap.isEmpty(); index--) { try { array[index] = heap.pop(); } catch (EmptyHeapException e) { // This should never occur throw new RuntimeException(e); } } return array; }
diff --git a/emir-core/src/main/java/eu/emi/emir/validator/RegistrationValidator.java b/emir-core/src/main/java/eu/emi/emir/validator/RegistrationValidator.java index 3431390..7d9d634 100644 --- a/emir-core/src/main/java/eu/emi/emir/validator/RegistrationValidator.java +++ b/emir-core/src/main/java/eu/emi/emir/validator/RegistrationValidator.java @@ -1,226 +1,226 @@ /** * */ package eu.emi.emir.validator; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import org.apache.log4j.Logger; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import eu.emi.emir.EMIRServer; import eu.emi.emir.ServerProperties; import eu.emi.emir.client.ServiceBasicAttributeNames; import eu.emi.emir.client.util.Log; import eu.emi.emir.exception.InvalidServiceDescriptionException; import eu.emi.emir.util.ServiceUtil; /** * @author a.memon * */ public class RegistrationValidator extends AbstractInfoValidator { private static Logger logger = Log.getLogger(Log.EMIR_CORE, RegistrationValidator.class); /* * (non-Javadoc) * * @see eu.emi.dsr.info.AbstractInformationValidator#checkUrl() */ @Override Boolean checkUrl() { try { if ((jo.has(ServiceBasicAttributeNames.SERVICE_ENDPOINT_URL .getAttributeName())) && (jo.getString(ServiceBasicAttributeNames.SERVICE_ENDPOINT_URL .getAttributeName()).isEmpty())) { logger.error("Invalid url"); return false; } valid = true; } catch (JSONException e) { Log.logException("",e); return false; } return true; } /* * (non-Javadoc) * * @see eu.emi.dsr.info.AbstractInformationValidator#checkDateTypes() */ @Override Boolean checkDateTypes() { // the format should be utc for (Iterator<?> iterator = jo.keys(); iterator.hasNext();) { String key = null; try { key = (String) iterator.next(); if ((jo.get(key) instanceof JSONObject) && (jo.getJSONObject(key).has("$date"))) { ServiceUtil.toUTCFormat(jo.getJSONObject(key).getString( "$date")); valid = true; } // some of the glue2 attributes should be defined as date // if // ((ServiceBasicAttributeNames.valueOf(key).getAttributeType() // == Date.class) // && (jo.get(key) instanceof JSONObject) // && (jo.getJSONObject(key).has("$date"))) { // valid = true; // } } catch (Exception e) { Log.logException("",new InvalidServiceDescriptionException( "invalid date format for the key: " + key, e)); valid = false; return false; } } for (ServiceBasicAttributeNames s : ServiceBasicAttributeNames.values()) { if (s.getAttributeType() == Date.class) { try { if (jo.has(s.getAttributeName())) { if ((jo.get(s.getAttributeName()) instanceof JSONObject) && (jo.getJSONObject(s.getAttributeName()) .has("$date"))) { // do nothing } else { return false; } } } catch (JSONException e) { return false; } } } return true; } /* * (non-Javadoc) * * @see eu.emi.dsr.info.AbstractInformationValidator#checkExpiryTime() */ @Override Boolean checkExpiryTime() { try { if (jo.has(ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName())) { if (jo.get(ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName()) instanceof JSONObject) { if (jo.getJSONObject( ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName()).has("$date")) { Date d = ServiceUtil .toUTCFormat(jo .getJSONObject( ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName()) .getString("$date")); Calendar c = Calendar.getInstance(); c.setTime(d); //creating the max expiry time calendar Calendar cMax = Calendar.getInstance(); int max_def=0; try { - max_def=EMIRServer.getServerProperties().getIntValue(ServerProperties.PROP_RECORD_MAXIMUM); + max_def=EMIRServer.getServerProperties().getIntValue(ServerProperties.PROP_RECORD_EXPIRY_MAXIMUM); } catch (NumberFormatException e) { logger.warn("Error in reading the configuration property of maximum default expiry days - setting the value to 730 days"); max_def = 730; } cMax.add(Calendar.DATE, max_def); if ((cMax.compareTo(c) < 0)) { logger.error("Failed to validate the service information: Given service expiry- "+ c.getTime() +", exceeds the default maximum- " + cMax.getTime()); return false; } Calendar now = Calendar.getInstance(); if (c.compareTo(Calendar.getInstance())<=0) { logger.error("Failed to validate the service information: Given service expiry- "+ c.getTime() +", mustn't be less than or equal-to current time - " + now.getTime()); return false; } } } else { logger.error("Failed to validate the service information: invalid date format for the key: " + ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName()); valid = false; return false; } } // else { // if expiry is not mentioned then will be added and set to 6 // months from now // Calendar c = Calendar.getInstance(); // c.add(c.MONTH, 6); // JSONObject j = new JSONObject(); // j.put("$date", ServiceUtil.toUTCFormat(c.getTime())); // jo.put(ServiceBasicAttributeNames.SERVICE_EXPIRE_ON // .getAttributeName(), j); // jo = DateUtil.setExpiryTime(jo, Integer.valueOf(DSRServer.getProperty(ServerConstants.REGISTRY_EXPIRY_DEFAULT, "1"))); // valid = true; // logger.error("missing expiry, added new field " // + ServiceBasicAttributeNames.SERVICE_EXPIRE_ON // .getAttributeName()); // } } catch (Exception e) { Log.logException("Invalid expiry time", e); return false; } return true; } /* * (non-Javadoc) * * @see eu.emi.dsr.validator.AbstractInfoValidator#checkArrays() */ @Override boolean checkArrays() { for (ServiceBasicAttributeNames s : ServiceBasicAttributeNames.values()) { if (s.getAttributeType() == JSONArray.class) { try { if (jo.has(s.getAttributeName())) { if (jo.get(s.getAttributeName()) instanceof JSONArray) { // do nothing } else { return false; } } } catch (JSONException e) { Log.logException( s.getAttributeName() + " is an array-it should be defined as [\"object\",\"object\"...]", e); return false; } } } return true; } }
true
true
Boolean checkExpiryTime() { try { if (jo.has(ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName())) { if (jo.get(ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName()) instanceof JSONObject) { if (jo.getJSONObject( ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName()).has("$date")) { Date d = ServiceUtil .toUTCFormat(jo .getJSONObject( ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName()) .getString("$date")); Calendar c = Calendar.getInstance(); c.setTime(d); //creating the max expiry time calendar Calendar cMax = Calendar.getInstance(); int max_def=0; try { max_def=EMIRServer.getServerProperties().getIntValue(ServerProperties.PROP_RECORD_MAXIMUM); } catch (NumberFormatException e) { logger.warn("Error in reading the configuration property of maximum default expiry days - setting the value to 730 days"); max_def = 730; } cMax.add(Calendar.DATE, max_def); if ((cMax.compareTo(c) < 0)) { logger.error("Failed to validate the service information: Given service expiry- "+ c.getTime() +", exceeds the default maximum- " + cMax.getTime()); return false; } Calendar now = Calendar.getInstance(); if (c.compareTo(Calendar.getInstance())<=0) { logger.error("Failed to validate the service information: Given service expiry- "+ c.getTime() +", mustn't be less than or equal-to current time - " + now.getTime()); return false; } } } else { logger.error("Failed to validate the service information: invalid date format for the key: " + ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName()); valid = false; return false; } } // else { // if expiry is not mentioned then will be added and set to 6 // months from now // Calendar c = Calendar.getInstance(); // c.add(c.MONTH, 6); // JSONObject j = new JSONObject(); // j.put("$date", ServiceUtil.toUTCFormat(c.getTime())); // jo.put(ServiceBasicAttributeNames.SERVICE_EXPIRE_ON // .getAttributeName(), j); // jo = DateUtil.setExpiryTime(jo, Integer.valueOf(DSRServer.getProperty(ServerConstants.REGISTRY_EXPIRY_DEFAULT, "1"))); // valid = true; // logger.error("missing expiry, added new field " // + ServiceBasicAttributeNames.SERVICE_EXPIRE_ON // .getAttributeName()); // } } catch (Exception e) { Log.logException("Invalid expiry time", e); return false; } return true; }
Boolean checkExpiryTime() { try { if (jo.has(ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName())) { if (jo.get(ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName()) instanceof JSONObject) { if (jo.getJSONObject( ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName()).has("$date")) { Date d = ServiceUtil .toUTCFormat(jo .getJSONObject( ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName()) .getString("$date")); Calendar c = Calendar.getInstance(); c.setTime(d); //creating the max expiry time calendar Calendar cMax = Calendar.getInstance(); int max_def=0; try { max_def=EMIRServer.getServerProperties().getIntValue(ServerProperties.PROP_RECORD_EXPIRY_MAXIMUM); } catch (NumberFormatException e) { logger.warn("Error in reading the configuration property of maximum default expiry days - setting the value to 730 days"); max_def = 730; } cMax.add(Calendar.DATE, max_def); if ((cMax.compareTo(c) < 0)) { logger.error("Failed to validate the service information: Given service expiry- "+ c.getTime() +", exceeds the default maximum- " + cMax.getTime()); return false; } Calendar now = Calendar.getInstance(); if (c.compareTo(Calendar.getInstance())<=0) { logger.error("Failed to validate the service information: Given service expiry- "+ c.getTime() +", mustn't be less than or equal-to current time - " + now.getTime()); return false; } } } else { logger.error("Failed to validate the service information: invalid date format for the key: " + ServiceBasicAttributeNames.SERVICE_EXPIRE_ON .getAttributeName()); valid = false; return false; } } // else { // if expiry is not mentioned then will be added and set to 6 // months from now // Calendar c = Calendar.getInstance(); // c.add(c.MONTH, 6); // JSONObject j = new JSONObject(); // j.put("$date", ServiceUtil.toUTCFormat(c.getTime())); // jo.put(ServiceBasicAttributeNames.SERVICE_EXPIRE_ON // .getAttributeName(), j); // jo = DateUtil.setExpiryTime(jo, Integer.valueOf(DSRServer.getProperty(ServerConstants.REGISTRY_EXPIRY_DEFAULT, "1"))); // valid = true; // logger.error("missing expiry, added new field " // + ServiceBasicAttributeNames.SERVICE_EXPIRE_ON // .getAttributeName()); // } } catch (Exception e) { Log.logException("Invalid expiry time", e); return false; } return true; }
diff --git a/src/source/ProofTree.java b/src/source/ProofTree.java index 21c69f6..d18c524 100644 --- a/src/source/ProofTree.java +++ b/src/source/ProofTree.java @@ -1,362 +1,362 @@ package source; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; import source.Token.Type; //import com.sun.tools.example.debug.bdi.MethodNotFoundException; public class ProofTree extends BinaryTree<Token> { protected final boolean debug = false; static final String kErrorVariable = "Variable exception"; static final String kErrorOperator = "Operator exception"; static final String kErrorParenthesis = "Parenthesis Exception"; static final String kErrorUnary = "Unary Operator Exception"; static final String kErrorMissing = "Missing argument"; static final String kExpressionInvalid = "Expression Exception"; public ProofTree() { super(); } public ProofTree(ProofNode root) { super(root); } private static boolean isValidExpression(Stack<Token.Type> expressionStack) { // for (Iterator<Token.Type> iter = expressionStack.iterator(); iter.hasNext();) // { // System.out.println(iter.next()); // } if (expressionStack.size() != 3) return false; return true; } private static Queue<Token> infixToPostfix(ArrayList<Token> tokenArray) throws IllegalLineException { Stack<Token> operatorStack = new Stack<Token>(); Queue<Token> linkedList = new LinkedList<Token>(); Stack<Token.Type> errorStack = new Stack<Token.Type>(); Stack<Token.Type> parenthesisStack = new Stack<Token.Type>(); Stack<Stack<Token.Type>> expressionStack = new Stack<Stack<Token.Type>>(); Token oldToken = null; Stack<Token.Type> currentTokenExpressionStack = null; for (Iterator<Token> iter = tokenArray.iterator(); iter.hasNext();) { Token token = iter.next(); if (token.getType() == Token.Type.OPEN_PARENTHESIS) { parenthesisStack.push(Token.Type.OPEN_PARENTHESIS); operatorStack.push(token); Stack<Token.Type> tokenExpressionStack = new Stack<Token.Type>(); expressionStack.push(tokenExpressionStack); currentTokenExpressionStack = tokenExpressionStack; } else if (token.getType() == Token.Type.CLOSE_PARENTHESIS) { if (parenthesisStack.empty() == true) throw new IllegalLineException(kErrorParenthesis); Token.Type type = parenthesisStack.pop(); if (type != Token.Type.OPEN_PARENTHESIS) throw new IllegalLineException(kErrorParenthesis); while (!operatorStack.isEmpty()) { Token currentToken = operatorStack.pop(); if (currentToken.getType() == Token.Type.OPEN_PARENTHESIS) { break; } linkedList.add(currentToken); } if (isValidExpression(currentTokenExpressionStack)) { expressionStack.pop(); if (expressionStack.empty()) currentTokenExpressionStack = null; else { currentTokenExpressionStack = expressionStack.lastElement(); currentTokenExpressionStack.push(Token.Type.VARIABLE); } } else throw new IllegalLineException(kExpressionInvalid); } else if (token.getType() == Token.Type.VARIABLE) { linkedList.add(token); - if (errorStack.empty() == false) + /*if (errorStack.empty() == false) { Token.Type lastType = errorStack.pop(); if (lastType == Token.Type.VARIABLE) throw new IllegalLineException(kErrorVariable); - } + }*/ errorStack.push(Token.Type.VARIABLE); if (currentTokenExpressionStack == null) - throw new IllegalLineException(kErrorVariable); + currentTokenExpressionStack = new Stack<Token.Type>(); currentTokenExpressionStack.push(Token.Type.VARIABLE); } else if (token.getType() == Token.Type.UNARY_NOT_OPERATOR) { if (oldToken != null && oldToken.getType() == Token.Type.VARIABLE) throw new IllegalLineException(kErrorUnary); operatorStack.push(token); } else { if (operatorStack.empty() == false) { Token lastToken = operatorStack.lastElement(); if (lastToken.getType() == Token.Type.UNARY_NOT_OPERATOR) { operatorStack.pop(); linkedList.add(lastToken); } } operatorStack.push(token); if (errorStack.empty() == true) throw new IllegalLineException(kErrorOperator); Token.Type type = errorStack.pop(); if (type != Token.Type.VARIABLE) throw new IllegalLineException(kErrorOperator); errorStack.push(token.getType()); currentTokenExpressionStack.push(token.getType()); } oldToken = token; } while (!operatorStack.isEmpty()) { Token token = operatorStack.pop(); linkedList.add(token); } if (parenthesisStack.empty() == false) throw new IllegalLineException(kErrorParenthesis); if (expressionStack.empty() == false) { if (!isValidExpression(currentTokenExpressionStack)) throw new IllegalLineException(kExpressionInvalid); } return linkedList; } public static ProofTree buildTree(ArrayList<Token> tokenArray) throws IllegalLineException { Queue<Token> queue = infixToPostfix(tokenArray); Stack<ProofNode> treeNodeStack = new Stack<ProofNode>(); for (Iterator<Token> iter = queue.iterator(); iter.hasNext();) { Token token = iter.next(); if (token.getType() == Token.Type.VARIABLE) { treeNodeStack.push(new ProofNode(token)); } else if (token.getType() == Token.Type.UNARY_NOT_OPERATOR) { if (treeNodeStack.isEmpty() == true) throw new IllegalLineException(kErrorUnary); treeNodeStack.lastElement().switchUnaryFlag(); } else { ProofNode parentNode = new ProofNode(token); if (treeNodeStack.size() < 2) throw new IllegalLineException(kErrorMissing); ProofNode rightNode = treeNodeStack.pop(); ProofNode leftNode = treeNodeStack.pop(); parentNode.linkTo(leftNode, rightNode); treeNodeStack.push(parentNode); } } return new ProofTree(treeNodeStack.pop()); } private ArrayList<Token.Type> getExpressionOrder(ProofTree definitionTree, Queue<Type> definitionQueue) { ArrayList<Token.Type> linkedList = new ArrayList<Token.Type>(); for (Iterator<Node<Token>> iter = definitionTree.iterator(); iter.hasNext();) { Node<Token> node = iter.next(); Token.Type token = node.getData().getType(); if (token != Token.Type.VARIABLE) linkedList.add(token); definitionQueue.add(token); } return linkedList; } public boolean isEquivalent(ProofTree definitionTree) { Queue<Token.Type> definitionQueue = new LinkedList<Token.Type>(); Queue<Token.Type> useQueue = new LinkedList<Token.Type>(); ArrayList<Token.Type> definitionOperatorQueue = getExpressionOrder(definitionTree, definitionQueue); int currentIndex = 0; for (Iterator<Node<Token>> iter = this.iterator(); iter.hasNext();) { Node<Token> node = iter.next(); Token.Type token = node.getData().getType(); if (token != Token.Type.VARIABLE) { if (currentIndex >= definitionOperatorQueue.size()) return false; Token.Type definitionToken = definitionOperatorQueue.get(currentIndex); if (definitionToken == token) { ++currentIndex; useQueue.add(token); } else useQueue.add(Token.Type.VARIABLE); } } return definitionQueue.equals(useQueue); } public boolean equals(ProofTree pt) { if (pt != null) { return equals (pt.root); } return false; } public boolean equals(ProofNode n) { if (n != null) return equalsHelper((ProofNode)root, n); return false; } public boolean equalsHelper(ProofNode n1, ProofNode n2) { if (n1 == null ^ n2 == null) //only one is null return false; else if (n1 == null && n2 == null) //both are null return true; if (!n1.equals(n2)) return false; boolean same = equalsHelper((ProofNode)n1.getLeft(), (ProofNode)n2.getLeft()); if (same) return equalsHelper((ProofNode)n1.getRight(),(ProofNode)n2.getRight()); return false; } /* // equalsNoSign public boolean equalsNoSign(Object o) { if (o != null) return equalsNoSign((ProofNode)((ProofTree)o).root); return false; } public boolean equalsNoSign(ProofNode n) { if (n != null) return equalsNoSignHelper((ProofNode)root, n); if(debug) System.out.println("equalsNoSign NULL"); return false; } public boolean equalsNoSignHelper(ProofNode n1, ProofNode n2) { if (!n1.equalsNoSign(n2)) { if(debug) System.out.println(" it is not equal sign"); return false; } boolean same = equalsHelper((ProofNode)n1.getLeft(), (ProofNode)n2.getLeft()); if (same) return equalsHelper((ProofNode)n1.getRight(),(ProofNode)n2.getRight()); return false; } */ //equalsOpositeSign public boolean equalsOpositeSign(ProofTree o) { if (debug) System.out.println("equalsOpositeSign ProofTree"); if (o != null) return equalsOpositeSign((ProofNode)((ProofTree)o).root); return false; } public boolean equalsOpositeSign(ProofNode n) { if (debug) System.out.println("equalsOpositeSign ProofNode"); if (n != null) return equalsOpositeSignHelper((ProofNode)root, n); if(debug) System.out.println("equalsNoSign NULL"); return false; } public boolean equalsOpositeSignHelper(ProofNode n1, ProofNode n2) { if (!n1.equalsOpositeSign(n2)) { if(debug) System.out.println(" it is not equal sign"); return false; } boolean same = equalsHelper((ProofNode)n1.getLeft(), (ProofNode)n2.getLeft()); if (same) return equalsHelper((ProofNode)n1.getRight(),(ProofNode)n2.getRight()); return false; } /* public boolean isEquivalent(Object o) throws MethodNotFoundException { throw new MethodNotFoundException(); }*/ }
false
true
private static Queue<Token> infixToPostfix(ArrayList<Token> tokenArray) throws IllegalLineException { Stack<Token> operatorStack = new Stack<Token>(); Queue<Token> linkedList = new LinkedList<Token>(); Stack<Token.Type> errorStack = new Stack<Token.Type>(); Stack<Token.Type> parenthesisStack = new Stack<Token.Type>(); Stack<Stack<Token.Type>> expressionStack = new Stack<Stack<Token.Type>>(); Token oldToken = null; Stack<Token.Type> currentTokenExpressionStack = null; for (Iterator<Token> iter = tokenArray.iterator(); iter.hasNext();) { Token token = iter.next(); if (token.getType() == Token.Type.OPEN_PARENTHESIS) { parenthesisStack.push(Token.Type.OPEN_PARENTHESIS); operatorStack.push(token); Stack<Token.Type> tokenExpressionStack = new Stack<Token.Type>(); expressionStack.push(tokenExpressionStack); currentTokenExpressionStack = tokenExpressionStack; } else if (token.getType() == Token.Type.CLOSE_PARENTHESIS) { if (parenthesisStack.empty() == true) throw new IllegalLineException(kErrorParenthesis); Token.Type type = parenthesisStack.pop(); if (type != Token.Type.OPEN_PARENTHESIS) throw new IllegalLineException(kErrorParenthesis); while (!operatorStack.isEmpty()) { Token currentToken = operatorStack.pop(); if (currentToken.getType() == Token.Type.OPEN_PARENTHESIS) { break; } linkedList.add(currentToken); } if (isValidExpression(currentTokenExpressionStack)) { expressionStack.pop(); if (expressionStack.empty()) currentTokenExpressionStack = null; else { currentTokenExpressionStack = expressionStack.lastElement(); currentTokenExpressionStack.push(Token.Type.VARIABLE); } } else throw new IllegalLineException(kExpressionInvalid); } else if (token.getType() == Token.Type.VARIABLE) { linkedList.add(token); if (errorStack.empty() == false) { Token.Type lastType = errorStack.pop(); if (lastType == Token.Type.VARIABLE) throw new IllegalLineException(kErrorVariable); } errorStack.push(Token.Type.VARIABLE); if (currentTokenExpressionStack == null) throw new IllegalLineException(kErrorVariable); currentTokenExpressionStack.push(Token.Type.VARIABLE); } else if (token.getType() == Token.Type.UNARY_NOT_OPERATOR) { if (oldToken != null && oldToken.getType() == Token.Type.VARIABLE) throw new IllegalLineException(kErrorUnary); operatorStack.push(token); } else { if (operatorStack.empty() == false) { Token lastToken = operatorStack.lastElement(); if (lastToken.getType() == Token.Type.UNARY_NOT_OPERATOR) { operatorStack.pop(); linkedList.add(lastToken); } } operatorStack.push(token); if (errorStack.empty() == true) throw new IllegalLineException(kErrorOperator); Token.Type type = errorStack.pop(); if (type != Token.Type.VARIABLE) throw new IllegalLineException(kErrorOperator); errorStack.push(token.getType()); currentTokenExpressionStack.push(token.getType()); } oldToken = token; } while (!operatorStack.isEmpty()) { Token token = operatorStack.pop(); linkedList.add(token); } if (parenthesisStack.empty() == false) throw new IllegalLineException(kErrorParenthesis); if (expressionStack.empty() == false) { if (!isValidExpression(currentTokenExpressionStack)) throw new IllegalLineException(kExpressionInvalid); } return linkedList; }
private static Queue<Token> infixToPostfix(ArrayList<Token> tokenArray) throws IllegalLineException { Stack<Token> operatorStack = new Stack<Token>(); Queue<Token> linkedList = new LinkedList<Token>(); Stack<Token.Type> errorStack = new Stack<Token.Type>(); Stack<Token.Type> parenthesisStack = new Stack<Token.Type>(); Stack<Stack<Token.Type>> expressionStack = new Stack<Stack<Token.Type>>(); Token oldToken = null; Stack<Token.Type> currentTokenExpressionStack = null; for (Iterator<Token> iter = tokenArray.iterator(); iter.hasNext();) { Token token = iter.next(); if (token.getType() == Token.Type.OPEN_PARENTHESIS) { parenthesisStack.push(Token.Type.OPEN_PARENTHESIS); operatorStack.push(token); Stack<Token.Type> tokenExpressionStack = new Stack<Token.Type>(); expressionStack.push(tokenExpressionStack); currentTokenExpressionStack = tokenExpressionStack; } else if (token.getType() == Token.Type.CLOSE_PARENTHESIS) { if (parenthesisStack.empty() == true) throw new IllegalLineException(kErrorParenthesis); Token.Type type = parenthesisStack.pop(); if (type != Token.Type.OPEN_PARENTHESIS) throw new IllegalLineException(kErrorParenthesis); while (!operatorStack.isEmpty()) { Token currentToken = operatorStack.pop(); if (currentToken.getType() == Token.Type.OPEN_PARENTHESIS) { break; } linkedList.add(currentToken); } if (isValidExpression(currentTokenExpressionStack)) { expressionStack.pop(); if (expressionStack.empty()) currentTokenExpressionStack = null; else { currentTokenExpressionStack = expressionStack.lastElement(); currentTokenExpressionStack.push(Token.Type.VARIABLE); } } else throw new IllegalLineException(kExpressionInvalid); } else if (token.getType() == Token.Type.VARIABLE) { linkedList.add(token); /*if (errorStack.empty() == false) { Token.Type lastType = errorStack.pop(); if (lastType == Token.Type.VARIABLE) throw new IllegalLineException(kErrorVariable); }*/ errorStack.push(Token.Type.VARIABLE); if (currentTokenExpressionStack == null) currentTokenExpressionStack = new Stack<Token.Type>(); currentTokenExpressionStack.push(Token.Type.VARIABLE); } else if (token.getType() == Token.Type.UNARY_NOT_OPERATOR) { if (oldToken != null && oldToken.getType() == Token.Type.VARIABLE) throw new IllegalLineException(kErrorUnary); operatorStack.push(token); } else { if (operatorStack.empty() == false) { Token lastToken = operatorStack.lastElement(); if (lastToken.getType() == Token.Type.UNARY_NOT_OPERATOR) { operatorStack.pop(); linkedList.add(lastToken); } } operatorStack.push(token); if (errorStack.empty() == true) throw new IllegalLineException(kErrorOperator); Token.Type type = errorStack.pop(); if (type != Token.Type.VARIABLE) throw new IllegalLineException(kErrorOperator); errorStack.push(token.getType()); currentTokenExpressionStack.push(token.getType()); } oldToken = token; } while (!operatorStack.isEmpty()) { Token token = operatorStack.pop(); linkedList.add(token); } if (parenthesisStack.empty() == false) throw new IllegalLineException(kErrorParenthesis); if (expressionStack.empty() == false) { if (!isValidExpression(currentTokenExpressionStack)) throw new IllegalLineException(kExpressionInvalid); } return linkedList; }
diff --git a/android/samples/PushDemo/src/com/avos/avoscloud/PushDemo/PushDemo.java b/android/samples/PushDemo/src/com/avos/avoscloud/PushDemo/PushDemo.java index 7f70d9c..5b6ae7e 100644 --- a/android/samples/PushDemo/src/com/avos/avoscloud/PushDemo/PushDemo.java +++ b/android/samples/PushDemo/src/com/avos/avoscloud/PushDemo/PushDemo.java @@ -1,35 +1,35 @@ package com.avos.avoscloud.PushDemo; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.avos.avoscloud.*; public class PushDemo extends Activity { /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); PushService.setDefaultPushCallback(this, PushDemo.class); PushService.subscribe(this, "public", PushDemo.class); PushService.subscribe(this, "private", Callback1.class); PushService.subscribe(this, "protected", Callback2.class); final Context context = this; final TextView t = (TextView)this.findViewById(R.id.mylabel); - t.setText("id: q" + ParseInstallation.getCurrentInstallation().getInstallationId()); + t.setText("id: " + ParseInstallation.getCurrentInstallation().getInstallationId()); ParseInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { PushService.unsubscribe(context, "protected"); ParseInstallation.getCurrentInstallation().saveInBackground(); } }); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); PushService.setDefaultPushCallback(this, PushDemo.class); PushService.subscribe(this, "public", PushDemo.class); PushService.subscribe(this, "private", Callback1.class); PushService.subscribe(this, "protected", Callback2.class); final Context context = this; final TextView t = (TextView)this.findViewById(R.id.mylabel); t.setText("id: q" + ParseInstallation.getCurrentInstallation().getInstallationId()); ParseInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { PushService.unsubscribe(context, "protected"); ParseInstallation.getCurrentInstallation().saveInBackground(); } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); PushService.setDefaultPushCallback(this, PushDemo.class); PushService.subscribe(this, "public", PushDemo.class); PushService.subscribe(this, "private", Callback1.class); PushService.subscribe(this, "protected", Callback2.class); final Context context = this; final TextView t = (TextView)this.findViewById(R.id.mylabel); t.setText("id: " + ParseInstallation.getCurrentInstallation().getInstallationId()); ParseInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { PushService.unsubscribe(context, "protected"); ParseInstallation.getCurrentInstallation().saveInBackground(); } }); }
diff --git a/maven-refapp-plugin/src/main/java/com/atlassian/maven/plugins/refapp/DebugMojo.java b/maven-refapp-plugin/src/main/java/com/atlassian/maven/plugins/refapp/DebugMojo.java index b07c81e..2a6641a 100644 --- a/maven-refapp-plugin/src/main/java/com/atlassian/maven/plugins/refapp/DebugMojo.java +++ b/maven-refapp-plugin/src/main/java/com/atlassian/maven/plugins/refapp/DebugMojo.java @@ -1,40 +1,40 @@ package com.atlassian.maven.plugins.refapp; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; /** * Debug the webapp * * @requiresDependencyResolution debug * @goal debug * @execute phase="package" */ public class DebugMojo extends RunMojo { /** * port for debugging * * @parameter expression="${jvm.debug.port}" */ protected int jvmDebugPort = 5005; /** * Suspend when debugging * * @parameter expression="${jvm.debug.suspend}" */ protected boolean jvmDebugSuspend = false; @Override protected void doExecute() throws MojoExecutionException, MojoFailureException { if (jvmArgs == null) { jvmArgs = "-Xmx512m -XX:MaxPermSize=160m"; } jvmArgs += " -Xdebug -Xrunjdwp:transport=dt_socket,address="+String.valueOf(jvmDebugPort)+",suspend="+(jvmDebugSuspend?"y":"n")+",server=y "; - super.execute(); + super.doExecute(); } }
true
true
protected void doExecute() throws MojoExecutionException, MojoFailureException { if (jvmArgs == null) { jvmArgs = "-Xmx512m -XX:MaxPermSize=160m"; } jvmArgs += " -Xdebug -Xrunjdwp:transport=dt_socket,address="+String.valueOf(jvmDebugPort)+",suspend="+(jvmDebugSuspend?"y":"n")+",server=y "; super.execute(); }
protected void doExecute() throws MojoExecutionException, MojoFailureException { if (jvmArgs == null) { jvmArgs = "-Xmx512m -XX:MaxPermSize=160m"; } jvmArgs += " -Xdebug -Xrunjdwp:transport=dt_socket,address="+String.valueOf(jvmDebugPort)+",suspend="+(jvmDebugSuspend?"y":"n")+",server=y "; super.doExecute(); }
diff --git a/kernel-private/src/main/java/org/sakaiproject/springframework/orm/hibernate/dialect/db2/DB2Dialect9.java b/kernel-private/src/main/java/org/sakaiproject/springframework/orm/hibernate/dialect/db2/DB2Dialect9.java index f1c9e9ab..61b0309b 100644 --- a/kernel-private/src/main/java/org/sakaiproject/springframework/orm/hibernate/dialect/db2/DB2Dialect9.java +++ b/kernel-private/src/main/java/org/sakaiproject/springframework/orm/hibernate/dialect/db2/DB2Dialect9.java @@ -1,32 +1,32 @@ package org.sakaiproject.springframework.orm.hibernate.dialect.db2; import org.hibernate.dialect.DB2Dialect; import java.sql.Types; /** * Created by IntelliJ IDEA. * User: jbush * Date: May 23, 2007 * Time: 4:20:48 PM * To change this template use File | Settings | File Templates. */ public class DB2Dialect9 extends DB2Dialect { public DB2Dialect9() { super(); registerColumnType( Types.VARBINARY, "LONG VARCHAR FOR BIT DATA" ); registerColumnType( Types.VARCHAR, "clob(1000000000)" ); registerColumnType( Types.VARCHAR, 1000000000, "clob($l)" ); - registerColumnType( Types.VARCHAR, 32704, "varchar($l)" ); + registerColumnType( Types.VARCHAR, 3999, "varchar($l)" ); //according to the db2 docs the max for clob and blob should be 2147438647, but this isn't working for me // possibly something to do with how my database is configured ? registerColumnType( Types.CLOB, "clob(1000000000)" ); registerColumnType( Types.CLOB, 1000000000, "clob($l)" ); registerColumnType( Types.BLOB, "blob(1000000000)" ); registerColumnType( Types.BLOB, 1000000000, "blob($l)" ); } }
true
true
public DB2Dialect9() { super(); registerColumnType( Types.VARBINARY, "LONG VARCHAR FOR BIT DATA" ); registerColumnType( Types.VARCHAR, "clob(1000000000)" ); registerColumnType( Types.VARCHAR, 1000000000, "clob($l)" ); registerColumnType( Types.VARCHAR, 32704, "varchar($l)" ); //according to the db2 docs the max for clob and blob should be 2147438647, but this isn't working for me // possibly something to do with how my database is configured ? registerColumnType( Types.CLOB, "clob(1000000000)" ); registerColumnType( Types.CLOB, 1000000000, "clob($l)" ); registerColumnType( Types.BLOB, "blob(1000000000)" ); registerColumnType( Types.BLOB, 1000000000, "blob($l)" ); }
public DB2Dialect9() { super(); registerColumnType( Types.VARBINARY, "LONG VARCHAR FOR BIT DATA" ); registerColumnType( Types.VARCHAR, "clob(1000000000)" ); registerColumnType( Types.VARCHAR, 1000000000, "clob($l)" ); registerColumnType( Types.VARCHAR, 3999, "varchar($l)" ); //according to the db2 docs the max for clob and blob should be 2147438647, but this isn't working for me // possibly something to do with how my database is configured ? registerColumnType( Types.CLOB, "clob(1000000000)" ); registerColumnType( Types.CLOB, 1000000000, "clob($l)" ); registerColumnType( Types.BLOB, "blob(1000000000)" ); registerColumnType( Types.BLOB, 1000000000, "blob($l)" ); }
diff --git a/common/servicemix-common/src/main/java/org/apache/servicemix/common/xbean/ClassLoaderXmlPreprocessor.java b/common/servicemix-common/src/main/java/org/apache/servicemix/common/xbean/ClassLoaderXmlPreprocessor.java index c5f4c2aff..06c4b5099 100644 --- a/common/servicemix-common/src/main/java/org/apache/servicemix/common/xbean/ClassLoaderXmlPreprocessor.java +++ b/common/servicemix-common/src/main/java/org/apache/servicemix/common/xbean/ClassLoaderXmlPreprocessor.java @@ -1,248 +1,254 @@ /* * 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.servicemix.common.xbean; import java.io.File; import java.io.FilenameFilter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import javax.xml.parsers.DocumentBuilder; import org.apache.servicemix.jbi.container.JBIContainer; import org.apache.servicemix.jbi.framework.SharedLibrary; import org.apache.servicemix.jbi.framework.ComponentMBeanImpl; import org.apache.servicemix.jbi.jaxp.SourceTransformer; import org.apache.xbean.classloader.JarFileClassLoader; import org.apache.xbean.server.repository.FileSystemRepository; import org.apache.xbean.server.repository.Repository; import org.apache.xbean.server.spring.loader.SpringLoader; import org.apache.xbean.spring.context.SpringApplicationContext; import org.apache.xbean.spring.context.SpringXmlPreprocessor; import org.springframework.beans.FatalBeanException; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Text; /** * An advanced xml preprocessor that will create a default classloader for the SU if none * is configured. * * @author gnodet */ public class ClassLoaderXmlPreprocessor implements SpringXmlPreprocessor { public static final String CLASSPATH_XML = "classpath.xml"; public static final String LIB_DIR = "/lib"; private final FileSystemRepository repository; private final JBIContainer container; public ClassLoaderXmlPreprocessor(Repository repository) { this(repository, null); } public ClassLoaderXmlPreprocessor(Repository repository, JBIContainer container) { if (repository instanceof FileSystemRepository == false) { throw new IllegalArgumentException("repository must be a FileSystemRepository"); } this.repository = (FileSystemRepository) repository; this.container = container; } public void preprocess(SpringApplicationContext applicationContext, XmlBeanDefinitionReader reader, Document document) { // determine the classLoader ClassLoader classLoader; NodeList classpathElements = document.getDocumentElement().getElementsByTagName("classpath"); if (classpathElements.getLength() == 0) { // Check if a classpath.xml file exists in the root of the SU URL url = repository.getResource(CLASSPATH_XML); if (url != null) { try { DocumentBuilder builder = new SourceTransformer().createDocumentBuilder(); Document doc = builder.parse(url.toString()); classLoader = getClassLoader(applicationContext, reader, doc); } catch (Exception e) { throw new FatalBeanException("Unable to load classpath.xml file", e); } } else { try { URL[] urls = getDefaultLocations(); ClassLoader parentLoader = getParentClassLoader(applicationContext); classLoader = new JarFileClassLoader(applicationContext.getDisplayName(), urls, parentLoader); // assign the class loader to the xml reader and the // application context } catch (Exception e) { throw new FatalBeanException("Unable to create default classloader for SU", e); } } } else { classLoader = getClassLoader(applicationContext, reader, document); } reader.setBeanClassLoader(classLoader); applicationContext.setClassLoader(classLoader); Thread.currentThread().setContextClassLoader(classLoader); } protected URL[] getDefaultLocations() { try { File root = repository.getRoot(); File[] jars = new File(root, LIB_DIR).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { name = name.toLowerCase(); return name.endsWith(".jar") || name.endsWith(".zip"); } }); URL[] urls = new URL[jars != null ? jars.length + 1 : 1]; urls[0] = root.toURL(); if (jars != null) { for (int i = 0; i < jars.length; i++) { urls[i+1] = jars[i].toURL(); } } return urls; } catch (MalformedURLException e) { throw new FatalBeanException("Unable to get default classpath locations", e); } } protected ClassLoader getClassLoader(SpringApplicationContext applicationContext, XmlBeanDefinitionReader reader, Document document) { // determine the classLoader ClassLoader classLoader; NodeList classpathElements = document.getDocumentElement().getElementsByTagName("classpath"); if (classpathElements.getLength() < 1) { classLoader = getParentClassLoader(applicationContext); } else if (classpathElements.getLength() > 1) { throw new FatalBeanException("Expected only classpath element but found " + classpathElements.getLength()); } else { Element classpathElement = (Element) classpathElements.item(0); // Delegation mode boolean inverse = false; String inverseAttr = classpathElement.getAttribute("inverse"); if (inverseAttr != null && "true".equalsIgnoreCase(inverseAttr)) { inverse = true; } // build hidden classes List<String> hidden = new ArrayList<String>(); NodeList hiddenElems = classpathElement.getElementsByTagName("hidden"); for (int i = 0; i < hiddenElems.getLength(); i++) { Element hiddenElement = (Element) hiddenElems.item(i); String pattern = ((Text) hiddenElement.getFirstChild()).getData().trim(); hidden.add(pattern); } // build non overridable classes List<String> nonOverridable = new ArrayList<String>(); NodeList nonOverridableElems = classpathElement.getElementsByTagName("nonOverridable"); for (int i = 0; i < nonOverridableElems.getLength(); i++) { Element nonOverridableElement = (Element) nonOverridableElems.item(i); String pattern = ((Text) nonOverridableElement.getFirstChild()).getData().trim(); nonOverridable.add(pattern); } // build the classpath List<String> classpath = new ArrayList<String>(); NodeList locations = classpathElement.getElementsByTagName("location"); for (int i = 0; i < locations.getLength(); i++) { Element locationElement = (Element) locations.item(i); String location = ((Text) locationElement.getFirstChild()).getData().trim(); classpath.add(location); } // Add shared libraries List<String> sls = new ArrayList<String>(); NodeList libraries = classpathElement.getElementsByTagName("library"); for (int i = 0; i < libraries.getLength(); i++) { Element locationElement = (Element) locations.item(i); String library = ((Text) locationElement.getFirstChild()).getData().trim(); sls.add(library); } if (sls.size() > 0 && container == null) { throw new IllegalStateException("Can not reference shared libraries if the component is not deployed in ServiceMix"); } // Add components List<String> components = new ArrayList<String>(); NodeList componentList = classpathElement.getElementsByTagName("component"); for (int i = 0; i < componentList.getLength(); i++) { Element locationElement = (Element) locations.item(i); String component = ((Text) locationElement.getFirstChild()).getData().trim(); components.add(component); } if (components.size() > 0 && container == null) { throw new IllegalStateException("Can not reference other components if the component is not deployed in ServiceMix"); } // convert the paths to URLS URL[] urls; if (classpath.size() != 0) { urls = new URL[classpath.size()]; for (ListIterator<String> iterator = classpath.listIterator(); iterator.hasNext();) { String location = iterator.next(); URL url = repository.getResource(location); if (url == null) { throw new FatalBeanException("Unable to resolve classpath location " + location); } urls[iterator.previousIndex()] = url; } } else { urls = getDefaultLocations(); } // create the classloader List<ClassLoader> parents = new ArrayList<ClassLoader>(); parents.add(getParentClassLoader(applicationContext)); for (String library : sls) { SharedLibrary sl = container.getRegistry().getSharedLibrary(library); + if (sl == null) { + throw new IllegalStateException("No such shared library: " + library); + } parents.add(sl.getClassLoader()); } for (String component : components) { ComponentMBeanImpl componentMBean = container.getRegistry().getComponent(component); + if (componentMBean == null) { + throw new IllegalStateException("No such component: " + componentMBean); + } parents.add(componentMBean.getComponent().getClass().getClassLoader()); } classLoader = new JarFileClassLoader(applicationContext.getDisplayName(), urls, parents.toArray(new ClassLoader[parents.size()]), inverse, hidden.toArray(new String[hidden.size()]), nonOverridable.toArray(new String[nonOverridable.size()])); // remove the classpath element so Spring doesn't get confused document.getDocumentElement().removeChild(classpathElement); } return classLoader; } private static ClassLoader getParentClassLoader(SpringApplicationContext applicationContext) { ClassLoader classLoader = applicationContext.getClassLoader(); if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } if (classLoader == null) { classLoader = SpringLoader.class.getClassLoader(); } return classLoader; } }
false
true
protected ClassLoader getClassLoader(SpringApplicationContext applicationContext, XmlBeanDefinitionReader reader, Document document) { // determine the classLoader ClassLoader classLoader; NodeList classpathElements = document.getDocumentElement().getElementsByTagName("classpath"); if (classpathElements.getLength() < 1) { classLoader = getParentClassLoader(applicationContext); } else if (classpathElements.getLength() > 1) { throw new FatalBeanException("Expected only classpath element but found " + classpathElements.getLength()); } else { Element classpathElement = (Element) classpathElements.item(0); // Delegation mode boolean inverse = false; String inverseAttr = classpathElement.getAttribute("inverse"); if (inverseAttr != null && "true".equalsIgnoreCase(inverseAttr)) { inverse = true; } // build hidden classes List<String> hidden = new ArrayList<String>(); NodeList hiddenElems = classpathElement.getElementsByTagName("hidden"); for (int i = 0; i < hiddenElems.getLength(); i++) { Element hiddenElement = (Element) hiddenElems.item(i); String pattern = ((Text) hiddenElement.getFirstChild()).getData().trim(); hidden.add(pattern); } // build non overridable classes List<String> nonOverridable = new ArrayList<String>(); NodeList nonOverridableElems = classpathElement.getElementsByTagName("nonOverridable"); for (int i = 0; i < nonOverridableElems.getLength(); i++) { Element nonOverridableElement = (Element) nonOverridableElems.item(i); String pattern = ((Text) nonOverridableElement.getFirstChild()).getData().trim(); nonOverridable.add(pattern); } // build the classpath List<String> classpath = new ArrayList<String>(); NodeList locations = classpathElement.getElementsByTagName("location"); for (int i = 0; i < locations.getLength(); i++) { Element locationElement = (Element) locations.item(i); String location = ((Text) locationElement.getFirstChild()).getData().trim(); classpath.add(location); } // Add shared libraries List<String> sls = new ArrayList<String>(); NodeList libraries = classpathElement.getElementsByTagName("library"); for (int i = 0; i < libraries.getLength(); i++) { Element locationElement = (Element) locations.item(i); String library = ((Text) locationElement.getFirstChild()).getData().trim(); sls.add(library); } if (sls.size() > 0 && container == null) { throw new IllegalStateException("Can not reference shared libraries if the component is not deployed in ServiceMix"); } // Add components List<String> components = new ArrayList<String>(); NodeList componentList = classpathElement.getElementsByTagName("component"); for (int i = 0; i < componentList.getLength(); i++) { Element locationElement = (Element) locations.item(i); String component = ((Text) locationElement.getFirstChild()).getData().trim(); components.add(component); } if (components.size() > 0 && container == null) { throw new IllegalStateException("Can not reference other components if the component is not deployed in ServiceMix"); } // convert the paths to URLS URL[] urls; if (classpath.size() != 0) { urls = new URL[classpath.size()]; for (ListIterator<String> iterator = classpath.listIterator(); iterator.hasNext();) { String location = iterator.next(); URL url = repository.getResource(location); if (url == null) { throw new FatalBeanException("Unable to resolve classpath location " + location); } urls[iterator.previousIndex()] = url; } } else { urls = getDefaultLocations(); } // create the classloader List<ClassLoader> parents = new ArrayList<ClassLoader>(); parents.add(getParentClassLoader(applicationContext)); for (String library : sls) { SharedLibrary sl = container.getRegistry().getSharedLibrary(library); parents.add(sl.getClassLoader()); } for (String component : components) { ComponentMBeanImpl componentMBean = container.getRegistry().getComponent(component); parents.add(componentMBean.getComponent().getClass().getClassLoader()); } classLoader = new JarFileClassLoader(applicationContext.getDisplayName(), urls, parents.toArray(new ClassLoader[parents.size()]), inverse, hidden.toArray(new String[hidden.size()]), nonOverridable.toArray(new String[nonOverridable.size()])); // remove the classpath element so Spring doesn't get confused document.getDocumentElement().removeChild(classpathElement); } return classLoader; }
protected ClassLoader getClassLoader(SpringApplicationContext applicationContext, XmlBeanDefinitionReader reader, Document document) { // determine the classLoader ClassLoader classLoader; NodeList classpathElements = document.getDocumentElement().getElementsByTagName("classpath"); if (classpathElements.getLength() < 1) { classLoader = getParentClassLoader(applicationContext); } else if (classpathElements.getLength() > 1) { throw new FatalBeanException("Expected only classpath element but found " + classpathElements.getLength()); } else { Element classpathElement = (Element) classpathElements.item(0); // Delegation mode boolean inverse = false; String inverseAttr = classpathElement.getAttribute("inverse"); if (inverseAttr != null && "true".equalsIgnoreCase(inverseAttr)) { inverse = true; } // build hidden classes List<String> hidden = new ArrayList<String>(); NodeList hiddenElems = classpathElement.getElementsByTagName("hidden"); for (int i = 0; i < hiddenElems.getLength(); i++) { Element hiddenElement = (Element) hiddenElems.item(i); String pattern = ((Text) hiddenElement.getFirstChild()).getData().trim(); hidden.add(pattern); } // build non overridable classes List<String> nonOverridable = new ArrayList<String>(); NodeList nonOverridableElems = classpathElement.getElementsByTagName("nonOverridable"); for (int i = 0; i < nonOverridableElems.getLength(); i++) { Element nonOverridableElement = (Element) nonOverridableElems.item(i); String pattern = ((Text) nonOverridableElement.getFirstChild()).getData().trim(); nonOverridable.add(pattern); } // build the classpath List<String> classpath = new ArrayList<String>(); NodeList locations = classpathElement.getElementsByTagName("location"); for (int i = 0; i < locations.getLength(); i++) { Element locationElement = (Element) locations.item(i); String location = ((Text) locationElement.getFirstChild()).getData().trim(); classpath.add(location); } // Add shared libraries List<String> sls = new ArrayList<String>(); NodeList libraries = classpathElement.getElementsByTagName("library"); for (int i = 0; i < libraries.getLength(); i++) { Element locationElement = (Element) locations.item(i); String library = ((Text) locationElement.getFirstChild()).getData().trim(); sls.add(library); } if (sls.size() > 0 && container == null) { throw new IllegalStateException("Can not reference shared libraries if the component is not deployed in ServiceMix"); } // Add components List<String> components = new ArrayList<String>(); NodeList componentList = classpathElement.getElementsByTagName("component"); for (int i = 0; i < componentList.getLength(); i++) { Element locationElement = (Element) locations.item(i); String component = ((Text) locationElement.getFirstChild()).getData().trim(); components.add(component); } if (components.size() > 0 && container == null) { throw new IllegalStateException("Can not reference other components if the component is not deployed in ServiceMix"); } // convert the paths to URLS URL[] urls; if (classpath.size() != 0) { urls = new URL[classpath.size()]; for (ListIterator<String> iterator = classpath.listIterator(); iterator.hasNext();) { String location = iterator.next(); URL url = repository.getResource(location); if (url == null) { throw new FatalBeanException("Unable to resolve classpath location " + location); } urls[iterator.previousIndex()] = url; } } else { urls = getDefaultLocations(); } // create the classloader List<ClassLoader> parents = new ArrayList<ClassLoader>(); parents.add(getParentClassLoader(applicationContext)); for (String library : sls) { SharedLibrary sl = container.getRegistry().getSharedLibrary(library); if (sl == null) { throw new IllegalStateException("No such shared library: " + library); } parents.add(sl.getClassLoader()); } for (String component : components) { ComponentMBeanImpl componentMBean = container.getRegistry().getComponent(component); if (componentMBean == null) { throw new IllegalStateException("No such component: " + componentMBean); } parents.add(componentMBean.getComponent().getClass().getClassLoader()); } classLoader = new JarFileClassLoader(applicationContext.getDisplayName(), urls, parents.toArray(new ClassLoader[parents.size()]), inverse, hidden.toArray(new String[hidden.size()]), nonOverridable.toArray(new String[nonOverridable.size()])); // remove the classpath element so Spring doesn't get confused document.getDocumentElement().removeChild(classpathElement); } return classLoader; }
diff --git a/MoveConditionInstruction.java b/MoveConditionInstruction.java index e16e41f..78b267f 100644 --- a/MoveConditionInstruction.java +++ b/MoveConditionInstruction.java @@ -1,44 +1,47 @@ import java.util.*; public class MoveConditionInstruction extends Instruction { public String immediate; public Register dest; public MoveConditionInstruction(String name, String immediate, Register dest) { super(name); this.immediate = immediate; this.dest = dest; } public String toSparc() { String tempname = new String(name); if(name.equals("movlt")){ tempname = "movl"; } else if(name.equals("movgt")){ tempname = "movg"; } + else if(name.equals("moveq")){ + tempname = "move"; + } //have to move immediate into a register!! return new String(tempname + " %icc, " + immediate + ", " + dest.sparcName); } public String toString() { return new String(name + " " + immediate + ", " + dest); } public ArrayList<Register> getSources(){ ArrayList<Register> ret = new ArrayList<Register>(); ret.add(dest); return ret; } public ArrayList<Register> getDests(){ ArrayList<Register> ret = new ArrayList<Register>(); ret.add(dest); return ret; } }
true
true
public String toSparc() { String tempname = new String(name); if(name.equals("movlt")){ tempname = "movl"; } else if(name.equals("movgt")){ tempname = "movg"; } //have to move immediate into a register!! return new String(tempname + " %icc, " + immediate + ", " + dest.sparcName); }
public String toSparc() { String tempname = new String(name); if(name.equals("movlt")){ tempname = "movl"; } else if(name.equals("movgt")){ tempname = "movg"; } else if(name.equals("moveq")){ tempname = "move"; } //have to move immediate into a register!! return new String(tempname + " %icc, " + immediate + ", " + dest.sparcName); }
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandRegistry.java b/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandRegistry.java index f640396a1..a8ce14cfa 100644 --- a/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandRegistry.java +++ b/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandRegistry.java @@ -1,1920 +1,1920 @@ package net.aufdemrand.denizen.scripts.commands; import java.util.HashMap; import java.util.Map; import net.aufdemrand.denizen.Denizen; import net.aufdemrand.denizen.interfaces.dRegistry; import net.aufdemrand.denizen.interfaces.RegistrationableInstance; import net.aufdemrand.denizen.scripts.commands.core.*; import net.aufdemrand.denizen.scripts.commands.item.*; import net.aufdemrand.denizen.scripts.commands.player.*; import net.aufdemrand.denizen.scripts.commands.server.AnnounceCommand; import net.aufdemrand.denizen.scripts.commands.server.ExecuteCommand; import net.aufdemrand.denizen.scripts.commands.server.ScoreboardCommand; import net.aufdemrand.denizen.scripts.commands.entity.*; import net.aufdemrand.denizen.scripts.commands.npc.*; import net.aufdemrand.denizen.scripts.commands.world.*; import net.aufdemrand.denizen.utilities.debugging.dB; public class CommandRegistry implements dRegistry { public Denizen denizen; public CommandRegistry(Denizen denizen) { this.denizen = denizen; } private Map<String, AbstractCommand> instances = new HashMap<String, AbstractCommand>(); private Map<Class<? extends AbstractCommand>, String> classes = new HashMap<Class<? extends AbstractCommand>, String>(); @Override public boolean register(String commandName, RegistrationableInstance commandInstance) { this.instances.put(commandName.toUpperCase(), (AbstractCommand) commandInstance); this.classes.put(((AbstractCommand) commandInstance).getClass(), commandName.toUpperCase()); return true; } @Override public Map<String, AbstractCommand> list() { return instances; } @Override public AbstractCommand get(String commandName) { if (instances.containsKey(commandName.toUpperCase())) return instances.get(commandName.toUpperCase()); else return null; } @Override public <T extends RegistrationableInstance> T get(Class<T> clazz) { if (classes.containsKey(clazz)) return (T) clazz.cast(instances.get(classes.get(clazz))); else return null; } @Override public void registerCoreMembers() { // <--[command] // @Name Anchor // @Usage anchor [id:<name>] [assume/add/remove/walkto/walknear] (range:<#>) // @Required 2 // @Stable Stable - // @Short + // @Short TODO // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AnchorCommand.class, "ANCHOR", "anchor [id:<name>] [assume/add/remove/walkto/walknear] (range:<#>)", 2); // <--[command] // @Name Animate // @Usage animate [<entity>|...] [animation:<name>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AnimateCommand.class, "ANIMATE", "animate [<entity>|...] [animation:<name>]", 1); // <--[command] // @Name AnimateChest // @Usage animatechest [<location>] ({open}/close) (sound:{true}/false) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AnimateChestCommand.class, "ANIMATECHEST", "animatechest [<location>] ({open}/close) (sound:{true}/false)", 1); // <--[command] // @Name Announce // @Usage announce ["<text>"] (to_ops) (to_flagged:<flag>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AnnounceCommand.class, "ANNOUNCE", "announce [\"<text>\"] (to_ops) (to_flagged:<flag>)", 1); // <--[command] // @Name Assignment // @Usage assignment [{set}/remove] (script:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AssignmentCommand.class, "ASSIGNMENT", "assignment [{set}/remove] (script:<name>)", 1); // <--[command] // @Name Attack // @Usage attack (cancel) (<entity>|...) (target:<entity>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AttackCommand.class, "ATTACK", "attack (cancel) (<entity>|...) (target:<entity>)", 0); // <--[command] // @Name Break // @Usage break [<location>] (entity:<entity>) (radius:<#.#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(BreakCommand.class, "BREAK", "break [<location>] (entity:<entity>) (radius:<#.#>)", 1); // <--[command] // @Name Burn // @Usage burn [<entity>|...] (duration:<value>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(BurnCommand.class, "BURN", "burn [<entity>|...] (duration:<value>)", 1); // <--[command] // @Name Cast, Potion // @Usage cast [<effect>] (remove) (duration:<value>) (power:<#>) (<entity>|...) // @Required 1 // @Stable Stable // @Short Casts a potion effect to a list of entities. // @Author aufdemrand/Jeebiss/Morphan1 // // @Description // Casts or removes a potion effect to or from a list of entities. If you don't specify a duration, // it defaults to 60 seconds. If you don't specify a power level, it defaults to 1. // // @Tags // <[email protected]_effect[<effect>]> will return true if the entity has an effect. // // @Usage // Use to apply an effect to an entity // - potion jump <player> d:120 p:3 // - narrate "You have been given the temporary ability to jump like a kangaroo." // // @Usage // Use to remove an effect from an entity // - if <[email protected]_effect[jump]> { // - potion jump remove <player> // } // // @Example TODO // // --> registerCoreMember(CastCommand.class, "CAST, POTION", "cast [<effect>] (remove) (duration:<value>) (power:<#>) (<entity>|...)", 1); // <--[command] // @Name Chat // @Usage chat ["<text>"] (targets:<entity>|...) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ChatCommand.class, "CHAT", "chat [\"<text>\"] (targets:<entity>|...)", 1); // <--[command] // @Name ChunkLoad // @Usage chunkload ({add}/remove/removeall) [<location>] (duration:<value>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ChunkLoadCommand.class, "CHUNKLOAD", "chunkload ({add}/remove/removeall) [<location>] (duration:<value>)", 1); // <--[command] // @Name Compass // @Usage compass [<location>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(CompassCommand.class, "COMPASS", "compass [<location>]", 1); // <--[command] // @Name Cooldown // @Usage cooldown [<duration>] (global) (s:<script>) // @Required 1 // @Stable Stable // @Short Temporarily disables a script-container from meeting requirements. // @Author aufdemrand // // @Description // Cools down a script-container. If an interact-container, when on cooldown, scripts will not pass a // requirements check allowing the next highest priority script to trigger. If any other type of script, a // manual requirements check (<s@script_name.requirements.check>) will also return false until the cooldown // period is completed. Cooldown requires a type (player or global), a script, and a duration. It also requires // a valid link to a dPlayer if using player-type cooldown. // // Cooldown periods are persistent through a server restart as they are saved in the saves.yml. // // @Tags // <s@script_name.cooled_down[player]> will return whether the script is cooled down // <s@script_name.cooldown> will return the duration of the cooldown in progress. // <[email protected]> will also check script cooldown, as well as any requirements. // // @Usage // Use to keep the current interact script from meeting requirements. // - cooldown 20m // // @Usage // Use to keep a player from activating a script for a specified duration. // - cooldown 11h s:s@bonus_script // - cooldown 5s s:s@hit_indicator // // @Usage // Use the 'global' argument to indicate the script to be on cooldown for all players. // - cooldown global 24h s:s@daily_treasure_offering // // @Example TODO // // --> registerCoreMember(CooldownCommand.class, "COOLDOWN", "cooldown [<duration>] (global) (s:<script>)", 1); // <--[command] // @Name CopyBlock // @Usage copyblock [location:<location>] [to:<location>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(CopyBlockCommand.class, "COPYBLOCK", "copyblock [location:<location>] [to:<location>]", 1); // <--[command] // @Name CreateWorld // @Usage createworld [<name>] (g:<generator>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(CreateWorldCommand.class, "CREATEWORLD", "createworld [<name>] (g:<generator>)", 1); // <--[command] // @Name Define // @Usage define [<id>] [<value>] // @Required 2 // @Stable 1.0 // @Short Creates a temporary variable inside a script queue. // @Author aufdemrand // // @Description // Definitions are queue-level (or script-level) 'variables' that can be used throughout a script, once // defined, by using %'s around the definition id/name. Definitions are only valid on the current queue and are // not transferred to any new queues constructed within the script, such as a 'run' command, without explicitly // specifying to do so. // // Definitions are lighter and faster than creating a temporary flag, but unlike flags, are only a single entry, // that is, you can't add or remove from the definition, but you can re-create it if you wish to specify a new // value. Definitions are also automatically destroyed when the queue is completed, so there is no worry for // leaving unused data hanging around. // // Definitions are also resolved before replaceable tags, meaning you can use them within tags, even as an // attribute. ie. <%player%.name> // // @Usage // Use to make complex tags look less complex, and scripts more readable. // - narrate 'You invoke your power of notice...' // - define range '<player.flag[range_level].mul[3]>' // - define blocks '<player.flag[noticeable_blocks>' // - narrate '[NOTICE] You have noticed <player.location.find.blocks[%blocks%].within[%range].size> // blocks in the area that may be of interest.' // // @Usage // Use to keep the value of a replaceable tag that you might use many times within a single script. Definitions // can be faster and cleaner than reusing a replaceable tag over and over. // - define arg1 <c.args.get[1]> // - if %arg1% == hello narrate 'Hello!' // - if %arg1% == goodbye narrate 'Goodbye!' // // @Usage // Use to pass some important information (arguments) on to another queue. // - run 'new_task' d:hello|world // 'new_task' now has some definitions, %1% and %2%, that contains the contents specified, 'hello' and 'world'. // // @Example // // --> registerCoreMember(DefineCommand.class, "DEFINE", "define [<id>] [<value>]", 2); // <--[command] // @Name Determine // @Usage determine [<value>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(DetermineCommand.class, "DETERMINE", "determine [<value>]", 1); // <--[command] // @Name Disengage // @Usage disengage (npc:<npc>) // @Required 0 // @Stable 1.0 // @Short Enables a NPCs triggers that have been temporarily disabled by the engage command. // @Author aufdemrand // // @Description // Re-enables any toggled triggers that have been disabled by disengage. Using // disengage inside scripts must have a NPC to reference, or one may be specified // by supplying a valid dNPC object with the npc argument. // // This is mostly regarded as an 'interact script command', though it may be used inside // other script types. This is because disengage works with the trigger system, which is an // interact script-container feature. // // NPCs that are interacted with while engaged will fire an 'on unavailable' assignment // script-container action. // // @See Engage Command // // @Usage // Use to reenable a NPC's triggers, disabled via 'engage'. // - engage // - chat 'Be right there!' // - walkto <player.location> // - wait 5s // - disengage // // @Example // --> registerCoreMember(DisengageCommand.class, "DISENGAGE", "disengage (npc:<npc>)", 0); // <--[command] // @Name DisplayItem // @Usage displayitem (remove) [<item>] [<location>] (duration:<value>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(DisplayItemCommand.class, "DISPLAYITEM", "displayitem (remove) [<item>] [<location>] (duration:<value>)", 2); // <--[command] // @Name Drop // @Usage drop [<item>/<entity>/<xp>] [<location>] (qty:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(DropCommand.class, "DROP", "drop [<item>/<entity>/<xp>] [<location>] (qty:<#>)", 1); // <--[command] // @Name Engage // @Usage engage (<duration>) (npc:<npc>) // @Required 0 // @Stable 1.0 // @Short Temporarily disables a NPCs toggled interact script-container triggers. // @Author aufdemrand // // @Description // Engaging a NPC will temporarily disable any interact script-container triggers. To reverse // this behavior, use either the disengage command, or specify a duration in which the engage // should timeout. Specifying an engage without a duration will render the NPC engaged until // a disengage is used on the NPC. Engaging a NPC affects all players attempting to interact // with the NPC. // // While engaged, all triggers and actions associated with triggers will not 'fire', except // the 'on unavailable' assignment script-container action, which will fire for triggers that // were enabled previous to the engage command. // // Engage can be useful when NPCs are carrying out a task that shouldn't be interrupted, or // to provide a good way to avoid accidental 'retrigger'. // // @See Disengage Command // // @Tags // <[email protected]> will return true if the NPC is currently engaged, false otherwise. // // @Usage // Use to make a NPC appear 'busy'. // - engage // - chat 'Give me a few minutes while I mix you a potion!' // - walkto <npc.anchor[mixing_station]> // - wait 10s // - walkto <npc.anchor[service_station]> // - chat 'Here you go!' // - give potion <player> // - disengage // // @Usage // Use to avoid 'retrigger'. // - engage 5s // - take quest_item // - flag player finished_quests:->:super_quest // // @Example // // --> registerCoreMember(EngageCommand.class, "ENGAGE", "engage (<duration>) (npc:<npc>)", 0); // <--[command] // @Name Engrave // @Usage engrave (set/remove) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(EngraveCommand.class, "ENGRAVE", "engrave (set/remove)", 0); // <--[command] // @Name Equip // @Usage equip (hand:<item>) (head:<item>) (chest:<item>) (legs:<item>) (boots:<item>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(EquipCommand.class, "EQUIP", "equip (hand:<item>) (head:<item>) (chest:<item>) (legs:<item>) (boots:<item>)", 1); // <--[command] // @Name Execute // @Usage execute [as_player/as_op/as_npc/as_server] [<Bukkit command>] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ExecuteCommand.class, "EXECUTE", "execute [as_player/as_op/as_npc/as_server] [<Bukkit command>]", 2); // <--[command] // @Name Experience // @Usage experience [{set}/give/take] (level) [<#>] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ExperienceCommand.class, "EXPERIENCE", "experience [{set}/give/take] (level) [<#>]", 2); // <--[command] // @Name Explode // @Usage explode (power:<#.#>) (<location>) (fire) (breakblocks) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ExplodeCommand.class, "EXPLODE", "explode (power:<#.#>) (<location>) (fire) (breakblocks)", 0); // <--[command] // @Name Fail // @Usage fail (script:<name>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FailCommand.class, "FAIL", "fail (script:<name>)", 0); // <--[command] // @Name Feed // @Usage feed (amt:<#>) (target:<entity>|...) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FeedCommand.class, "FEED", "feed (amt:<#>) (target:<entity>|...)", 0); // <--[command] // @Name Finish // @Usage finish (script:<name>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FinishCommand.class, "FINISH", "finish (script:<name>)", 0); // <--[command] // @Name Firework // @Usage firework (<location>) (power:<#>) (type:<name>/random) (primary:<color>|...) (fade:<color>|...) (flicker) (trail) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FireworkCommand.class, "FIREWORK", "firework (<location>) (power:<#>) (type:<name>/random) (primary:<color>|...) (fade:<color>|...) (flicker) (trail)", 0); // <--[command] // @Name Fish // @Usage fish (catchfish) (stop) (<location>) (catchpercent:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FishCommand.class, "FISH", "fish (catchfish) (stop) (<location>) (catchpercent:<#>)", 1); // <--[command] // @Name Flag // @Usage flag ({player}/npc/global) [<name>([<#>])](:<action>)[:<value>] (duration:<value>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FlagCommand.class, "FLAG", "flag ({player}/npc/global) [<name>([<#>])](:<action>)[:<value>] (duration:<value>)", 1); // <--[command] // @Name Fly // @Usage fly (cancel) [<entity>|...] (origin:<location>) (destinations:<location>|...) (speed:<#.#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FlyCommand.class, "FLY", "fly (cancel) [<entity>|...] (origin:<location>) (destinations:<location>|...) (speed:<#.#>)", 1); // <--[command] // @Name Follow // @Usage follow (stop) (lead:<#.#>) (target:<entity>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FollowCommand.class, "FOLLOW", "follow (stop) (lead:<#.#>) (target:<entity>)", 0); // <--[command] // @Name ForEach // @Usage foreach [<object>|...] [<commands>] // @Required 2 // @Stable Experimental // @Short Loops through a dList, running a set of commands for each item. // @Author Morphan1/mcmonkey // // @Description // Loops through a dList of any type. For each item in the dList, the specified commands will be ran for // that item. To call the value of the item while in the loop, you can use %value%. // // @Usage // Use to run commands on multiple items. // - foreach li@e@123|n@424|p@BobBarker { // - announce "There's something at <%value%.location>!" // } // // @Example // // --> registerCoreMember(ForEachCommand.class, "FOREACH", "foreach [<object>|...] [<commands>]", 2); // <--[command] // @Name Give // @Usage give [money/<item>] (qty:<#>) (engrave) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(GiveCommand.class, "GIVE", "give [money/<item>] (qty:<#>) (engrave)", 1); // <--[command] // @Name Group // @Usage group [add/remove] [<group>] (world:<name>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(GroupCommand.class, "GROUP", "group [add/remove] [<group>] (world:<name>)", 2); // <--[command] // @Name Head // @Usage head (player) [skin:<name>] // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(HeadCommand.class, "HEAD", "head (player) [skin:<name>]", 0); // <--[command] // @Name Heal // @Usage heal (<#.#>) (<entity>|...) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(HealCommand.class, "HEAL", "heal (<#.#>) (<entity>|...)", 0); // <--[command] // @Name Health // @Usage health [<#>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(HealthCommand.class, "HEALTH", "health [<#>]", 1); // <--[command] // @Name Hurt // @Usage hurt (<#.#>) (<entity>|...) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(HurtCommand.class, "HURT", "hurt (<#.#>) (<entity>|...)", 0); // <--[command] // @Name If // @Usage if [<value>] (!)(<operator> <value>) (&&/|| ...) [<commands>] (else <commands>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(IfCommand.class, "IF", "if [<value>] (!)(<operator> <value>) (&&/|| ...) [<commands>] (else <commands>)", 2); // <--[command] // @Name Inventory // @Usage inventory [open/copy/move/swap/add/remove/keep/exclude/fill/clear] [destination:<inventory>] (origin:<inventory>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(InventoryCommand.class, "INVENTORY", "inventory [open/copy/move/swap/add/remove/keep/exclude/fill/clear] [destination:<inventory>] (origin:<inventory>)", 2); // <--[command] // @Name Invisible // @Usage invisible [player/npc] [state:true/false/toggle] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(InvisibleCommand.class, "INVISIBLE", "invisible [player/npc] [state:true/false/toggle]", 2); // <--[command] // @Name Leash // @Usage leash (cancel) [<entity>|...] (holder:<entity>/<location>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(LeashCommand.class, "LEASH", "leash (cancel) [<entity>|...] (holder:<entity>/<location>)", 1); // <--[command] // @Name Listen // @Usage listen ({new}/cancel/finish) [kill/block/item/itemdrop/travel] [<requirements>] [script:<name>] (id:<name>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ListenCommand.class, "LISTEN", "listen ({new}/cancel/finish) [kill/block/item/itemdrop/travel] [<requirements>] [script:<name>] (id:<name>)", 2); // <--[command] // @Name Log // @Usage log [<text>] (type:severe/info/warning/fine/finer/finest) [file:<name>] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(LogCommand.class, "LOG", "log [<text>] (type:severe/info/warning/fine/finer/finest) [file:<name>]", 2); // <--[command] // @Name Look // @Usage look (<entity>|...) [<location>] (duration:<duration>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(LookCommand.class, "LOOK", "look (<entity>|...) [<location>] (duration:<duration>)", 1); // <--[command] // @Name LookClose // @Usage lookclose [state:true/false] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(LookcloseCommand.class, "LOOKCLOSE", "lookclose [state:true/false]", 1); // <--[command] // @Name Midi // @Usage midi [file:<name>] [<location>/listeners:<player>|...] (tempo:<#.#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(MidiCommand.class, "MIDI", "midi [file:<name>] [<location>/listeners:<player>|...] (tempo:<#.#>)", 1); // <--[command] // @Name Mount // @Usage mount (cancel) [<entity>|...] (<location>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(MountCommand.class, "MOUNT", "mount (cancel) [<entity>|...] (<location>)", 0); // <--[command] // @Name ModifyBlock // @Usage modifyblock [<location>] [<block>] (radius:<#>) (height:<#>) (depth:<#>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ModifyBlockCommand.class, "MODIFYBLOCK", "modifyblock [<location>] [<block>] (radius:<#>) (height:<#>) (depth:<#>)", 2); // <--[command] // @Usage nameplate [<chatcolor>] [set:<text>] (target:<player>) +--> Requires ProtocolLib // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(NameplateCommand.class, "NAMEPLATE", "nameplate [<chatcolor>] [set:<text>] (target:<player>) +--> Requires ProtocolLib", 1); // <--[command] // @Name Narrate // @Usage narrate ["<text>"] (targets:<player>|...) (format:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(NarrateCommand.class, "NARRATE", "narrate [\"<text>\"] (targets:<player>|...) (format:<name>)", 1); // <--[command] // @Name Note // @Usage note [<Notable dObject>] [as:<name>] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(NoteCommand.class, "NOTE", "note [<Notable dObject>] [as:<name>]", 2); // <--[command] // @Name Oxygen // @Usage oxygen (type:maximum/remaining) (mode:set/add/remove) [qty:<#>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(OxygenCommand.class, "OXYGEN", "oxygen (type:maximum/remaining) (mode:set/add/remove) [qty:<#>]", 1); // <--[command] // @Name PlayEffect // @Usage playeffect [<location>] [effect:<name>] (data:<#.#>) (visibility:<#.#>) (qty:<#>) (offset:<#.#>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PlayEffectCommand.class, "PLAYEFFECT", "playeffect [<location>] [effect:<name>] (data:<#.#>) (visibility:<#.#>) (qty:<#>) (offset:<#.#>)", 2); // <--[command] // @Name PlaySound // @Usage playsound [<location>] [sound:<name>] (volume:<#.#>) (pitch:<#.#>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PlaySoundCommand.class, "PLAYSOUND", "playsound [<location>] [sound:<name>] (volume:<#.#>) (pitch:<#.#>)", 2); // <--[command] // @Name Permission // @Usage permission [add|remove] [permission] (player:<name>) (group:<name>) (world:<name>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PermissionCommand.class, "PERMISSION", "permission [add|remove] [permission] (player:<name>) (group:<name>) (world:<name>)", 2); // <--[command] // @Name Pose // @Usage pose (player/npc) [id:<name>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PoseCommand.class, "POSE", "pose (player/npc) [id:<name>]", 1); // <--[command] // @Name Pause // @Usage pause [waypoints/navigation] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PauseCommand.class, "PAUSE", "pause [waypoints/navigation]", 1); // <--[command] // @Name Queue // @Usage queue (queue:<id>) [clear/pause/resume/delay:<#>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(QueueCommand.class, "QUEUE", "queue (queue:<id>) [clear/pause/resume/delay:<#>]", 1); // <--[command] // @Name Random // @Usage random [<#>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RandomCommand.class, "RANDOM", "random [<#>]", 1); // <--[command] // @Name Remove // @Usage remove [<entity>|...] (region:<name>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RemoveCommand.class, "REMOVE", "remove [<entity>|...] (region:<name>)", 0); // <--[command] // @Name Rename // @Usage rename [<npc>] [<name>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RenameCommand.class, "RENAME", "rename [<npc>] [<name>]", 1); // <--[command] // @Name Repeat // @Usage repeat [<amount>] [<commands>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RepeatCommand.class, "REPEAT", "repeat [<amount>] [<commands>]", 1); // <--[command] // @Name Reset // @Usage reset [fails/finishes/cooldown] (script:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ResetCommand.class, "RESET", "reset [fails/finishes/cooldown] (script:<name>)", 1); // <--[command] // @Name Run // @Usage run [<script>] (path:<name>) (as:<player>/<npc>) (define:<element>|...) (id:<name>) (delay:<value>) (loop) (qty:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RunCommand.class, "RUN", "run [<script>] (path:<name>) (as:<player>/<npc>) (define:<element>|...) (id:<name>) (delay:<value>) (loop) (qty:<#>)", 1); // <--[command] // @Name RunTask // @Deprecated This has been replaced by the Run command. // @Usage runtask [<name>] (instantly) (queue(:<name>)) (delay:<#>) (define:<element>|...) // @Required 1 // @Stable Stable // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RuntaskCommand.class, "RUNTASK", "runtask [<name>] (instantly) (queue(:<name>)) (delay:<#>) (define:<element>|...)", 1); // <--[command] // @Name Scoreboard // @Usage scoreboard [set/remove/show/hide] [<name>] [value:<name>] (priority:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ScoreboardCommand.class, "SCOREBOARD", "scoreboard [set/remove/show/hide] [<name>] [value:<name>] (priority:<#>)", 1); // <--[command] // @Name Scribe // @Usage scribe [script:<name>] (give/drop/equip) (<item>) (<location>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ScribeCommand.class, "SCRIBE", "scribe [script:<name>] (give/drop/equip) (<item>) (<location>)", 1); // <--[command] // @Name Shoot // @Usage shoot [<entity>|...] (origin:<entity>/<location>) (destination:<location>) [{calculated} (height:<#.#>) (gravity:<#.#>)]/[custom speed:<#.#> duration:<value>] (script:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ShootCommand.class, "SHOOT", "shoot [<entity>|...] (origin:<entity>/<location>) (destination:<location>) [{calculated} (height:<#.#>) (gravity:<#.#>)]/[custom speed:<#.#> duration:<value>] (script:<name>)", 1); // <--[command] // @Name ShowFake // @Usage showfake [<material>] [<location>|...] (d:<duration>{10s}) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ShowFakeCommand.class, "SHOWFAKE", "showfake [<material>] [<location>|...] (d:<duration>{10s})", 2); // <--[command] // @Name Sign // @Usage sign (type:{sign_post}/wall_sign) ["<line>|..."] [<location>] (direction:n/e/w/s) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(SignCommand.class, "SIGN", "sign (type:{sign_post}/wall_sign) [\"<line>|...\"] [<location>] (direction:n/e/w/s)", 1); // <--[command] // @Name Sit // @Usage sit (<location>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(SitCommand.class, "SIT", "sit (<location>)", 0); // <--[command] // @Name Spawn // @Usage spawn [<entity>|...] (<location>) (target:<entity>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(SpawnCommand.class, "SPAWN", "spawn [<entity>|...] (<location>) (target:<entity>)", 1); // <--[command] // @Name Stand // @Usage stand // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(StandCommand.class, "STAND", "stand", 0); // <--[command] // @Name Strike // @Usage strike (no_damage) [<location>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(StrikeCommand.class, "STRIKE", "strike (no_damage) [<location>]", 1); // <--[command] // @Name Switch // @Usage switch [<location>] (state:[{toggle}/on/off]) (duration:<value>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(SwitchCommand.class, "SWITCH", "switch [<location>] (state:[{toggle}/on/off]) (duration:<value>)", 1); // <--[command] // @Name Take // @Usage take [money/iteminhand/<item>] (qty:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(TakeCommand.class, "TAKE", "take [money/iteminhand/<item>] (qty:<#>)", 1); // <--[command] // @Name Teleport // @Usage teleport (<entity>|...) (<location>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(TeleportCommand.class, "TELEPORT", "teleport (<entity>|...) (<location>)", 1); // <--[command] // @Name Time // @Usage time [type:{global}/player] [<value>] (world:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(TimeCommand.class, "TIME", "time [type:{global}/player] [<value>] (world:<name>)", 1); // <--[command] // @Name Trigger // @Usage trigger [name:chat/click/damage/proximity] (state:true/false) (cooldown:<#.#>) (radius:<#>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(TriggerCommand.class, "TRIGGER", "trigger [name:chat/click/damage/proximity] (state:true/false) (cooldown:<#.#>) (radius:<#>)", 2); // <--[command] // @Name Viewer // @Usage viewer ({create <location>}/modify/remove) [id:<name>] (type:{sign_post}/wall_sign) (display:{location}/score/logged_in) (direction:n/e/w/s) // @Required 1 // @Stable Experimental // @Short Creates a sign that auto-updates with information. // @Author Morphan1 // // @Description // Creates a sign that auto-updates with information about a player, including their location, score, and // whether they're logged in or not. // // @Tags // None // // @Usage // Create a sign that shows the location of a player on a wall // - viewer player:ThatGuy create 113,76,-302,world id:PlayerLoc1 type:wall_sign display:location // // @Example // Todo // --> registerCoreMember(ViewerCommand.class, "VIEWER", "viewer ({create <location>}/modify/remove) [id:<name>] (type:{sign_post}/wall_sign) (display:{location}/score/logged_in) (direction:n/e/w/s)", 2); // <--[command] // @Name Vulnerable // @Usage vulnerable (state:{true}/false/toggle) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(VulnerableCommand.class, "VULNERABLE", "vulnerable (state:{true}/false/toggle)", 0); // <--[command] // @Name Wait // @Usage wait (<duration>) (queue:<name>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(WaitCommand.class, "WAIT", "wait (<duration>) (queue:<name>)", 0); // <--[command] // @Name Walk, WalkTo // @Usage walkto [<location>] (speed:<#>) (auto_range) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(WalkCommand.class, "WALK, WALKTO", "walk [<location>] (speed:<#>) (auto_range)", 1); // <--[command] // @Name Weather // @Usage weather [type:{global}/player] [sunny/storm/thunder] (world:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(WeatherCommand.class, "WEATHER", "weather [type:{global}/player] [sunny/storm/thunder] (world:<name>)", 1); // <--[command] // @Name Yaml // @Usage yaml [load/create/save:<file>]/[write:<key>]/[write:<key> value:<value>] [id:<name>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(YamlCommand.class, "YAML", "yaml [load/create/save:<file>]/[write:<key>]/[write:<key> value:<value>] [id:<name>]", 1); // <--[command] // @Name Zap // @Usage zap (<script>:)[<step>] (<duration>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ZapCommand.class, "ZAP", "zap (<script>:)[<step>] (<duration>)", 0); dB.echoApproval("Loaded core commands: " + instances.keySet().toString()); } private <T extends AbstractCommand> void registerCoreMember(Class<T> cmd, String names, String hint, int args) { for (String name : names.split(", ")) { try { cmd.newInstance().activate().as(name).withOptions(hint, args); } catch(Exception e) { dB.echoError("Could not register command " + name + ": " + e.getMessage()); if (dB.showStackTraces) e.printStackTrace(); } } } @Override public void disableCoreMembers() { for (RegistrationableInstance member : instances.values()) try { member.onDisable(); } catch (Exception e) { dB.echoError("Unable to disable '" + member.getClass().getName() + "'!"); if (dB.showStackTraces) e.printStackTrace(); } } }
true
true
public void registerCoreMembers() { // <--[command] // @Name Anchor // @Usage anchor [id:<name>] [assume/add/remove/walkto/walknear] (range:<#>) // @Required 2 // @Stable Stable // @Short // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AnchorCommand.class, "ANCHOR", "anchor [id:<name>] [assume/add/remove/walkto/walknear] (range:<#>)", 2); // <--[command] // @Name Animate // @Usage animate [<entity>|...] [animation:<name>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AnimateCommand.class, "ANIMATE", "animate [<entity>|...] [animation:<name>]", 1); // <--[command] // @Name AnimateChest // @Usage animatechest [<location>] ({open}/close) (sound:{true}/false) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AnimateChestCommand.class, "ANIMATECHEST", "animatechest [<location>] ({open}/close) (sound:{true}/false)", 1); // <--[command] // @Name Announce // @Usage announce ["<text>"] (to_ops) (to_flagged:<flag>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AnnounceCommand.class, "ANNOUNCE", "announce [\"<text>\"] (to_ops) (to_flagged:<flag>)", 1); // <--[command] // @Name Assignment // @Usage assignment [{set}/remove] (script:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AssignmentCommand.class, "ASSIGNMENT", "assignment [{set}/remove] (script:<name>)", 1); // <--[command] // @Name Attack // @Usage attack (cancel) (<entity>|...) (target:<entity>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AttackCommand.class, "ATTACK", "attack (cancel) (<entity>|...) (target:<entity>)", 0); // <--[command] // @Name Break // @Usage break [<location>] (entity:<entity>) (radius:<#.#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(BreakCommand.class, "BREAK", "break [<location>] (entity:<entity>) (radius:<#.#>)", 1); // <--[command] // @Name Burn // @Usage burn [<entity>|...] (duration:<value>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(BurnCommand.class, "BURN", "burn [<entity>|...] (duration:<value>)", 1); // <--[command] // @Name Cast, Potion // @Usage cast [<effect>] (remove) (duration:<value>) (power:<#>) (<entity>|...) // @Required 1 // @Stable Stable // @Short Casts a potion effect to a list of entities. // @Author aufdemrand/Jeebiss/Morphan1 // // @Description // Casts or removes a potion effect to or from a list of entities. If you don't specify a duration, // it defaults to 60 seconds. If you don't specify a power level, it defaults to 1. // // @Tags // <[email protected]_effect[<effect>]> will return true if the entity has an effect. // // @Usage // Use to apply an effect to an entity // - potion jump <player> d:120 p:3 // - narrate "You have been given the temporary ability to jump like a kangaroo." // // @Usage // Use to remove an effect from an entity // - if <[email protected]_effect[jump]> { // - potion jump remove <player> // } // // @Example TODO // // --> registerCoreMember(CastCommand.class, "CAST, POTION", "cast [<effect>] (remove) (duration:<value>) (power:<#>) (<entity>|...)", 1); // <--[command] // @Name Chat // @Usage chat ["<text>"] (targets:<entity>|...) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ChatCommand.class, "CHAT", "chat [\"<text>\"] (targets:<entity>|...)", 1); // <--[command] // @Name ChunkLoad // @Usage chunkload ({add}/remove/removeall) [<location>] (duration:<value>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ChunkLoadCommand.class, "CHUNKLOAD", "chunkload ({add}/remove/removeall) [<location>] (duration:<value>)", 1); // <--[command] // @Name Compass // @Usage compass [<location>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(CompassCommand.class, "COMPASS", "compass [<location>]", 1); // <--[command] // @Name Cooldown // @Usage cooldown [<duration>] (global) (s:<script>) // @Required 1 // @Stable Stable // @Short Temporarily disables a script-container from meeting requirements. // @Author aufdemrand // // @Description // Cools down a script-container. If an interact-container, when on cooldown, scripts will not pass a // requirements check allowing the next highest priority script to trigger. If any other type of script, a // manual requirements check (<s@script_name.requirements.check>) will also return false until the cooldown // period is completed. Cooldown requires a type (player or global), a script, and a duration. It also requires // a valid link to a dPlayer if using player-type cooldown. // // Cooldown periods are persistent through a server restart as they are saved in the saves.yml. // // @Tags // <s@script_name.cooled_down[player]> will return whether the script is cooled down // <s@script_name.cooldown> will return the duration of the cooldown in progress. // <[email protected]> will also check script cooldown, as well as any requirements. // // @Usage // Use to keep the current interact script from meeting requirements. // - cooldown 20m // // @Usage // Use to keep a player from activating a script for a specified duration. // - cooldown 11h s:s@bonus_script // - cooldown 5s s:s@hit_indicator // // @Usage // Use the 'global' argument to indicate the script to be on cooldown for all players. // - cooldown global 24h s:s@daily_treasure_offering // // @Example TODO // // --> registerCoreMember(CooldownCommand.class, "COOLDOWN", "cooldown [<duration>] (global) (s:<script>)", 1); // <--[command] // @Name CopyBlock // @Usage copyblock [location:<location>] [to:<location>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(CopyBlockCommand.class, "COPYBLOCK", "copyblock [location:<location>] [to:<location>]", 1); // <--[command] // @Name CreateWorld // @Usage createworld [<name>] (g:<generator>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(CreateWorldCommand.class, "CREATEWORLD", "createworld [<name>] (g:<generator>)", 1); // <--[command] // @Name Define // @Usage define [<id>] [<value>] // @Required 2 // @Stable 1.0 // @Short Creates a temporary variable inside a script queue. // @Author aufdemrand // // @Description // Definitions are queue-level (or script-level) 'variables' that can be used throughout a script, once // defined, by using %'s around the definition id/name. Definitions are only valid on the current queue and are // not transferred to any new queues constructed within the script, such as a 'run' command, without explicitly // specifying to do so. // // Definitions are lighter and faster than creating a temporary flag, but unlike flags, are only a single entry, // that is, you can't add or remove from the definition, but you can re-create it if you wish to specify a new // value. Definitions are also automatically destroyed when the queue is completed, so there is no worry for // leaving unused data hanging around. // // Definitions are also resolved before replaceable tags, meaning you can use them within tags, even as an // attribute. ie. <%player%.name> // // @Usage // Use to make complex tags look less complex, and scripts more readable. // - narrate 'You invoke your power of notice...' // - define range '<player.flag[range_level].mul[3]>' // - define blocks '<player.flag[noticeable_blocks>' // - narrate '[NOTICE] You have noticed <player.location.find.blocks[%blocks%].within[%range].size> // blocks in the area that may be of interest.' // // @Usage // Use to keep the value of a replaceable tag that you might use many times within a single script. Definitions // can be faster and cleaner than reusing a replaceable tag over and over. // - define arg1 <c.args.get[1]> // - if %arg1% == hello narrate 'Hello!' // - if %arg1% == goodbye narrate 'Goodbye!' // // @Usage // Use to pass some important information (arguments) on to another queue. // - run 'new_task' d:hello|world // 'new_task' now has some definitions, %1% and %2%, that contains the contents specified, 'hello' and 'world'. // // @Example // // --> registerCoreMember(DefineCommand.class, "DEFINE", "define [<id>] [<value>]", 2); // <--[command] // @Name Determine // @Usage determine [<value>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(DetermineCommand.class, "DETERMINE", "determine [<value>]", 1); // <--[command] // @Name Disengage // @Usage disengage (npc:<npc>) // @Required 0 // @Stable 1.0 // @Short Enables a NPCs triggers that have been temporarily disabled by the engage command. // @Author aufdemrand // // @Description // Re-enables any toggled triggers that have been disabled by disengage. Using // disengage inside scripts must have a NPC to reference, or one may be specified // by supplying a valid dNPC object with the npc argument. // // This is mostly regarded as an 'interact script command', though it may be used inside // other script types. This is because disengage works with the trigger system, which is an // interact script-container feature. // // NPCs that are interacted with while engaged will fire an 'on unavailable' assignment // script-container action. // // @See Engage Command // // @Usage // Use to reenable a NPC's triggers, disabled via 'engage'. // - engage // - chat 'Be right there!' // - walkto <player.location> // - wait 5s // - disengage // // @Example // --> registerCoreMember(DisengageCommand.class, "DISENGAGE", "disengage (npc:<npc>)", 0); // <--[command] // @Name DisplayItem // @Usage displayitem (remove) [<item>] [<location>] (duration:<value>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(DisplayItemCommand.class, "DISPLAYITEM", "displayitem (remove) [<item>] [<location>] (duration:<value>)", 2); // <--[command] // @Name Drop // @Usage drop [<item>/<entity>/<xp>] [<location>] (qty:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(DropCommand.class, "DROP", "drop [<item>/<entity>/<xp>] [<location>] (qty:<#>)", 1); // <--[command] // @Name Engage // @Usage engage (<duration>) (npc:<npc>) // @Required 0 // @Stable 1.0 // @Short Temporarily disables a NPCs toggled interact script-container triggers. // @Author aufdemrand // // @Description // Engaging a NPC will temporarily disable any interact script-container triggers. To reverse // this behavior, use either the disengage command, or specify a duration in which the engage // should timeout. Specifying an engage without a duration will render the NPC engaged until // a disengage is used on the NPC. Engaging a NPC affects all players attempting to interact // with the NPC. // // While engaged, all triggers and actions associated with triggers will not 'fire', except // the 'on unavailable' assignment script-container action, which will fire for triggers that // were enabled previous to the engage command. // // Engage can be useful when NPCs are carrying out a task that shouldn't be interrupted, or // to provide a good way to avoid accidental 'retrigger'. // // @See Disengage Command // // @Tags // <[email protected]> will return true if the NPC is currently engaged, false otherwise. // // @Usage // Use to make a NPC appear 'busy'. // - engage // - chat 'Give me a few minutes while I mix you a potion!' // - walkto <npc.anchor[mixing_station]> // - wait 10s // - walkto <npc.anchor[service_station]> // - chat 'Here you go!' // - give potion <player> // - disengage // // @Usage // Use to avoid 'retrigger'. // - engage 5s // - take quest_item // - flag player finished_quests:->:super_quest // // @Example // // --> registerCoreMember(EngageCommand.class, "ENGAGE", "engage (<duration>) (npc:<npc>)", 0); // <--[command] // @Name Engrave // @Usage engrave (set/remove) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(EngraveCommand.class, "ENGRAVE", "engrave (set/remove)", 0); // <--[command] // @Name Equip // @Usage equip (hand:<item>) (head:<item>) (chest:<item>) (legs:<item>) (boots:<item>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(EquipCommand.class, "EQUIP", "equip (hand:<item>) (head:<item>) (chest:<item>) (legs:<item>) (boots:<item>)", 1); // <--[command] // @Name Execute // @Usage execute [as_player/as_op/as_npc/as_server] [<Bukkit command>] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ExecuteCommand.class, "EXECUTE", "execute [as_player/as_op/as_npc/as_server] [<Bukkit command>]", 2); // <--[command] // @Name Experience // @Usage experience [{set}/give/take] (level) [<#>] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ExperienceCommand.class, "EXPERIENCE", "experience [{set}/give/take] (level) [<#>]", 2); // <--[command] // @Name Explode // @Usage explode (power:<#.#>) (<location>) (fire) (breakblocks) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ExplodeCommand.class, "EXPLODE", "explode (power:<#.#>) (<location>) (fire) (breakblocks)", 0); // <--[command] // @Name Fail // @Usage fail (script:<name>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FailCommand.class, "FAIL", "fail (script:<name>)", 0); // <--[command] // @Name Feed // @Usage feed (amt:<#>) (target:<entity>|...) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FeedCommand.class, "FEED", "feed (amt:<#>) (target:<entity>|...)", 0); // <--[command] // @Name Finish // @Usage finish (script:<name>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FinishCommand.class, "FINISH", "finish (script:<name>)", 0); // <--[command] // @Name Firework // @Usage firework (<location>) (power:<#>) (type:<name>/random) (primary:<color>|...) (fade:<color>|...) (flicker) (trail) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FireworkCommand.class, "FIREWORK", "firework (<location>) (power:<#>) (type:<name>/random) (primary:<color>|...) (fade:<color>|...) (flicker) (trail)", 0); // <--[command] // @Name Fish // @Usage fish (catchfish) (stop) (<location>) (catchpercent:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FishCommand.class, "FISH", "fish (catchfish) (stop) (<location>) (catchpercent:<#>)", 1); // <--[command] // @Name Flag // @Usage flag ({player}/npc/global) [<name>([<#>])](:<action>)[:<value>] (duration:<value>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FlagCommand.class, "FLAG", "flag ({player}/npc/global) [<name>([<#>])](:<action>)[:<value>] (duration:<value>)", 1); // <--[command] // @Name Fly // @Usage fly (cancel) [<entity>|...] (origin:<location>) (destinations:<location>|...) (speed:<#.#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FlyCommand.class, "FLY", "fly (cancel) [<entity>|...] (origin:<location>) (destinations:<location>|...) (speed:<#.#>)", 1); // <--[command] // @Name Follow // @Usage follow (stop) (lead:<#.#>) (target:<entity>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FollowCommand.class, "FOLLOW", "follow (stop) (lead:<#.#>) (target:<entity>)", 0); // <--[command] // @Name ForEach // @Usage foreach [<object>|...] [<commands>] // @Required 2 // @Stable Experimental // @Short Loops through a dList, running a set of commands for each item. // @Author Morphan1/mcmonkey // // @Description // Loops through a dList of any type. For each item in the dList, the specified commands will be ran for // that item. To call the value of the item while in the loop, you can use %value%. // // @Usage // Use to run commands on multiple items. // - foreach li@e@123|n@424|p@BobBarker { // - announce "There's something at <%value%.location>!" // } // // @Example // // --> registerCoreMember(ForEachCommand.class, "FOREACH", "foreach [<object>|...] [<commands>]", 2); // <--[command] // @Name Give // @Usage give [money/<item>] (qty:<#>) (engrave) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(GiveCommand.class, "GIVE", "give [money/<item>] (qty:<#>) (engrave)", 1); // <--[command] // @Name Group // @Usage group [add/remove] [<group>] (world:<name>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(GroupCommand.class, "GROUP", "group [add/remove] [<group>] (world:<name>)", 2); // <--[command] // @Name Head // @Usage head (player) [skin:<name>] // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(HeadCommand.class, "HEAD", "head (player) [skin:<name>]", 0); // <--[command] // @Name Heal // @Usage heal (<#.#>) (<entity>|...) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(HealCommand.class, "HEAL", "heal (<#.#>) (<entity>|...)", 0); // <--[command] // @Name Health // @Usage health [<#>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(HealthCommand.class, "HEALTH", "health [<#>]", 1); // <--[command] // @Name Hurt // @Usage hurt (<#.#>) (<entity>|...) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(HurtCommand.class, "HURT", "hurt (<#.#>) (<entity>|...)", 0); // <--[command] // @Name If // @Usage if [<value>] (!)(<operator> <value>) (&&/|| ...) [<commands>] (else <commands>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(IfCommand.class, "IF", "if [<value>] (!)(<operator> <value>) (&&/|| ...) [<commands>] (else <commands>)", 2); // <--[command] // @Name Inventory // @Usage inventory [open/copy/move/swap/add/remove/keep/exclude/fill/clear] [destination:<inventory>] (origin:<inventory>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(InventoryCommand.class, "INVENTORY", "inventory [open/copy/move/swap/add/remove/keep/exclude/fill/clear] [destination:<inventory>] (origin:<inventory>)", 2); // <--[command] // @Name Invisible // @Usage invisible [player/npc] [state:true/false/toggle] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(InvisibleCommand.class, "INVISIBLE", "invisible [player/npc] [state:true/false/toggle]", 2); // <--[command] // @Name Leash // @Usage leash (cancel) [<entity>|...] (holder:<entity>/<location>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(LeashCommand.class, "LEASH", "leash (cancel) [<entity>|...] (holder:<entity>/<location>)", 1); // <--[command] // @Name Listen // @Usage listen ({new}/cancel/finish) [kill/block/item/itemdrop/travel] [<requirements>] [script:<name>] (id:<name>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ListenCommand.class, "LISTEN", "listen ({new}/cancel/finish) [kill/block/item/itemdrop/travel] [<requirements>] [script:<name>] (id:<name>)", 2); // <--[command] // @Name Log // @Usage log [<text>] (type:severe/info/warning/fine/finer/finest) [file:<name>] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(LogCommand.class, "LOG", "log [<text>] (type:severe/info/warning/fine/finer/finest) [file:<name>]", 2); // <--[command] // @Name Look // @Usage look (<entity>|...) [<location>] (duration:<duration>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(LookCommand.class, "LOOK", "look (<entity>|...) [<location>] (duration:<duration>)", 1); // <--[command] // @Name LookClose // @Usage lookclose [state:true/false] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(LookcloseCommand.class, "LOOKCLOSE", "lookclose [state:true/false]", 1); // <--[command] // @Name Midi // @Usage midi [file:<name>] [<location>/listeners:<player>|...] (tempo:<#.#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(MidiCommand.class, "MIDI", "midi [file:<name>] [<location>/listeners:<player>|...] (tempo:<#.#>)", 1); // <--[command] // @Name Mount // @Usage mount (cancel) [<entity>|...] (<location>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(MountCommand.class, "MOUNT", "mount (cancel) [<entity>|...] (<location>)", 0); // <--[command] // @Name ModifyBlock // @Usage modifyblock [<location>] [<block>] (radius:<#>) (height:<#>) (depth:<#>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ModifyBlockCommand.class, "MODIFYBLOCK", "modifyblock [<location>] [<block>] (radius:<#>) (height:<#>) (depth:<#>)", 2); // <--[command] // @Usage nameplate [<chatcolor>] [set:<text>] (target:<player>) +--> Requires ProtocolLib // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(NameplateCommand.class, "NAMEPLATE", "nameplate [<chatcolor>] [set:<text>] (target:<player>) +--> Requires ProtocolLib", 1); // <--[command] // @Name Narrate // @Usage narrate ["<text>"] (targets:<player>|...) (format:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(NarrateCommand.class, "NARRATE", "narrate [\"<text>\"] (targets:<player>|...) (format:<name>)", 1); // <--[command] // @Name Note // @Usage note [<Notable dObject>] [as:<name>] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(NoteCommand.class, "NOTE", "note [<Notable dObject>] [as:<name>]", 2); // <--[command] // @Name Oxygen // @Usage oxygen (type:maximum/remaining) (mode:set/add/remove) [qty:<#>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(OxygenCommand.class, "OXYGEN", "oxygen (type:maximum/remaining) (mode:set/add/remove) [qty:<#>]", 1); // <--[command] // @Name PlayEffect // @Usage playeffect [<location>] [effect:<name>] (data:<#.#>) (visibility:<#.#>) (qty:<#>) (offset:<#.#>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PlayEffectCommand.class, "PLAYEFFECT", "playeffect [<location>] [effect:<name>] (data:<#.#>) (visibility:<#.#>) (qty:<#>) (offset:<#.#>)", 2); // <--[command] // @Name PlaySound // @Usage playsound [<location>] [sound:<name>] (volume:<#.#>) (pitch:<#.#>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PlaySoundCommand.class, "PLAYSOUND", "playsound [<location>] [sound:<name>] (volume:<#.#>) (pitch:<#.#>)", 2); // <--[command] // @Name Permission // @Usage permission [add|remove] [permission] (player:<name>) (group:<name>) (world:<name>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PermissionCommand.class, "PERMISSION", "permission [add|remove] [permission] (player:<name>) (group:<name>) (world:<name>)", 2); // <--[command] // @Name Pose // @Usage pose (player/npc) [id:<name>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PoseCommand.class, "POSE", "pose (player/npc) [id:<name>]", 1); // <--[command] // @Name Pause // @Usage pause [waypoints/navigation] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PauseCommand.class, "PAUSE", "pause [waypoints/navigation]", 1); // <--[command] // @Name Queue // @Usage queue (queue:<id>) [clear/pause/resume/delay:<#>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(QueueCommand.class, "QUEUE", "queue (queue:<id>) [clear/pause/resume/delay:<#>]", 1); // <--[command] // @Name Random // @Usage random [<#>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RandomCommand.class, "RANDOM", "random [<#>]", 1); // <--[command] // @Name Remove // @Usage remove [<entity>|...] (region:<name>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RemoveCommand.class, "REMOVE", "remove [<entity>|...] (region:<name>)", 0); // <--[command] // @Name Rename // @Usage rename [<npc>] [<name>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RenameCommand.class, "RENAME", "rename [<npc>] [<name>]", 1); // <--[command] // @Name Repeat // @Usage repeat [<amount>] [<commands>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RepeatCommand.class, "REPEAT", "repeat [<amount>] [<commands>]", 1); // <--[command] // @Name Reset // @Usage reset [fails/finishes/cooldown] (script:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ResetCommand.class, "RESET", "reset [fails/finishes/cooldown] (script:<name>)", 1); // <--[command] // @Name Run // @Usage run [<script>] (path:<name>) (as:<player>/<npc>) (define:<element>|...) (id:<name>) (delay:<value>) (loop) (qty:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RunCommand.class, "RUN", "run [<script>] (path:<name>) (as:<player>/<npc>) (define:<element>|...) (id:<name>) (delay:<value>) (loop) (qty:<#>)", 1); // <--[command] // @Name RunTask // @Deprecated This has been replaced by the Run command. // @Usage runtask [<name>] (instantly) (queue(:<name>)) (delay:<#>) (define:<element>|...) // @Required 1 // @Stable Stable // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RuntaskCommand.class, "RUNTASK", "runtask [<name>] (instantly) (queue(:<name>)) (delay:<#>) (define:<element>|...)", 1); // <--[command] // @Name Scoreboard // @Usage scoreboard [set/remove/show/hide] [<name>] [value:<name>] (priority:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ScoreboardCommand.class, "SCOREBOARD", "scoreboard [set/remove/show/hide] [<name>] [value:<name>] (priority:<#>)", 1); // <--[command] // @Name Scribe // @Usage scribe [script:<name>] (give/drop/equip) (<item>) (<location>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ScribeCommand.class, "SCRIBE", "scribe [script:<name>] (give/drop/equip) (<item>) (<location>)", 1); // <--[command] // @Name Shoot // @Usage shoot [<entity>|...] (origin:<entity>/<location>) (destination:<location>) [{calculated} (height:<#.#>) (gravity:<#.#>)]/[custom speed:<#.#> duration:<value>] (script:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ShootCommand.class, "SHOOT", "shoot [<entity>|...] (origin:<entity>/<location>) (destination:<location>) [{calculated} (height:<#.#>) (gravity:<#.#>)]/[custom speed:<#.#> duration:<value>] (script:<name>)", 1); // <--[command] // @Name ShowFake // @Usage showfake [<material>] [<location>|...] (d:<duration>{10s}) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ShowFakeCommand.class, "SHOWFAKE", "showfake [<material>] [<location>|...] (d:<duration>{10s})", 2); // <--[command] // @Name Sign // @Usage sign (type:{sign_post}/wall_sign) ["<line>|..."] [<location>] (direction:n/e/w/s) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(SignCommand.class, "SIGN", "sign (type:{sign_post}/wall_sign) [\"<line>|...\"] [<location>] (direction:n/e/w/s)", 1); // <--[command] // @Name Sit // @Usage sit (<location>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(SitCommand.class, "SIT", "sit (<location>)", 0); // <--[command] // @Name Spawn // @Usage spawn [<entity>|...] (<location>) (target:<entity>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(SpawnCommand.class, "SPAWN", "spawn [<entity>|...] (<location>) (target:<entity>)", 1); // <--[command] // @Name Stand // @Usage stand // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(StandCommand.class, "STAND", "stand", 0); // <--[command] // @Name Strike // @Usage strike (no_damage) [<location>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(StrikeCommand.class, "STRIKE", "strike (no_damage) [<location>]", 1); // <--[command] // @Name Switch // @Usage switch [<location>] (state:[{toggle}/on/off]) (duration:<value>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(SwitchCommand.class, "SWITCH", "switch [<location>] (state:[{toggle}/on/off]) (duration:<value>)", 1); // <--[command] // @Name Take // @Usage take [money/iteminhand/<item>] (qty:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(TakeCommand.class, "TAKE", "take [money/iteminhand/<item>] (qty:<#>)", 1); // <--[command] // @Name Teleport // @Usage teleport (<entity>|...) (<location>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(TeleportCommand.class, "TELEPORT", "teleport (<entity>|...) (<location>)", 1); // <--[command] // @Name Time // @Usage time [type:{global}/player] [<value>] (world:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(TimeCommand.class, "TIME", "time [type:{global}/player] [<value>] (world:<name>)", 1); // <--[command] // @Name Trigger // @Usage trigger [name:chat/click/damage/proximity] (state:true/false) (cooldown:<#.#>) (radius:<#>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(TriggerCommand.class, "TRIGGER", "trigger [name:chat/click/damage/proximity] (state:true/false) (cooldown:<#.#>) (radius:<#>)", 2); // <--[command] // @Name Viewer // @Usage viewer ({create <location>}/modify/remove) [id:<name>] (type:{sign_post}/wall_sign) (display:{location}/score/logged_in) (direction:n/e/w/s) // @Required 1 // @Stable Experimental // @Short Creates a sign that auto-updates with information. // @Author Morphan1 // // @Description // Creates a sign that auto-updates with information about a player, including their location, score, and // whether they're logged in or not. // // @Tags // None // // @Usage // Create a sign that shows the location of a player on a wall // - viewer player:ThatGuy create 113,76,-302,world id:PlayerLoc1 type:wall_sign display:location // // @Example // Todo // --> registerCoreMember(ViewerCommand.class, "VIEWER", "viewer ({create <location>}/modify/remove) [id:<name>] (type:{sign_post}/wall_sign) (display:{location}/score/logged_in) (direction:n/e/w/s)", 2); // <--[command] // @Name Vulnerable // @Usage vulnerable (state:{true}/false/toggle) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(VulnerableCommand.class, "VULNERABLE", "vulnerable (state:{true}/false/toggle)", 0); // <--[command] // @Name Wait // @Usage wait (<duration>) (queue:<name>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(WaitCommand.class, "WAIT", "wait (<duration>) (queue:<name>)", 0); // <--[command] // @Name Walk, WalkTo // @Usage walkto [<location>] (speed:<#>) (auto_range) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(WalkCommand.class, "WALK, WALKTO", "walk [<location>] (speed:<#>) (auto_range)", 1); // <--[command] // @Name Weather // @Usage weather [type:{global}/player] [sunny/storm/thunder] (world:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(WeatherCommand.class, "WEATHER", "weather [type:{global}/player] [sunny/storm/thunder] (world:<name>)", 1); // <--[command] // @Name Yaml // @Usage yaml [load/create/save:<file>]/[write:<key>]/[write:<key> value:<value>] [id:<name>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(YamlCommand.class, "YAML", "yaml [load/create/save:<file>]/[write:<key>]/[write:<key> value:<value>] [id:<name>]", 1); // <--[command] // @Name Zap // @Usage zap (<script>:)[<step>] (<duration>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ZapCommand.class, "ZAP", "zap (<script>:)[<step>] (<duration>)", 0); dB.echoApproval("Loaded core commands: " + instances.keySet().toString()); }
public void registerCoreMembers() { // <--[command] // @Name Anchor // @Usage anchor [id:<name>] [assume/add/remove/walkto/walknear] (range:<#>) // @Required 2 // @Stable Stable // @Short TODO // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AnchorCommand.class, "ANCHOR", "anchor [id:<name>] [assume/add/remove/walkto/walknear] (range:<#>)", 2); // <--[command] // @Name Animate // @Usage animate [<entity>|...] [animation:<name>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AnimateCommand.class, "ANIMATE", "animate [<entity>|...] [animation:<name>]", 1); // <--[command] // @Name AnimateChest // @Usage animatechest [<location>] ({open}/close) (sound:{true}/false) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AnimateChestCommand.class, "ANIMATECHEST", "animatechest [<location>] ({open}/close) (sound:{true}/false)", 1); // <--[command] // @Name Announce // @Usage announce ["<text>"] (to_ops) (to_flagged:<flag>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AnnounceCommand.class, "ANNOUNCE", "announce [\"<text>\"] (to_ops) (to_flagged:<flag>)", 1); // <--[command] // @Name Assignment // @Usage assignment [{set}/remove] (script:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AssignmentCommand.class, "ASSIGNMENT", "assignment [{set}/remove] (script:<name>)", 1); // <--[command] // @Name Attack // @Usage attack (cancel) (<entity>|...) (target:<entity>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(AttackCommand.class, "ATTACK", "attack (cancel) (<entity>|...) (target:<entity>)", 0); // <--[command] // @Name Break // @Usage break [<location>] (entity:<entity>) (radius:<#.#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(BreakCommand.class, "BREAK", "break [<location>] (entity:<entity>) (radius:<#.#>)", 1); // <--[command] // @Name Burn // @Usage burn [<entity>|...] (duration:<value>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(BurnCommand.class, "BURN", "burn [<entity>|...] (duration:<value>)", 1); // <--[command] // @Name Cast, Potion // @Usage cast [<effect>] (remove) (duration:<value>) (power:<#>) (<entity>|...) // @Required 1 // @Stable Stable // @Short Casts a potion effect to a list of entities. // @Author aufdemrand/Jeebiss/Morphan1 // // @Description // Casts or removes a potion effect to or from a list of entities. If you don't specify a duration, // it defaults to 60 seconds. If you don't specify a power level, it defaults to 1. // // @Tags // <[email protected]_effect[<effect>]> will return true if the entity has an effect. // // @Usage // Use to apply an effect to an entity // - potion jump <player> d:120 p:3 // - narrate "You have been given the temporary ability to jump like a kangaroo." // // @Usage // Use to remove an effect from an entity // - if <[email protected]_effect[jump]> { // - potion jump remove <player> // } // // @Example TODO // // --> registerCoreMember(CastCommand.class, "CAST, POTION", "cast [<effect>] (remove) (duration:<value>) (power:<#>) (<entity>|...)", 1); // <--[command] // @Name Chat // @Usage chat ["<text>"] (targets:<entity>|...) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ChatCommand.class, "CHAT", "chat [\"<text>\"] (targets:<entity>|...)", 1); // <--[command] // @Name ChunkLoad // @Usage chunkload ({add}/remove/removeall) [<location>] (duration:<value>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ChunkLoadCommand.class, "CHUNKLOAD", "chunkload ({add}/remove/removeall) [<location>] (duration:<value>)", 1); // <--[command] // @Name Compass // @Usage compass [<location>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(CompassCommand.class, "COMPASS", "compass [<location>]", 1); // <--[command] // @Name Cooldown // @Usage cooldown [<duration>] (global) (s:<script>) // @Required 1 // @Stable Stable // @Short Temporarily disables a script-container from meeting requirements. // @Author aufdemrand // // @Description // Cools down a script-container. If an interact-container, when on cooldown, scripts will not pass a // requirements check allowing the next highest priority script to trigger. If any other type of script, a // manual requirements check (<s@script_name.requirements.check>) will also return false until the cooldown // period is completed. Cooldown requires a type (player or global), a script, and a duration. It also requires // a valid link to a dPlayer if using player-type cooldown. // // Cooldown periods are persistent through a server restart as they are saved in the saves.yml. // // @Tags // <s@script_name.cooled_down[player]> will return whether the script is cooled down // <s@script_name.cooldown> will return the duration of the cooldown in progress. // <[email protected]> will also check script cooldown, as well as any requirements. // // @Usage // Use to keep the current interact script from meeting requirements. // - cooldown 20m // // @Usage // Use to keep a player from activating a script for a specified duration. // - cooldown 11h s:s@bonus_script // - cooldown 5s s:s@hit_indicator // // @Usage // Use the 'global' argument to indicate the script to be on cooldown for all players. // - cooldown global 24h s:s@daily_treasure_offering // // @Example TODO // // --> registerCoreMember(CooldownCommand.class, "COOLDOWN", "cooldown [<duration>] (global) (s:<script>)", 1); // <--[command] // @Name CopyBlock // @Usage copyblock [location:<location>] [to:<location>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(CopyBlockCommand.class, "COPYBLOCK", "copyblock [location:<location>] [to:<location>]", 1); // <--[command] // @Name CreateWorld // @Usage createworld [<name>] (g:<generator>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(CreateWorldCommand.class, "CREATEWORLD", "createworld [<name>] (g:<generator>)", 1); // <--[command] // @Name Define // @Usage define [<id>] [<value>] // @Required 2 // @Stable 1.0 // @Short Creates a temporary variable inside a script queue. // @Author aufdemrand // // @Description // Definitions are queue-level (or script-level) 'variables' that can be used throughout a script, once // defined, by using %'s around the definition id/name. Definitions are only valid on the current queue and are // not transferred to any new queues constructed within the script, such as a 'run' command, without explicitly // specifying to do so. // // Definitions are lighter and faster than creating a temporary flag, but unlike flags, are only a single entry, // that is, you can't add or remove from the definition, but you can re-create it if you wish to specify a new // value. Definitions are also automatically destroyed when the queue is completed, so there is no worry for // leaving unused data hanging around. // // Definitions are also resolved before replaceable tags, meaning you can use them within tags, even as an // attribute. ie. <%player%.name> // // @Usage // Use to make complex tags look less complex, and scripts more readable. // - narrate 'You invoke your power of notice...' // - define range '<player.flag[range_level].mul[3]>' // - define blocks '<player.flag[noticeable_blocks>' // - narrate '[NOTICE] You have noticed <player.location.find.blocks[%blocks%].within[%range].size> // blocks in the area that may be of interest.' // // @Usage // Use to keep the value of a replaceable tag that you might use many times within a single script. Definitions // can be faster and cleaner than reusing a replaceable tag over and over. // - define arg1 <c.args.get[1]> // - if %arg1% == hello narrate 'Hello!' // - if %arg1% == goodbye narrate 'Goodbye!' // // @Usage // Use to pass some important information (arguments) on to another queue. // - run 'new_task' d:hello|world // 'new_task' now has some definitions, %1% and %2%, that contains the contents specified, 'hello' and 'world'. // // @Example // // --> registerCoreMember(DefineCommand.class, "DEFINE", "define [<id>] [<value>]", 2); // <--[command] // @Name Determine // @Usage determine [<value>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(DetermineCommand.class, "DETERMINE", "determine [<value>]", 1); // <--[command] // @Name Disengage // @Usage disengage (npc:<npc>) // @Required 0 // @Stable 1.0 // @Short Enables a NPCs triggers that have been temporarily disabled by the engage command. // @Author aufdemrand // // @Description // Re-enables any toggled triggers that have been disabled by disengage. Using // disengage inside scripts must have a NPC to reference, or one may be specified // by supplying a valid dNPC object with the npc argument. // // This is mostly regarded as an 'interact script command', though it may be used inside // other script types. This is because disengage works with the trigger system, which is an // interact script-container feature. // // NPCs that are interacted with while engaged will fire an 'on unavailable' assignment // script-container action. // // @See Engage Command // // @Usage // Use to reenable a NPC's triggers, disabled via 'engage'. // - engage // - chat 'Be right there!' // - walkto <player.location> // - wait 5s // - disengage // // @Example // --> registerCoreMember(DisengageCommand.class, "DISENGAGE", "disengage (npc:<npc>)", 0); // <--[command] // @Name DisplayItem // @Usage displayitem (remove) [<item>] [<location>] (duration:<value>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(DisplayItemCommand.class, "DISPLAYITEM", "displayitem (remove) [<item>] [<location>] (duration:<value>)", 2); // <--[command] // @Name Drop // @Usage drop [<item>/<entity>/<xp>] [<location>] (qty:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(DropCommand.class, "DROP", "drop [<item>/<entity>/<xp>] [<location>] (qty:<#>)", 1); // <--[command] // @Name Engage // @Usage engage (<duration>) (npc:<npc>) // @Required 0 // @Stable 1.0 // @Short Temporarily disables a NPCs toggled interact script-container triggers. // @Author aufdemrand // // @Description // Engaging a NPC will temporarily disable any interact script-container triggers. To reverse // this behavior, use either the disengage command, or specify a duration in which the engage // should timeout. Specifying an engage without a duration will render the NPC engaged until // a disengage is used on the NPC. Engaging a NPC affects all players attempting to interact // with the NPC. // // While engaged, all triggers and actions associated with triggers will not 'fire', except // the 'on unavailable' assignment script-container action, which will fire for triggers that // were enabled previous to the engage command. // // Engage can be useful when NPCs are carrying out a task that shouldn't be interrupted, or // to provide a good way to avoid accidental 'retrigger'. // // @See Disengage Command // // @Tags // <[email protected]> will return true if the NPC is currently engaged, false otherwise. // // @Usage // Use to make a NPC appear 'busy'. // - engage // - chat 'Give me a few minutes while I mix you a potion!' // - walkto <npc.anchor[mixing_station]> // - wait 10s // - walkto <npc.anchor[service_station]> // - chat 'Here you go!' // - give potion <player> // - disengage // // @Usage // Use to avoid 'retrigger'. // - engage 5s // - take quest_item // - flag player finished_quests:->:super_quest // // @Example // // --> registerCoreMember(EngageCommand.class, "ENGAGE", "engage (<duration>) (npc:<npc>)", 0); // <--[command] // @Name Engrave // @Usage engrave (set/remove) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(EngraveCommand.class, "ENGRAVE", "engrave (set/remove)", 0); // <--[command] // @Name Equip // @Usage equip (hand:<item>) (head:<item>) (chest:<item>) (legs:<item>) (boots:<item>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(EquipCommand.class, "EQUIP", "equip (hand:<item>) (head:<item>) (chest:<item>) (legs:<item>) (boots:<item>)", 1); // <--[command] // @Name Execute // @Usage execute [as_player/as_op/as_npc/as_server] [<Bukkit command>] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ExecuteCommand.class, "EXECUTE", "execute [as_player/as_op/as_npc/as_server] [<Bukkit command>]", 2); // <--[command] // @Name Experience // @Usage experience [{set}/give/take] (level) [<#>] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ExperienceCommand.class, "EXPERIENCE", "experience [{set}/give/take] (level) [<#>]", 2); // <--[command] // @Name Explode // @Usage explode (power:<#.#>) (<location>) (fire) (breakblocks) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ExplodeCommand.class, "EXPLODE", "explode (power:<#.#>) (<location>) (fire) (breakblocks)", 0); // <--[command] // @Name Fail // @Usage fail (script:<name>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FailCommand.class, "FAIL", "fail (script:<name>)", 0); // <--[command] // @Name Feed // @Usage feed (amt:<#>) (target:<entity>|...) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FeedCommand.class, "FEED", "feed (amt:<#>) (target:<entity>|...)", 0); // <--[command] // @Name Finish // @Usage finish (script:<name>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FinishCommand.class, "FINISH", "finish (script:<name>)", 0); // <--[command] // @Name Firework // @Usage firework (<location>) (power:<#>) (type:<name>/random) (primary:<color>|...) (fade:<color>|...) (flicker) (trail) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FireworkCommand.class, "FIREWORK", "firework (<location>) (power:<#>) (type:<name>/random) (primary:<color>|...) (fade:<color>|...) (flicker) (trail)", 0); // <--[command] // @Name Fish // @Usage fish (catchfish) (stop) (<location>) (catchpercent:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FishCommand.class, "FISH", "fish (catchfish) (stop) (<location>) (catchpercent:<#>)", 1); // <--[command] // @Name Flag // @Usage flag ({player}/npc/global) [<name>([<#>])](:<action>)[:<value>] (duration:<value>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FlagCommand.class, "FLAG", "flag ({player}/npc/global) [<name>([<#>])](:<action>)[:<value>] (duration:<value>)", 1); // <--[command] // @Name Fly // @Usage fly (cancel) [<entity>|...] (origin:<location>) (destinations:<location>|...) (speed:<#.#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FlyCommand.class, "FLY", "fly (cancel) [<entity>|...] (origin:<location>) (destinations:<location>|...) (speed:<#.#>)", 1); // <--[command] // @Name Follow // @Usage follow (stop) (lead:<#.#>) (target:<entity>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(FollowCommand.class, "FOLLOW", "follow (stop) (lead:<#.#>) (target:<entity>)", 0); // <--[command] // @Name ForEach // @Usage foreach [<object>|...] [<commands>] // @Required 2 // @Stable Experimental // @Short Loops through a dList, running a set of commands for each item. // @Author Morphan1/mcmonkey // // @Description // Loops through a dList of any type. For each item in the dList, the specified commands will be ran for // that item. To call the value of the item while in the loop, you can use %value%. // // @Usage // Use to run commands on multiple items. // - foreach li@e@123|n@424|p@BobBarker { // - announce "There's something at <%value%.location>!" // } // // @Example // // --> registerCoreMember(ForEachCommand.class, "FOREACH", "foreach [<object>|...] [<commands>]", 2); // <--[command] // @Name Give // @Usage give [money/<item>] (qty:<#>) (engrave) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(GiveCommand.class, "GIVE", "give [money/<item>] (qty:<#>) (engrave)", 1); // <--[command] // @Name Group // @Usage group [add/remove] [<group>] (world:<name>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(GroupCommand.class, "GROUP", "group [add/remove] [<group>] (world:<name>)", 2); // <--[command] // @Name Head // @Usage head (player) [skin:<name>] // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(HeadCommand.class, "HEAD", "head (player) [skin:<name>]", 0); // <--[command] // @Name Heal // @Usage heal (<#.#>) (<entity>|...) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(HealCommand.class, "HEAL", "heal (<#.#>) (<entity>|...)", 0); // <--[command] // @Name Health // @Usage health [<#>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(HealthCommand.class, "HEALTH", "health [<#>]", 1); // <--[command] // @Name Hurt // @Usage hurt (<#.#>) (<entity>|...) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(HurtCommand.class, "HURT", "hurt (<#.#>) (<entity>|...)", 0); // <--[command] // @Name If // @Usage if [<value>] (!)(<operator> <value>) (&&/|| ...) [<commands>] (else <commands>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(IfCommand.class, "IF", "if [<value>] (!)(<operator> <value>) (&&/|| ...) [<commands>] (else <commands>)", 2); // <--[command] // @Name Inventory // @Usage inventory [open/copy/move/swap/add/remove/keep/exclude/fill/clear] [destination:<inventory>] (origin:<inventory>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(InventoryCommand.class, "INVENTORY", "inventory [open/copy/move/swap/add/remove/keep/exclude/fill/clear] [destination:<inventory>] (origin:<inventory>)", 2); // <--[command] // @Name Invisible // @Usage invisible [player/npc] [state:true/false/toggle] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(InvisibleCommand.class, "INVISIBLE", "invisible [player/npc] [state:true/false/toggle]", 2); // <--[command] // @Name Leash // @Usage leash (cancel) [<entity>|...] (holder:<entity>/<location>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(LeashCommand.class, "LEASH", "leash (cancel) [<entity>|...] (holder:<entity>/<location>)", 1); // <--[command] // @Name Listen // @Usage listen ({new}/cancel/finish) [kill/block/item/itemdrop/travel] [<requirements>] [script:<name>] (id:<name>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ListenCommand.class, "LISTEN", "listen ({new}/cancel/finish) [kill/block/item/itemdrop/travel] [<requirements>] [script:<name>] (id:<name>)", 2); // <--[command] // @Name Log // @Usage log [<text>] (type:severe/info/warning/fine/finer/finest) [file:<name>] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(LogCommand.class, "LOG", "log [<text>] (type:severe/info/warning/fine/finer/finest) [file:<name>]", 2); // <--[command] // @Name Look // @Usage look (<entity>|...) [<location>] (duration:<duration>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(LookCommand.class, "LOOK", "look (<entity>|...) [<location>] (duration:<duration>)", 1); // <--[command] // @Name LookClose // @Usage lookclose [state:true/false] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(LookcloseCommand.class, "LOOKCLOSE", "lookclose [state:true/false]", 1); // <--[command] // @Name Midi // @Usage midi [file:<name>] [<location>/listeners:<player>|...] (tempo:<#.#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(MidiCommand.class, "MIDI", "midi [file:<name>] [<location>/listeners:<player>|...] (tempo:<#.#>)", 1); // <--[command] // @Name Mount // @Usage mount (cancel) [<entity>|...] (<location>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(MountCommand.class, "MOUNT", "mount (cancel) [<entity>|...] (<location>)", 0); // <--[command] // @Name ModifyBlock // @Usage modifyblock [<location>] [<block>] (radius:<#>) (height:<#>) (depth:<#>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ModifyBlockCommand.class, "MODIFYBLOCK", "modifyblock [<location>] [<block>] (radius:<#>) (height:<#>) (depth:<#>)", 2); // <--[command] // @Usage nameplate [<chatcolor>] [set:<text>] (target:<player>) +--> Requires ProtocolLib // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(NameplateCommand.class, "NAMEPLATE", "nameplate [<chatcolor>] [set:<text>] (target:<player>) +--> Requires ProtocolLib", 1); // <--[command] // @Name Narrate // @Usage narrate ["<text>"] (targets:<player>|...) (format:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(NarrateCommand.class, "NARRATE", "narrate [\"<text>\"] (targets:<player>|...) (format:<name>)", 1); // <--[command] // @Name Note // @Usage note [<Notable dObject>] [as:<name>] // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(NoteCommand.class, "NOTE", "note [<Notable dObject>] [as:<name>]", 2); // <--[command] // @Name Oxygen // @Usage oxygen (type:maximum/remaining) (mode:set/add/remove) [qty:<#>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(OxygenCommand.class, "OXYGEN", "oxygen (type:maximum/remaining) (mode:set/add/remove) [qty:<#>]", 1); // <--[command] // @Name PlayEffect // @Usage playeffect [<location>] [effect:<name>] (data:<#.#>) (visibility:<#.#>) (qty:<#>) (offset:<#.#>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PlayEffectCommand.class, "PLAYEFFECT", "playeffect [<location>] [effect:<name>] (data:<#.#>) (visibility:<#.#>) (qty:<#>) (offset:<#.#>)", 2); // <--[command] // @Name PlaySound // @Usage playsound [<location>] [sound:<name>] (volume:<#.#>) (pitch:<#.#>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PlaySoundCommand.class, "PLAYSOUND", "playsound [<location>] [sound:<name>] (volume:<#.#>) (pitch:<#.#>)", 2); // <--[command] // @Name Permission // @Usage permission [add|remove] [permission] (player:<name>) (group:<name>) (world:<name>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PermissionCommand.class, "PERMISSION", "permission [add|remove] [permission] (player:<name>) (group:<name>) (world:<name>)", 2); // <--[command] // @Name Pose // @Usage pose (player/npc) [id:<name>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PoseCommand.class, "POSE", "pose (player/npc) [id:<name>]", 1); // <--[command] // @Name Pause // @Usage pause [waypoints/navigation] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(PauseCommand.class, "PAUSE", "pause [waypoints/navigation]", 1); // <--[command] // @Name Queue // @Usage queue (queue:<id>) [clear/pause/resume/delay:<#>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(QueueCommand.class, "QUEUE", "queue (queue:<id>) [clear/pause/resume/delay:<#>]", 1); // <--[command] // @Name Random // @Usage random [<#>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RandomCommand.class, "RANDOM", "random [<#>]", 1); // <--[command] // @Name Remove // @Usage remove [<entity>|...] (region:<name>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RemoveCommand.class, "REMOVE", "remove [<entity>|...] (region:<name>)", 0); // <--[command] // @Name Rename // @Usage rename [<npc>] [<name>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RenameCommand.class, "RENAME", "rename [<npc>] [<name>]", 1); // <--[command] // @Name Repeat // @Usage repeat [<amount>] [<commands>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RepeatCommand.class, "REPEAT", "repeat [<amount>] [<commands>]", 1); // <--[command] // @Name Reset // @Usage reset [fails/finishes/cooldown] (script:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ResetCommand.class, "RESET", "reset [fails/finishes/cooldown] (script:<name>)", 1); // <--[command] // @Name Run // @Usage run [<script>] (path:<name>) (as:<player>/<npc>) (define:<element>|...) (id:<name>) (delay:<value>) (loop) (qty:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RunCommand.class, "RUN", "run [<script>] (path:<name>) (as:<player>/<npc>) (define:<element>|...) (id:<name>) (delay:<value>) (loop) (qty:<#>)", 1); // <--[command] // @Name RunTask // @Deprecated This has been replaced by the Run command. // @Usage runtask [<name>] (instantly) (queue(:<name>)) (delay:<#>) (define:<element>|...) // @Required 1 // @Stable Stable // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(RuntaskCommand.class, "RUNTASK", "runtask [<name>] (instantly) (queue(:<name>)) (delay:<#>) (define:<element>|...)", 1); // <--[command] // @Name Scoreboard // @Usage scoreboard [set/remove/show/hide] [<name>] [value:<name>] (priority:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ScoreboardCommand.class, "SCOREBOARD", "scoreboard [set/remove/show/hide] [<name>] [value:<name>] (priority:<#>)", 1); // <--[command] // @Name Scribe // @Usage scribe [script:<name>] (give/drop/equip) (<item>) (<location>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ScribeCommand.class, "SCRIBE", "scribe [script:<name>] (give/drop/equip) (<item>) (<location>)", 1); // <--[command] // @Name Shoot // @Usage shoot [<entity>|...] (origin:<entity>/<location>) (destination:<location>) [{calculated} (height:<#.#>) (gravity:<#.#>)]/[custom speed:<#.#> duration:<value>] (script:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ShootCommand.class, "SHOOT", "shoot [<entity>|...] (origin:<entity>/<location>) (destination:<location>) [{calculated} (height:<#.#>) (gravity:<#.#>)]/[custom speed:<#.#> duration:<value>] (script:<name>)", 1); // <--[command] // @Name ShowFake // @Usage showfake [<material>] [<location>|...] (d:<duration>{10s}) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ShowFakeCommand.class, "SHOWFAKE", "showfake [<material>] [<location>|...] (d:<duration>{10s})", 2); // <--[command] // @Name Sign // @Usage sign (type:{sign_post}/wall_sign) ["<line>|..."] [<location>] (direction:n/e/w/s) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(SignCommand.class, "SIGN", "sign (type:{sign_post}/wall_sign) [\"<line>|...\"] [<location>] (direction:n/e/w/s)", 1); // <--[command] // @Name Sit // @Usage sit (<location>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(SitCommand.class, "SIT", "sit (<location>)", 0); // <--[command] // @Name Spawn // @Usage spawn [<entity>|...] (<location>) (target:<entity>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(SpawnCommand.class, "SPAWN", "spawn [<entity>|...] (<location>) (target:<entity>)", 1); // <--[command] // @Name Stand // @Usage stand // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(StandCommand.class, "STAND", "stand", 0); // <--[command] // @Name Strike // @Usage strike (no_damage) [<location>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(StrikeCommand.class, "STRIKE", "strike (no_damage) [<location>]", 1); // <--[command] // @Name Switch // @Usage switch [<location>] (state:[{toggle}/on/off]) (duration:<value>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(SwitchCommand.class, "SWITCH", "switch [<location>] (state:[{toggle}/on/off]) (duration:<value>)", 1); // <--[command] // @Name Take // @Usage take [money/iteminhand/<item>] (qty:<#>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(TakeCommand.class, "TAKE", "take [money/iteminhand/<item>] (qty:<#>)", 1); // <--[command] // @Name Teleport // @Usage teleport (<entity>|...) (<location>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(TeleportCommand.class, "TELEPORT", "teleport (<entity>|...) (<location>)", 1); // <--[command] // @Name Time // @Usage time [type:{global}/player] [<value>] (world:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(TimeCommand.class, "TIME", "time [type:{global}/player] [<value>] (world:<name>)", 1); // <--[command] // @Name Trigger // @Usage trigger [name:chat/click/damage/proximity] (state:true/false) (cooldown:<#.#>) (radius:<#>) // @Required 2 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(TriggerCommand.class, "TRIGGER", "trigger [name:chat/click/damage/proximity] (state:true/false) (cooldown:<#.#>) (radius:<#>)", 2); // <--[command] // @Name Viewer // @Usage viewer ({create <location>}/modify/remove) [id:<name>] (type:{sign_post}/wall_sign) (display:{location}/score/logged_in) (direction:n/e/w/s) // @Required 1 // @Stable Experimental // @Short Creates a sign that auto-updates with information. // @Author Morphan1 // // @Description // Creates a sign that auto-updates with information about a player, including their location, score, and // whether they're logged in or not. // // @Tags // None // // @Usage // Create a sign that shows the location of a player on a wall // - viewer player:ThatGuy create 113,76,-302,world id:PlayerLoc1 type:wall_sign display:location // // @Example // Todo // --> registerCoreMember(ViewerCommand.class, "VIEWER", "viewer ({create <location>}/modify/remove) [id:<name>] (type:{sign_post}/wall_sign) (display:{location}/score/logged_in) (direction:n/e/w/s)", 2); // <--[command] // @Name Vulnerable // @Usage vulnerable (state:{true}/false/toggle) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(VulnerableCommand.class, "VULNERABLE", "vulnerable (state:{true}/false/toggle)", 0); // <--[command] // @Name Wait // @Usage wait (<duration>) (queue:<name>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(WaitCommand.class, "WAIT", "wait (<duration>) (queue:<name>)", 0); // <--[command] // @Name Walk, WalkTo // @Usage walkto [<location>] (speed:<#>) (auto_range) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(WalkCommand.class, "WALK, WALKTO", "walk [<location>] (speed:<#>) (auto_range)", 1); // <--[command] // @Name Weather // @Usage weather [type:{global}/player] [sunny/storm/thunder] (world:<name>) // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(WeatherCommand.class, "WEATHER", "weather [type:{global}/player] [sunny/storm/thunder] (world:<name>)", 1); // <--[command] // @Name Yaml // @Usage yaml [load/create/save:<file>]/[write:<key>]/[write:<key> value:<value>] [id:<name>] // @Required 1 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(YamlCommand.class, "YAML", "yaml [load/create/save:<file>]/[write:<key>]/[write:<key> value:<value>] [id:<name>]", 1); // <--[command] // @Name Zap // @Usage zap (<script>:)[<step>] (<duration>) // @Required 0 // @Stable Todo // @Short Todo // @Author Todo // @Description // Todo // @Tags // Todo // @Usage // Todo // @Example // Todo // --> registerCoreMember(ZapCommand.class, "ZAP", "zap (<script>:)[<step>] (<duration>)", 0); dB.echoApproval("Loaded core commands: " + instances.keySet().toString()); }
diff --git a/src/biz/bokhorst/xprivacy/XPrivacy.java b/src/biz/bokhorst/xprivacy/XPrivacy.java index 264bac9a..fa195eec 100644 --- a/src/biz/bokhorst/xprivacy/XPrivacy.java +++ b/src/biz/bokhorst/xprivacy/XPrivacy.java @@ -1,454 +1,455 @@ package biz.bokhorst.xprivacy; import java.lang.reflect.Constructor; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.Random; import android.annotation.SuppressLint; import android.content.Context; import android.os.Binder; import android.os.Build; import android.os.Process; import android.util.Log; import de.robv.android.xposed.IXposedHookZygoteInit; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.XC_MethodHook; import static de.robv.android.xposed.XposedHelpers.findClass; @SuppressLint("DefaultLocale") public class XPrivacy implements IXposedHookLoadPackage, IXposedHookZygoteInit { private static String mSecret = null; private static boolean mAccountManagerHooked = false; private static boolean mActivityManagerHooked = false; private static boolean mClipboardManagerHooked = false; private static boolean mConnectivityManagerHooked = false; private static boolean mLocationManagerHooked = false; private static boolean mPackageManagerHooked = false; private static boolean mSensorManagerHooked = false; private static boolean mTelephonyManagerHooked = false; private static boolean mWindowManagerHooked = false; private static boolean mWiFiManagerHooked = false; private static List<String> mListHookError = new ArrayList<String>(); // http://developer.android.com/reference/android/Manifest.permission.html @SuppressLint("InlinedApi") public void initZygote(StartupParam startupParam) throws Throwable { // Check for LBE security master if (Util.hasLBE()) return; Util.log(null, Log.INFO, String.format("Load %s", startupParam.modulePath)); // Generate secret mSecret = Long.toHexString(new Random().nextLong()); PrivacyService.setupDatabase(); // System server try { // frameworks/base/services/java/com/android/server/SystemServer.java Class<?> cSystemServer = Class.forName("com.android.server.SystemServer"); Method mMain = cSystemServer.getDeclaredMethod("main", String[].class); XposedBridge.hookMethod(mMain, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { PrivacyService.register(mListHookError, mSecret); } }); } catch (Throwable ex) { Util.bug(null, ex); } // App widget manager hookAll(XAppWidgetManager.getInstances(), mSecret); // Application hookAll(XApplication.getInstances(), mSecret); // Audio record hookAll(XAudioRecord.getInstances(), mSecret); // Binder device hookAll(XBinder.getInstances(), mSecret); // Bluetooth adapater hookAll(XBluetoothAdapter.getInstances(), mSecret); // Bluetooth device hookAll(XBluetoothDevice.getInstances(), mSecret); // Camera hookAll(XCamera.getInstances(), mSecret); // Content resolver hookAll(XContentResolver.getInstances(), mSecret); // Context wrapper hookAll(XContextImpl.getInstances(), mSecret); // Environment hookAll(XEnvironment.getInstances(), mSecret); // InetAddress hookAll(XInetAddress.getInstances(), mSecret); // InputDevice hookAll(XInputDevice.getInstances(), mSecret); // IO bridge hookAll(XIoBridge.getInstances(), mSecret); // Media recorder hookAll(XMediaRecorder.getInstances(), mSecret); // Network info hookAll(XNetworkInfo.getInstances(), mSecret); // Network interface hookAll(XNetworkInterface.getInstances(), mSecret); // NFC adapter hookAll(XNfcAdapter.getInstances(), mSecret); // Package manager service hookAll(XProcess.getInstances(), mSecret); // Process builder hookAll(XProcessBuilder.getInstances(), mSecret); // Resources hookAll(XResources.getInstances(), mSecret); // Runtime hookAll(XRuntime.getInstances(), mSecret); // Settings secure hookAll(XSettingsSecure.getInstances(), mSecret); // SMS manager hookAll(XSmsManager.getInstances(), mSecret); // System properties hookAll(XSystemProperties.getInstances(), mSecret); // Web view hookAll(XWebView.getInstances(), mSecret); // Intent receive hookAll(XActivityThread.getInstances(), mSecret); // Intent send hookAll(XActivity.getInstances(), mSecret); } public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable { // Check for LBE security master if (Util.hasLBE()) return; // Log load Util.log(null, Log.INFO, String.format("Load package=%s uid=%d", lpparam.packageName, Process.myUid())); // Skip hooking self String self = XPrivacy.class.getPackage().getName(); if (lpparam.packageName.equals(self)) { hookAll(XUtilHook.getInstances(), lpparam.classLoader, mSecret); return; } // Build SERIAL if (PrivacyManager.getRestriction(null, Process.myUid(), PrivacyManager.cIdentification, "SERIAL", mSecret)) XposedHelpers.setStaticObjectField(Build.class, "SERIAL", PrivacyManager.getDefacedProp(Process.myUid(), "SERIAL")); // Advertising Id try { Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient$Info", false, lpparam.classLoader); hookAll(XAdvertisingIdClientInfo.getInstances(), lpparam.classLoader, mSecret); } catch (Throwable ignored) { } // Google auth try { Class.forName("com.google.android.gms.auth.GoogleAuthUtil", false, lpparam.classLoader); hookAll(XGoogleAuthUtil.getInstances(), lpparam.classLoader, mSecret); } catch (Throwable ignored) { } // Location client try { Class.forName("com.google.android.gms.location.LocationClient", false, lpparam.classLoader); hookAll(XLocationClient.getInstances(), lpparam.classLoader, mSecret); } catch (Throwable ignored) { } } public static void handleGetSystemService(XHook hook, String name, Object instance) { Util.log(hook, Log.INFO, "getSystemService " + name + "=" + instance.getClass().getName() + " uid=" + Binder.getCallingUid()); if ("android.telephony.MSimTelephonyManager".equals(instance.getClass().getName())) { Util.log(hook, Log.WARN, "Telephone service=" + Context.TELEPHONY_SERVICE); Class<?> clazz = instance.getClass(); while (clazz != null) { Util.log(hook, Log.WARN, "Class " + clazz); for (Method method : clazz.getDeclaredMethods()) Util.log(hook, Log.WARN, "Declared " + method); clazz = clazz.getSuperclass(); } } if (name.equals(Context.ACCOUNT_SERVICE)) { // Account manager if (!mAccountManagerHooked) { hookAll(XAccountManager.getInstances(instance), mSecret); mAccountManagerHooked = true; } } else if (name.equals(Context.ACTIVITY_SERVICE)) { // Activity manager if (!mActivityManagerHooked) { hookAll(XActivityManager.getInstances(instance), mSecret); mActivityManagerHooked = true; } } else if (name.equals(Context.CLIPBOARD_SERVICE)) { // Clipboard manager if (!mClipboardManagerHooked) { XPrivacy.hookAll(XClipboardManager.getInstances(instance), mSecret); mClipboardManagerHooked = true; } } else if (name.equals(Context.CONNECTIVITY_SERVICE)) { // Connectivity manager if (!mConnectivityManagerHooked) { hookAll(XConnectivityManager.getInstances(instance), mSecret); mConnectivityManagerHooked = true; } } else if (name.equals(Context.LOCATION_SERVICE)) { // Location manager if (!mLocationManagerHooked) { hookAll(XLocationManager.getInstances(instance), mSecret); mLocationManagerHooked = true; } } else if (name.equals("PackageManager")) { // Package manager if (!mPackageManagerHooked) { hookAll(XPackageManager.getInstances(instance), mSecret); mPackageManagerHooked = true; } } else if (name.equals(Context.SENSOR_SERVICE)) { // Sensor manager if (!mSensorManagerHooked) { hookAll(XSensorManager.getInstances(instance), mSecret); mSensorManagerHooked = true; } } else if (name.equals(Context.TELEPHONY_SERVICE)) { // Telephony manager if (!mTelephonyManagerHooked) { hookAll(XTelephonyManager.getInstances(instance), mSecret); mTelephonyManagerHooked = true; } } else if (name.equals(Context.WINDOW_SERVICE)) { // Window manager if (!mWindowManagerHooked) { XPrivacy.hookAll(XWindowManager.getInstances(instance), mSecret); mWindowManagerHooked = true; } } else if (name.equals(Context.WIFI_SERVICE)) { // WiFi manager if (!mWiFiManagerHooked) { XPrivacy.hookAll(XWifiManager.getInstances(instance), mSecret); mWiFiManagerHooked = true; } } } public static void hookAll(List<XHook> listHook, String secret) { for (XHook hook : listHook) hook(hook, secret); } public static void hookAll(List<XHook> listHook, ClassLoader classLoader, String secret) { for (XHook hook : listHook) hook(hook, classLoader, secret); } private static void hook(XHook hook, String secret) { hook(hook, null, secret); } private static void hook(final XHook hook, ClassLoader classLoader, String secret) { // Check SDK version Hook md = null; String message = null; if (hook.getRestrictionName() == null) { if (hook.getSdk() == 0) message = "No SDK specified for " + hook; } else { md = PrivacyManager.getHook(hook.getRestrictionName(), hook.getSpecifier()); if (md == null) message = "Hook not found " + hook; else if (hook.getSdk() != 0) message = "SDK not expected for " + hook; } if (message != null) { mListHookError.add(message); Util.log(hook, Log.ERROR, message); } int sdk = 0; if (hook.getRestrictionName() == null) sdk = hook.getSdk(); else if (md != null) sdk = md.getSdk(); if (Build.VERSION.SDK_INT < sdk) return; // Provide secret hook.setSecret(secret); try { // Create hook method XC_MethodHook methodHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { try { if (Process.myUid() <= 0) return; XParam xparam = XParam.fromXposed(param); hook.before(xparam); if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); param.setObjectExtra("xextra", xparam.getExtras()); } catch (Throwable ex) { Util.bug(null, ex); } } @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { if (!param.hasThrowable()) try { if (Process.myUid() <= 0) return; XParam xparam = XParam.fromXposed(param); xparam.setExtras(param.getObjectExtra("xextra")); hook.after(xparam); if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); } catch (Throwable ex) { Util.bug(null, ex); } } }; // Find class Class<?> hookClass = null; try { // hookClass = Class.forName(hook.getClassName()); hookClass = findClass(hook.getClassName(), classLoader); } catch (Throwable ex) { message = String.format("Class not found for %s", hook); mListHookError.add(message); Util.log(hook, hook.isOptional() ? Log.WARN : Log.ERROR, message); } // Get members List<Member> listMember = new ArrayList<Member>(); Class<?> clazz = hookClass; while (clazz != null) { if (hook.getMethodName() == null) { for (Constructor<?> constructor : clazz.getDeclaredConstructors()) if (Modifier.isPublic(constructor.getModifiers()) ? hook.isVisible() : !hook.isVisible()) listMember.add(constructor); + break; } else { for (Method method : clazz.getDeclaredMethods()) if (method.getName().equals(hook.getMethodName()) && (Modifier.isPublic(method.getModifiers()) ? hook.isVisible() : !hook.isVisible())) listMember.add(method); } clazz = clazz.getSuperclass(); } // Hook members for (Member member : listMember) try { XposedBridge.hookMethod(member, methodHook); } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } // Check if members found if (listMember.isEmpty() && !hook.getClassName().startsWith("com.google.android.gms")) { message = String.format("Method not found for %s", hook); mListHookError.add(message); Util.log(hook, hook.isOptional() ? Log.WARN : Log.ERROR, message); } } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } } // WORKAROUND: when a native lib is loaded after hooking, the hook is undone private static List<XC_MethodHook.Unhook> mUnhookNativeMethod = new ArrayList<XC_MethodHook.Unhook>(); @SuppressWarnings("unused") private static void registerNativeMethod(final XHook hook, Method method, XC_MethodHook.Unhook unhook) { if (Process.myUid() > 0) { synchronized (mUnhookNativeMethod) { mUnhookNativeMethod.add(unhook); Util.log(hook, Log.INFO, "Native " + method + " uid=" + Process.myUid()); } } } @SuppressWarnings("unused") private static void hookCheckNative() { try { XC_MethodHook hook = new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { if (Process.myUid() > 0) try { synchronized (mUnhookNativeMethod) { Util.log(null, Log.INFO, "Loading " + param.args[0] + " uid=" + Process.myUid() + " count=" + mUnhookNativeMethod.size()); for (XC_MethodHook.Unhook unhook : mUnhookNativeMethod) { XposedBridge.hookMethod(unhook.getHookedMethod(), unhook.getCallback()); unhook.unhook(); } } } catch (Throwable ex) { Util.bug(null, ex); } } }; Class<?> runtimeClass = Class.forName("java.lang.Runtime"); for (Method method : runtimeClass.getDeclaredMethods()) if (method.getName().equals("load") || method.getName().equals("loadLibrary")) { XposedBridge.hookMethod(method, hook); Util.log(null, Log.WARN, "Hooked " + method); } } catch (Throwable ex) { Util.bug(null, ex); } } }
true
true
private static void hook(final XHook hook, ClassLoader classLoader, String secret) { // Check SDK version Hook md = null; String message = null; if (hook.getRestrictionName() == null) { if (hook.getSdk() == 0) message = "No SDK specified for " + hook; } else { md = PrivacyManager.getHook(hook.getRestrictionName(), hook.getSpecifier()); if (md == null) message = "Hook not found " + hook; else if (hook.getSdk() != 0) message = "SDK not expected for " + hook; } if (message != null) { mListHookError.add(message); Util.log(hook, Log.ERROR, message); } int sdk = 0; if (hook.getRestrictionName() == null) sdk = hook.getSdk(); else if (md != null) sdk = md.getSdk(); if (Build.VERSION.SDK_INT < sdk) return; // Provide secret hook.setSecret(secret); try { // Create hook method XC_MethodHook methodHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { try { if (Process.myUid() <= 0) return; XParam xparam = XParam.fromXposed(param); hook.before(xparam); if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); param.setObjectExtra("xextra", xparam.getExtras()); } catch (Throwable ex) { Util.bug(null, ex); } } @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { if (!param.hasThrowable()) try { if (Process.myUid() <= 0) return; XParam xparam = XParam.fromXposed(param); xparam.setExtras(param.getObjectExtra("xextra")); hook.after(xparam); if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); } catch (Throwable ex) { Util.bug(null, ex); } } }; // Find class Class<?> hookClass = null; try { // hookClass = Class.forName(hook.getClassName()); hookClass = findClass(hook.getClassName(), classLoader); } catch (Throwable ex) { message = String.format("Class not found for %s", hook); mListHookError.add(message); Util.log(hook, hook.isOptional() ? Log.WARN : Log.ERROR, message); } // Get members List<Member> listMember = new ArrayList<Member>(); Class<?> clazz = hookClass; while (clazz != null) { if (hook.getMethodName() == null) { for (Constructor<?> constructor : clazz.getDeclaredConstructors()) if (Modifier.isPublic(constructor.getModifiers()) ? hook.isVisible() : !hook.isVisible()) listMember.add(constructor); } else { for (Method method : clazz.getDeclaredMethods()) if (method.getName().equals(hook.getMethodName()) && (Modifier.isPublic(method.getModifiers()) ? hook.isVisible() : !hook.isVisible())) listMember.add(method); } clazz = clazz.getSuperclass(); } // Hook members for (Member member : listMember) try { XposedBridge.hookMethod(member, methodHook); } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } // Check if members found if (listMember.isEmpty() && !hook.getClassName().startsWith("com.google.android.gms")) { message = String.format("Method not found for %s", hook); mListHookError.add(message); Util.log(hook, hook.isOptional() ? Log.WARN : Log.ERROR, message); } } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } }
private static void hook(final XHook hook, ClassLoader classLoader, String secret) { // Check SDK version Hook md = null; String message = null; if (hook.getRestrictionName() == null) { if (hook.getSdk() == 0) message = "No SDK specified for " + hook; } else { md = PrivacyManager.getHook(hook.getRestrictionName(), hook.getSpecifier()); if (md == null) message = "Hook not found " + hook; else if (hook.getSdk() != 0) message = "SDK not expected for " + hook; } if (message != null) { mListHookError.add(message); Util.log(hook, Log.ERROR, message); } int sdk = 0; if (hook.getRestrictionName() == null) sdk = hook.getSdk(); else if (md != null) sdk = md.getSdk(); if (Build.VERSION.SDK_INT < sdk) return; // Provide secret hook.setSecret(secret); try { // Create hook method XC_MethodHook methodHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { try { if (Process.myUid() <= 0) return; XParam xparam = XParam.fromXposed(param); hook.before(xparam); if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); param.setObjectExtra("xextra", xparam.getExtras()); } catch (Throwable ex) { Util.bug(null, ex); } } @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { if (!param.hasThrowable()) try { if (Process.myUid() <= 0) return; XParam xparam = XParam.fromXposed(param); xparam.setExtras(param.getObjectExtra("xextra")); hook.after(xparam); if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); } catch (Throwable ex) { Util.bug(null, ex); } } }; // Find class Class<?> hookClass = null; try { // hookClass = Class.forName(hook.getClassName()); hookClass = findClass(hook.getClassName(), classLoader); } catch (Throwable ex) { message = String.format("Class not found for %s", hook); mListHookError.add(message); Util.log(hook, hook.isOptional() ? Log.WARN : Log.ERROR, message); } // Get members List<Member> listMember = new ArrayList<Member>(); Class<?> clazz = hookClass; while (clazz != null) { if (hook.getMethodName() == null) { for (Constructor<?> constructor : clazz.getDeclaredConstructors()) if (Modifier.isPublic(constructor.getModifiers()) ? hook.isVisible() : !hook.isVisible()) listMember.add(constructor); break; } else { for (Method method : clazz.getDeclaredMethods()) if (method.getName().equals(hook.getMethodName()) && (Modifier.isPublic(method.getModifiers()) ? hook.isVisible() : !hook.isVisible())) listMember.add(method); } clazz = clazz.getSuperclass(); } // Hook members for (Member member : listMember) try { XposedBridge.hookMethod(member, methodHook); } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } // Check if members found if (listMember.isEmpty() && !hook.getClassName().startsWith("com.google.android.gms")) { message = String.format("Method not found for %s", hook); mListHookError.add(message); Util.log(hook, hook.isOptional() ? Log.WARN : Log.ERROR, message); } } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } }
diff --git a/WeCharades/src/com/example/wecharades/presenter/SearchPlayerPresenter.java b/WeCharades/src/com/example/wecharades/presenter/SearchPlayerPresenter.java index 066b3c6..f08def0 100644 --- a/WeCharades/src/com/example/wecharades/presenter/SearchPlayerPresenter.java +++ b/WeCharades/src/com/example/wecharades/presenter/SearchPlayerPresenter.java @@ -1,128 +1,129 @@ package com.example.wecharades.presenter; import java.util.ArrayList; import java.util.SortedSet; import java.util.TreeSet; import android.view.KeyEvent; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import com.example.wecharades.R; import com.example.wecharades.model.DatabaseException; import com.example.wecharades.model.Game; import com.example.wecharades.model.Invitation; import com.example.wecharades.views.SearchPlayerActivity; import com.parse.ParseException; import com.parse.ParsePush; /** * * @author Alexander * */ public class SearchPlayerPresenter extends Presenter { private SearchPlayerActivity activity; public SearchPlayerPresenter(SearchPlayerActivity activity) { super(activity); this.activity = (SearchPlayerActivity) activity; } /** * Sets listener on Search box * @param searchBox */ public void setListeners(EditText searchBox) { searchBox.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { activity.onClickSearch(v); return true; } else { return false; } } }); } /** * Update screen * @param s */ public void update(String s){ activity.showProgressBar(); performSearch(s); activity.hideProgressBar(); } /** * Search for a player * @param searchString */ private void performSearch(String searchString) { try { ListView view = (ListView) activity.findViewById(R.id.result_list); TextView text = (TextView) activity.findViewById(R.id.empty_list_item); text.setText("No results found!"); view.setEmptyView(text); SortedSet<String> list = dc.getAllOtherPlayerNames().subSet(searchString, searchString + Character.MAX_VALUE); //Create a list of player who the player cannot send an invitation to: TreeSet<String> alreadySent = new TreeSet<String>(); TreeSet<String> alreadyPlaying = new TreeSet<String>(); for(Invitation inv : dc.getSentInvitations()){ alreadySent.add(inv.getInvitee().getName()); } for(Game g : dc.getGames()){ + if(!g.isFinished()) alreadyPlaying.add(g.getOpponent(dc.getCurrentPlayer()).getName()); } ArrayList<String> resultList = new ArrayList<String>(list); if (!list.isEmpty()) view.setAdapter(new SearchPlayerAdapter(activity, resultList, alreadySent, alreadyPlaying)); } catch (DatabaseException e) { activity.showNegativeDialog("Error", e.prettyPrint(), "OK"); } } /** * Send invitation to player and update database * @param invitee */ public void invite(String invitee) { try { dc.sendInvitation(dc.getPlayer(invitee)); sendNotificationtoOtherPlayer(invitee); } catch (DatabaseException e){ activity.showNegativeDialog("Error", e.prettyPrint(), "OK"); } } /** * Send notification about invitation * @param invitee */ private void sendNotificationtoOtherPlayer(String invitee) { ParsePush push = new ParsePush(); System.out.println(invitee); push.setChannel(invitee); push.setMessage("Charade invitation from: " + dc.getCurrentPlayer().getName()); try { push.send(); } catch (ParseException e) { System.out.println("ParseException"); push.sendInBackground(); } System.out.println("4"); } }
true
true
private void performSearch(String searchString) { try { ListView view = (ListView) activity.findViewById(R.id.result_list); TextView text = (TextView) activity.findViewById(R.id.empty_list_item); text.setText("No results found!"); view.setEmptyView(text); SortedSet<String> list = dc.getAllOtherPlayerNames().subSet(searchString, searchString + Character.MAX_VALUE); //Create a list of player who the player cannot send an invitation to: TreeSet<String> alreadySent = new TreeSet<String>(); TreeSet<String> alreadyPlaying = new TreeSet<String>(); for(Invitation inv : dc.getSentInvitations()){ alreadySent.add(inv.getInvitee().getName()); } for(Game g : dc.getGames()){ alreadyPlaying.add(g.getOpponent(dc.getCurrentPlayer()).getName()); } ArrayList<String> resultList = new ArrayList<String>(list); if (!list.isEmpty()) view.setAdapter(new SearchPlayerAdapter(activity, resultList, alreadySent, alreadyPlaying)); } catch (DatabaseException e) { activity.showNegativeDialog("Error", e.prettyPrint(), "OK"); } }
private void performSearch(String searchString) { try { ListView view = (ListView) activity.findViewById(R.id.result_list); TextView text = (TextView) activity.findViewById(R.id.empty_list_item); text.setText("No results found!"); view.setEmptyView(text); SortedSet<String> list = dc.getAllOtherPlayerNames().subSet(searchString, searchString + Character.MAX_VALUE); //Create a list of player who the player cannot send an invitation to: TreeSet<String> alreadySent = new TreeSet<String>(); TreeSet<String> alreadyPlaying = new TreeSet<String>(); for(Invitation inv : dc.getSentInvitations()){ alreadySent.add(inv.getInvitee().getName()); } for(Game g : dc.getGames()){ if(!g.isFinished()) alreadyPlaying.add(g.getOpponent(dc.getCurrentPlayer()).getName()); } ArrayList<String> resultList = new ArrayList<String>(list); if (!list.isEmpty()) view.setAdapter(new SearchPlayerAdapter(activity, resultList, alreadySent, alreadyPlaying)); } catch (DatabaseException e) { activity.showNegativeDialog("Error", e.prettyPrint(), "OK"); } }
diff --git a/src/test/java/com/springsource/greenhouse/members/MembersControllerTest.java b/src/test/java/com/springsource/greenhouse/members/MembersControllerTest.java index d1c968b9..da9d24b5 100644 --- a/src/test/java/com/springsource/greenhouse/members/MembersControllerTest.java +++ b/src/test/java/com/springsource/greenhouse/members/MembersControllerTest.java @@ -1,56 +1,57 @@ package com.springsource.greenhouse.members; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.ui.ExtendedModelMap; import com.springsource.greenhouse.test.utils.GreenhouseTestDatabaseFactory; public class MembersControllerTest { private EmbeddedDatabase db; private JdbcTemplate jdbcTemplate; private MembersController controller; @Before public void setup() { db = GreenhouseTestDatabaseFactory.createUserDatabase( new FileSystemResource("src/main/webapp/WEB-INF/database/schema-user.sql"), new ClassPathResource("MembersControllerTest.sql", getClass())); jdbcTemplate = new JdbcTemplate(db); - controller = new MembersController(jdbcTemplate); + MembersService membersService = new DefaultMembersService(jdbcTemplate); + controller = new MembersController(membersService); } @After public void destroy() { db.shutdown(); } @Test public void testMemberViewForUsername() { ExtendedModelMap model = new ExtendedModelMap(); controller.memberView("kdonald", model); Member member = (Member) model.get("member"); assertEquals("Keith", member.getFirstName()); assertEquals("Donald", member.getLastName()); } @Test public void testMemberViewForId() { ExtendedModelMap model = new ExtendedModelMap(); controller.memberView("1", model); Member member = (Member) model.get("member"); assertEquals("Keith", member.getFirstName()); assertEquals("Donald", member.getLastName()); } }
true
true
public void setup() { db = GreenhouseTestDatabaseFactory.createUserDatabase( new FileSystemResource("src/main/webapp/WEB-INF/database/schema-user.sql"), new ClassPathResource("MembersControllerTest.sql", getClass())); jdbcTemplate = new JdbcTemplate(db); controller = new MembersController(jdbcTemplate); }
public void setup() { db = GreenhouseTestDatabaseFactory.createUserDatabase( new FileSystemResource("src/main/webapp/WEB-INF/database/schema-user.sql"), new ClassPathResource("MembersControllerTest.sql", getClass())); jdbcTemplate = new JdbcTemplate(db); MembersService membersService = new DefaultMembersService(jdbcTemplate); controller = new MembersController(membersService); }
diff --git a/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/edit/policies/RotatableNonresizableShapeEditPolicy.java b/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/edit/policies/RotatableNonresizableShapeEditPolicy.java index 8f59e0224..8c810a6d3 100644 --- a/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/edit/policies/RotatableNonresizableShapeEditPolicy.java +++ b/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/edit/policies/RotatableNonresizableShapeEditPolicy.java @@ -1,224 +1,227 @@ /* * (c) Fachhochschule Potsdam */ package org.fritzing.fritzing.diagram.edit.policies; import java.io.InputStream; import java.util.HashMap; import java.util.List; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; import org.eclipse.draw2d.Border; import org.eclipse.draw2d.LineBorder; import org.eclipse.draw2d.PositionConstants; import org.eclipse.gef.GraphicalEditPart; import org.eclipse.gef.Handle; import org.eclipse.gef.handles.AbstractHandle; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.RotatableShapeEditPolicy; import org.eclipse.gmf.runtime.diagram.ui.internal.handles.RotateHandle; import org.eclipse.gmf.runtime.diagram.ui.internal.tools.RotateTracker; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.RGB; import org.fritzing.fritzing.diagram.part.FritzingDiagramEditorPlugin; /** * @generated NOT */ public class RotatableNonresizableShapeEditPolicy extends RotatableShapeEditPolicy { public static HashMap<Integer, Cursor> rotateCursors = new HashMap<Integer, Cursor>(); static RGB handleRGB = new RGB(0x51, 0x8a, 0x5b); static Color fillColor = new Color(null, handleRGB); static String cursorImageFileSuffix = ".gif"; /** * @generated NOT */ public void setResizeDirections(int newDirections) { // superclass sets these to all 4 directions in createSelectionHandles // so get rid of them here super.setResizeDirections(0); } /** * @generated NOT */ protected List createSelectionHandles() { List l = super.createSelectionHandles(); for (Object obj : l) { if(obj instanceof AbstractHandle) { AbstractHandle handle = (AbstractHandle) obj; Border border = handle.getBorder(); if(border instanceof LineBorder) { LineBorder lborder = (LineBorder) border; lborder.setWidth(2); lborder.setColor(fillColor); } } } return l; } /** * @generated NOT */ protected Handle createRotationHandle(GraphicalEditPart owner, int direction) { String prefix = ""; int hotX; int hotY; switch (direction) { case PositionConstants.SOUTH_EAST: hotY = 0; hotX = 0; - prefix = "SE"; + prefix = "rotateSE"; break; case PositionConstants.NORTH_EAST: - prefix = "NE"; hotY = 1; hotX = 0; + prefix = "rotateNE"; break; case PositionConstants.SOUTH_WEST: hotY = 0; hotX = 1; - prefix = "SW"; + prefix = "rotateSW"; break; case PositionConstants.NORTH_WEST: hotY = 1; hotX = 1; - prefix = "NW"; + prefix = "rotateNW"; break; default: + direction = PositionConstants.SOUTH_EAST; hotY = 0; hotX = 0; - direction = PositionConstants.SOUTH_EAST; - prefix = "SE"; + prefix = "rotateSE"; } Integer key = new Integer(direction); Cursor rotateCursor = rotateCursors.get(key); if (rotateCursor == null) { try { - InputStream stream = FileLocator.openStream(FritzingDiagramEditorPlugin.getInstance().getBundle(), new Path("icons/cursors/" + prefix + cursorImageFileSuffix), false); + InputStream stream = FileLocator.openStream( + FritzingDiagramEditorPlugin.getInstance().getBundle(), + new Path("icons/cursors/" + prefix + cursorImageFileSuffix), + false); if (stream != null) { ImageData imageData = new ImageData(stream); if (hotY == 1) hotY = imageData.height - 1; if (hotX == 1) hotX = imageData.width - 1; rotateCursor = new Cursor(null, imageData, hotX, hotY); rotateCursors.put(key, rotateCursor); } } catch (Exception ex ) { FritzingDiagramEditorPlugin .getInstance() .logError( "Unable to create cursor: " + ex.getMessage(), ex); } } RotateHandle handle = new RotateHandle(owner, direction) { protected Color getFillColor() { return fillColor; } }; if (rotateCursor != null) { handle.setCursor(rotateCursor); } handle.setDragTracker(new CustomCursorRotateTracker(owner, direction, rotateCursor)); return handle; } /* private boolean isRotationRequired(ChangeBoundsRequest request) { return request instanceof RotateShapeRequest ? ((RotateShapeRequest) request).shouldRotate() : false; } protected void showChangeBoundsFeedback(ChangeBoundsRequest request) { super.showChangeBoundsFeedback(request); System.out.println("show change " + request.getClass().getName()); } protected Rectangle getInitialFeedbackBounds() { System.out.println("get initial bounds "); return super.getInitialFeedbackBounds(); } protected void showChangeBoundsFeedback(ChangeBoundsRequest request) { ChangeBoundsRequest cbr = (ChangeBoundsRequest) request; if (isRotationRequired(cbr)) { Control control = Display.getCurrent().getCursorControl(); savedCursor = control.getCursor(); control.setCursor(new Cursor(Display.getCurrent(), SWT.CURSOR_WAIT)); System.out.println("setting cursor? " + control.getToolTipText() + " " + request.getClass().getName()); } } public void eraseTargetFeedback(Request request) { if (request instanceof ChangeBoundsRequest) { ChangeBoundsRequest cbr = (ChangeBoundsRequest) request; if (isRotationRequired(cbr)) { Control control = Display.getCurrent().getCursorControl(); control.setCursor(savedCursor); } } } */ } /** * @generated NOT */ class CustomCursorRotateTracker extends RotateTracker { int direction; Cursor cursor; /** * @generated NOT */ public CustomCursorRotateTracker(GraphicalEditPart owner, int direction, Cursor cursor) { super(owner, direction); this.direction = direction; this.cursor = cursor; } /** * @generated NOT */ protected Cursor getDefaultCursor() { return cursor; } protected boolean handleButtonDown(int button) { // boolean result = super.handleButtonDown(button); if (button == 1) { // tell it we're already dragging // setFlag makes movedPastThreshold return true //setFlag(FLAG_PAST_THRESHOLD, true); setFlag(1, true); handleDrag(); handleDragStarted(); handleDragInProgress(); } return result; } }
false
true
protected Handle createRotationHandle(GraphicalEditPart owner, int direction) { String prefix = ""; int hotX; int hotY; switch (direction) { case PositionConstants.SOUTH_EAST: hotY = 0; hotX = 0; prefix = "SE"; break; case PositionConstants.NORTH_EAST: prefix = "NE"; hotY = 1; hotX = 0; break; case PositionConstants.SOUTH_WEST: hotY = 0; hotX = 1; prefix = "SW"; break; case PositionConstants.NORTH_WEST: hotY = 1; hotX = 1; prefix = "NW"; break; default: hotY = 0; hotX = 0; direction = PositionConstants.SOUTH_EAST; prefix = "SE"; } Integer key = new Integer(direction); Cursor rotateCursor = rotateCursors.get(key); if (rotateCursor == null) { try { InputStream stream = FileLocator.openStream(FritzingDiagramEditorPlugin.getInstance().getBundle(), new Path("icons/cursors/" + prefix + cursorImageFileSuffix), false); if (stream != null) { ImageData imageData = new ImageData(stream); if (hotY == 1) hotY = imageData.height - 1; if (hotX == 1) hotX = imageData.width - 1; rotateCursor = new Cursor(null, imageData, hotX, hotY); rotateCursors.put(key, rotateCursor); } } catch (Exception ex ) { FritzingDiagramEditorPlugin .getInstance() .logError( "Unable to create cursor: " + ex.getMessage(), ex); } } RotateHandle handle = new RotateHandle(owner, direction) { protected Color getFillColor() { return fillColor; } }; if (rotateCursor != null) { handle.setCursor(rotateCursor); } handle.setDragTracker(new CustomCursorRotateTracker(owner, direction, rotateCursor)); return handle; }
protected Handle createRotationHandle(GraphicalEditPart owner, int direction) { String prefix = ""; int hotX; int hotY; switch (direction) { case PositionConstants.SOUTH_EAST: hotY = 0; hotX = 0; prefix = "rotateSE"; break; case PositionConstants.NORTH_EAST: hotY = 1; hotX = 0; prefix = "rotateNE"; break; case PositionConstants.SOUTH_WEST: hotY = 0; hotX = 1; prefix = "rotateSW"; break; case PositionConstants.NORTH_WEST: hotY = 1; hotX = 1; prefix = "rotateNW"; break; default: direction = PositionConstants.SOUTH_EAST; hotY = 0; hotX = 0; prefix = "rotateSE"; } Integer key = new Integer(direction); Cursor rotateCursor = rotateCursors.get(key); if (rotateCursor == null) { try { InputStream stream = FileLocator.openStream( FritzingDiagramEditorPlugin.getInstance().getBundle(), new Path("icons/cursors/" + prefix + cursorImageFileSuffix), false); if (stream != null) { ImageData imageData = new ImageData(stream); if (hotY == 1) hotY = imageData.height - 1; if (hotX == 1) hotX = imageData.width - 1; rotateCursor = new Cursor(null, imageData, hotX, hotY); rotateCursors.put(key, rotateCursor); } } catch (Exception ex ) { FritzingDiagramEditorPlugin .getInstance() .logError( "Unable to create cursor: " + ex.getMessage(), ex); } } RotateHandle handle = new RotateHandle(owner, direction) { protected Color getFillColor() { return fillColor; } }; if (rotateCursor != null) { handle.setCursor(rotateCursor); } handle.setDragTracker(new CustomCursorRotateTracker(owner, direction, rotateCursor)); return handle; }
diff --git a/core/src/main/java/org/apache/abdera/util/AbstractXPath.java b/core/src/main/java/org/apache/abdera/util/AbstractXPath.java index 453ac15a..1769a39d 100644 --- a/core/src/main/java/org/apache/abdera/util/AbstractXPath.java +++ b/core/src/main/java/org/apache/abdera/util/AbstractXPath.java @@ -1,70 +1,70 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.util; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.abdera.model.Base; import org.apache.abdera.xpath.XPath; import org.apache.abdera.xpath.XPathException; public abstract class AbstractXPath implements XPath { private Map<String,String> namespaces = null; public Map<String, String> getDefaultNamespaces() { if (namespaces == null) namespaces = new HashMap<String,String>(); - namespaces.put(Constants.PREFIX, Constants.ATOM_NS); - namespaces.put(Constants.APP_PREFIX, Constants.APP_NS); - namespaces.put(Constants.CONTROL_PREFIX, Constants.CONTROL_NS); + namespaces.put("a", Constants.ATOM_NS); + namespaces.put("app", Constants.APP_NS); + namespaces.put("pub", Constants.CONTROL_NS); return namespaces; } public void setDefaultNamespaces(Map<String, String> namespaces) { this.namespaces = namespaces; } public List selectNodes(String path, Base base) throws XPathException { return selectNodes(path, base, getDefaultNamespaces()); } public Object selectSingleNode(String path, Base base) throws XPathException { return selectSingleNode(path, base, getDefaultNamespaces()); } public Object evaluate(String path, Base base) throws XPathException { return evaluate(path, base, getDefaultNamespaces()); } public String valueOf(String path, Base base) throws XPathException { return valueOf(path, base, getDefaultNamespaces()); } public boolean isTrue(String path, Base base) throws XPathException { return isTrue(path, base, getDefaultNamespaces()); } public Number numericValueOf(String path, Base base) throws XPathException { return numericValueOf(path, base, getDefaultNamespaces()); } }
true
true
public Map<String, String> getDefaultNamespaces() { if (namespaces == null) namespaces = new HashMap<String,String>(); namespaces.put(Constants.PREFIX, Constants.ATOM_NS); namespaces.put(Constants.APP_PREFIX, Constants.APP_NS); namespaces.put(Constants.CONTROL_PREFIX, Constants.CONTROL_NS); return namespaces; }
public Map<String, String> getDefaultNamespaces() { if (namespaces == null) namespaces = new HashMap<String,String>(); namespaces.put("a", Constants.ATOM_NS); namespaces.put("app", Constants.APP_NS); namespaces.put("pub", Constants.CONTROL_NS); return namespaces; }
diff --git a/src/main/java/org/abstractj/crypto/Util.java b/src/main/java/org/abstractj/crypto/Util.java index 69a0a3b..88ce44d 100644 --- a/src/main/java/org/abstractj/crypto/Util.java +++ b/src/main/java/org/abstractj/crypto/Util.java @@ -1,16 +1,16 @@ package org.abstractj.crypto; public class Util { public static byte[] checkLength(byte[] data, int size) { - if (data == null || data.length != size) - throw new RuntimeException("Invalid size: " + data.length); + if (data == null || data.length < size) + throw new RuntimeException("Invalid length: " + data.length); return data; } public static int checkSize(int size, int minimumSize) { if (size < minimumSize) throw new RuntimeException("Invalid size: " + size); return size; } }
true
true
public static byte[] checkLength(byte[] data, int size) { if (data == null || data.length != size) throw new RuntimeException("Invalid size: " + data.length); return data; }
public static byte[] checkLength(byte[] data, int size) { if (data == null || data.length < size) throw new RuntimeException("Invalid length: " + data.length); return data; }
diff --git a/org.eclipse.mylyn.trac.tests/src/org/eclipse/mylyn/trac/tests/core/TracTaskDataHandlerXmlRpcTest.java b/org.eclipse.mylyn.trac.tests/src/org/eclipse/mylyn/trac/tests/core/TracTaskDataHandlerXmlRpcTest.java index cc269f5c6..166297740 100644 --- a/org.eclipse.mylyn.trac.tests/src/org/eclipse/mylyn/trac/tests/core/TracTaskDataHandlerXmlRpcTest.java +++ b/org.eclipse.mylyn.trac.tests/src/org/eclipse/mylyn/trac/tests/core/TracTaskDataHandlerXmlRpcTest.java @@ -1,399 +1,399 @@ /******************************************************************************* * Copyright (c) 2006, 2009 Steffen Pingel 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: * Steffen Pingel - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.trac.tests.core; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import junit.framework.TestCase; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.mylyn.commons.net.AuthenticationCredentials; import org.eclipse.mylyn.commons.net.AuthenticationType; import org.eclipse.mylyn.internal.tasks.core.TaskTask; import org.eclipse.mylyn.internal.tasks.core.data.TextTaskAttachmentSource; import org.eclipse.mylyn.internal.tasks.core.sync.SynchronizationSession; import org.eclipse.mylyn.internal.trac.core.TracAttribute; import org.eclipse.mylyn.internal.trac.core.TracAttributeMapper; import org.eclipse.mylyn.internal.trac.core.TracCorePlugin; import org.eclipse.mylyn.internal.trac.core.TracRepositoryConnector; import org.eclipse.mylyn.internal.trac.core.TracTaskDataHandler; import org.eclipse.mylyn.internal.trac.core.TracTaskMapper; import org.eclipse.mylyn.internal.trac.core.client.ITracClient; import org.eclipse.mylyn.internal.trac.core.model.TracTicket; import org.eclipse.mylyn.internal.trac.core.model.TracTicket.Key; import org.eclipse.mylyn.internal.trac.core.util.TracUtil; import org.eclipse.mylyn.tasks.core.ITask; import org.eclipse.mylyn.tasks.core.ITaskAttachment; import org.eclipse.mylyn.tasks.core.RepositoryStatus; import org.eclipse.mylyn.tasks.core.TaskMapping; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.data.AbstractTaskAttachmentHandler; import org.eclipse.mylyn.tasks.core.data.TaskAttribute; import org.eclipse.mylyn.tasks.core.data.TaskData; import org.eclipse.mylyn.tasks.core.data.TaskMapper; import org.eclipse.mylyn.tasks.core.data.TaskOperation; import org.eclipse.mylyn.tasks.core.data.TaskRelation; import org.eclipse.mylyn.tasks.ui.TasksUi; import org.eclipse.mylyn.trac.tests.support.TracFixture; import org.eclipse.mylyn.trac.tests.support.TracTestConstants; import org.eclipse.mylyn.trac.tests.support.TracTestUtil; import org.eclipse.mylyn.trac.tests.support.XmlRpcServer.TestData; /** * @author Steffen Pingel */ public class TracTaskDataHandlerXmlRpcTest extends TestCase { private TracRepositoryConnector connector; private TaskRepository repository; private TestData data; private TracTaskDataHandler taskDataHandler; private ITracClient client; public TracTaskDataHandlerXmlRpcTest() { } @Override protected void setUp() throws Exception { super.setUp(); data = TracFixture.init010(); connector = (TracRepositoryConnector) TasksUi.getRepositoryConnector(TracCorePlugin.CONNECTOR_KIND); taskDataHandler = connector.getTaskDataHandler(); repository = TracFixture.current().singleRepository(); client = connector.getClientManager().getTracClient(repository); } private SynchronizationSession createSession(ITask... tasks) { SynchronizationSession session = new SynchronizationSession(); session.setNeedsPerformQueries(true); session.setTaskRepository(repository); session.setFullSynchronization(true); session.setTasks(new HashSet<ITask>(Arrays.asList(tasks))); return session; } public void testMarkStaleTasks() throws Exception { SynchronizationSession session; TracTicket ticket = TracTestUtil.createTicket(client, "markStaleTasks"); ITask task = TracTestUtil.createTask(repository, ticket.getId() + ""); long lastModified = TracUtil.toTracTime(task.getModificationDate()); // an empty set should not cause contact to the repository repository.setSynchronizationTimeStamp(null); session = createSession(task); connector.preSynchronization(session, null); assertTrue(session.needsPerformQueries()); assertNull(repository.getSynchronizationTimeStamp()); repository.setSynchronizationTimeStamp(null); session = createSession(task); connector.preSynchronization(session, null); assertTrue(session.needsPerformQueries()); assertEquals(Collections.singleton(task), session.getStaleTasks()); // always returns the ticket because time comparison mode is >= repository.setSynchronizationTimeStamp(lastModified + ""); session = createSession(task); connector.preSynchronization(session, null); // TODO this was fixed so it returns false now but only if the // query returns a single task assertFalse(session.needsPerformQueries()); assertEquals(Collections.emptySet(), session.getStaleTasks()); repository.setSynchronizationTimeStamp((lastModified + 1) + ""); session = createSession(task); connector.preSynchronization(session, null); assertFalse(session.needsPerformQueries()); assertEquals(Collections.emptySet(), session.getStaleTasks()); // change ticket making sure it gets a new change time - Thread.sleep(1000); + Thread.sleep(1500); ticket.putBuiltinValue(Key.DESCRIPTION, lastModified + ""); client.updateTicket(ticket, "comment", null); repository.setSynchronizationTimeStamp((lastModified + 1) + ""); session = createSession(task); connector.preSynchronization(session, null); assertTrue(session.needsPerformQueries()); assertEquals(Collections.singleton(task), session.getStaleTasks()); } public void testMarkStaleTasksNoTimeStamp() throws Exception { SynchronizationSession session; ITask task = TracTestUtil.createTask(repository, data.offlineHandlerTicketId + ""); session = createSession(task); repository.setSynchronizationTimeStamp(null); connector.preSynchronization(session, null); assertTrue(session.needsPerformQueries()); assertEquals(Collections.singleton(task), session.getStaleTasks()); session = createSession(task); repository.setSynchronizationTimeStamp(""); connector.preSynchronization(session, null); assertTrue(session.needsPerformQueries()); assertEquals(Collections.singleton(task), session.getStaleTasks()); session = createSession(task); repository.setSynchronizationTimeStamp("0"); connector.preSynchronization(session, null); assertTrue(session.needsPerformQueries()); assertEquals(Collections.singleton(task), session.getStaleTasks()); session = createSession(task); repository.setSynchronizationTimeStamp("abc"); connector.preSynchronization(session, null); assertTrue(session.needsPerformQueries()); assertEquals(Collections.singleton(task), session.getStaleTasks()); } public void testNonNumericTaskId() { try { connector.getTaskData(repository, "abc", null); fail("Expected CoreException"); } catch (CoreException e) { } } public void testAttachmentChangesLastModifiedDate() throws Exception { AbstractTaskAttachmentHandler attachmentHandler = connector.getTaskAttachmentHandler(); ITask task = TracTestUtil.createTask(repository, data.attachmentTicketId + ""); Date lastModified = task.getModificationDate(); // XXX the test case fails when comment == null attachmentHandler.postContent(repository, task, new TextTaskAttachmentSource("abc"), "comment", null, null); task = TracTestUtil.createTask(repository, data.attachmentTicketId + ""); Date newLastModified = task.getModificationDate(); assertTrue("Expected " + newLastModified + " to be more recent than " + lastModified, newLastModified.after(lastModified)); } public void testAttachmentUrlEncoding() throws Exception { AbstractTaskAttachmentHandler attachmentHandler = connector.getTaskAttachmentHandler(); TracTicket ticket = TracTestUtil.createTicket(client, "attachment url test"); ITask task = TracTestUtil.createTask(repository, ticket.getId() + ""); attachmentHandler.postContent(repository, task, new TextTaskAttachmentSource("abc") { @Override public String getName() { return "https%3A%2F%2Fbugs.eclipse.org%2Fbugs.xml.zip"; } }, "comment", null, null); task = TracTestUtil.createTask(repository, ticket.getId() + ""); List<ITaskAttachment> attachments = TracTestUtil.getTaskAttachments(task); assertEquals(1, attachments.size()); assertEquals(repository.getUrl() + "/attachment/ticket/" + ticket.getId() + "/https%253A%252F%252Fbugs.eclipse.org%252Fbugs.xml.zip", attachments.get(0).getUrl()); } public void testPostTaskDataInvalidCredentials() throws Exception { ITask task = TracTestUtil.createTask(repository, data.offlineHandlerTicketId + ""); TaskData taskData = TasksUi.getTaskDataManager().getTaskData(task); taskData.getRoot().getMappedAttribute(TaskAttribute.COMMENT_NEW).setValue("new comment"); repository.setCredentials(AuthenticationType.REPOSITORY, new AuthenticationCredentials("foo", "bar"), false); try { taskDataHandler.postTaskData(repository, taskData, null, null); } catch (CoreException expected) { assertEquals(RepositoryStatus.ERROR_REPOSITORY_LOGIN, expected.getStatus().getCode()); } assertEquals("new comment", taskData.getRoot().getMappedAttribute(TaskAttribute.COMMENT_NEW).getValue()); } public void testCanInitializeTaskData() throws Exception { ITask task = new TaskTask(TracCorePlugin.CONNECTOR_KIND, "", ""); assertFalse(taskDataHandler.canInitializeSubTaskData(repository, task)); task.setAttribute(TracRepositoryConnector.TASK_KEY_SUPPORTS_SUBTASKS, Boolean.TRUE.toString()); assertTrue(taskDataHandler.canInitializeSubTaskData(repository, task)); task = TracTestUtil.createTask(repository, data.offlineHandlerTicketId + ""); TaskData taskData = taskDataHandler.getTaskData(repository, data.offlineHandlerTicketId + "", null); assertFalse(taskDataHandler.canInitializeSubTaskData(repository, task)); taskData.getRoot().createAttribute(TracTaskDataHandler.ATTRIBUTE_BLOCKED_BY); connector.updateTaskFromTaskData(repository, task, taskData); assertTrue(taskDataHandler.canInitializeSubTaskData(repository, task)); task.setAttribute(TracRepositoryConnector.TASK_KEY_SUPPORTS_SUBTASKS, Boolean.FALSE.toString()); connector.updateTaskFromTaskData(repository, task, taskData); assertTrue(taskDataHandler.canInitializeSubTaskData(repository, task)); } public void testInitializeSubTaskDataInvalidParent() throws Exception { TaskData parentTaskData = taskDataHandler.getTaskData(repository, data.offlineHandlerTicketId + "", new NullProgressMonitor()); try { taskDataHandler.initializeSubTaskData(repository, parentTaskData, parentTaskData, null); fail("expected CoreException"); } catch (CoreException expected) { } } public void testInitializeSubTaskData() throws Exception { TaskData parentTaskData = taskDataHandler.getTaskData(repository, data.offlineHandlerTicketId + "", null); TaskMapper parentTaskMapper = new TracTaskMapper(parentTaskData, null); parentTaskMapper.setSummary("abc"); parentTaskMapper.setDescription("def"); String component = parentTaskData.getRoot() .getMappedAttribute(TracAttribute.COMPONENT.getTracKey()) .getOptions() .get(0); parentTaskMapper.setComponent(component); parentTaskData.getRoot().createAttribute(TracTaskDataHandler.ATTRIBUTE_BLOCKED_BY); TaskData subTaskData = new TaskData(parentTaskData.getAttributeMapper(), TracCorePlugin.CONNECTOR_KIND, "", ""); subTaskData.getRoot().createAttribute(TracTaskDataHandler.ATTRIBUTE_BLOCKING); taskDataHandler.initializeSubTaskData(repository, subTaskData, parentTaskData, new NullProgressMonitor()); TaskMapper subTaskMapper = new TracTaskMapper(subTaskData, null); assertEquals("", subTaskMapper.getSummary()); assertEquals("", subTaskMapper.getDescription()); assertEquals(component, subTaskMapper.getComponent()); TaskAttribute attribute = subTaskData.getRoot().getMappedAttribute(TracTaskDataHandler.ATTRIBUTE_BLOCKING); assertEquals(parentTaskData.getTaskId(), attribute.getValue()); attribute = parentTaskData.getRoot().getMappedAttribute(TracTaskDataHandler.ATTRIBUTE_BLOCKED_BY); assertEquals("", attribute.getValue()); } public void testGetSubTaskIds() throws Exception { TaskData taskData = new TaskData(new TracAttributeMapper(new TaskRepository("", ""), client), TracCorePlugin.CONNECTOR_KIND, "", ""); TaskAttribute blockedBy = taskData.getRoot().createAttribute(TracTaskDataHandler.ATTRIBUTE_BLOCKED_BY); Collection<String> subTaskIds; blockedBy.setValue("123 456"); subTaskIds = getSubTaskIds(taskData); assertEquals(2, subTaskIds.size()); assertTrue(subTaskIds.contains("123")); assertTrue(subTaskIds.contains("456")); blockedBy.setValue("7,8"); subTaskIds = getSubTaskIds(taskData); assertEquals(2, subTaskIds.size()); assertTrue(subTaskIds.contains("7")); assertTrue(subTaskIds.contains("8")); blockedBy.setValue(" 7 , 8, "); subTaskIds = getSubTaskIds(taskData); assertEquals(2, subTaskIds.size()); assertTrue(subTaskIds.contains("7")); assertTrue(subTaskIds.contains("8")); blockedBy.setValue("7"); subTaskIds = getSubTaskIds(taskData); assertEquals(1, subTaskIds.size()); assertTrue(subTaskIds.contains("7")); blockedBy.setValue(""); subTaskIds = getSubTaskIds(taskData); assertEquals(0, subTaskIds.size()); blockedBy.setValue(" "); subTaskIds = getSubTaskIds(taskData); assertEquals(0, subTaskIds.size()); } private Collection<String> getSubTaskIds(TaskData taskData) { List<String> subTaskIds = new ArrayList<String>(); Collection<TaskRelation> relations = connector.getTaskRelations(taskData); for (TaskRelation taskRelation : relations) { subTaskIds.add(taskRelation.getTaskId()); } return subTaskIds; } public void testInitializeTaskData() throws Exception { TaskData taskData = new TaskData(taskDataHandler.getAttributeMapper(repository), TracCorePlugin.CONNECTOR_KIND, "", ""); TaskMapping mapping = new TaskMapping() { @Override public String getDescription() { return "description"; } @Override public String getSummary() { return "summary"; } }; taskDataHandler.initializeTaskData(repository, taskData, mapping, new NullProgressMonitor()); // initializeTaskData() should ignore the initialization data TaskMapper mapper = new TracTaskMapper(taskData, null); assertEquals(null, mapper.getResolution()); assertEquals("", mapper.getSummary()); assertEquals("", mapper.getDescription()); // check for default values assertEquals("Defect", mapper.getTaskKind()); assertEquals("major", mapper.getPriority()); // empty attributes should not exist assertNull(taskData.getRoot().getAttribute(TracAttribute.SEVERITY.getTracKey())); } public void testOperations() throws Exception { boolean hasReassign = TracTestConstants.TEST_TRAC_011_URL.equals(repository.getRepositoryUrl()); TaskData taskData = taskDataHandler.getTaskData(repository, "1", new NullProgressMonitor()); List<TaskAttribute> operations = taskData.getAttributeMapper().getAttributesByType(taskData, TaskAttribute.TYPE_OPERATION); assertEquals((hasReassign ? 5 : 4), operations.size()); TaskOperation operation = taskData.getAttributeMapper().getTaskOperation(operations.get(0)); assertEquals(TaskAttribute.OPERATION, operation.getTaskAttribute().getId()); operation = taskData.getAttributeMapper().getTaskOperation(operations.get(1)); assertEquals("leave", operation.getOperationId()); assertNotNull(operation.getLabel()); operation = taskData.getAttributeMapper().getTaskOperation(operations.get(2)); assertEquals("resolve", operation.getOperationId()); assertNotNull(operation.getLabel()); String associatedId = operation.getTaskAttribute().getMetaData().getValue( TaskAttribute.META_ASSOCIATED_ATTRIBUTE_ID); assertNotNull(associatedId); if (hasReassign) { operation = taskData.getAttributeMapper().getTaskOperation(operations.get(3)); assertEquals("reassign", operation.getOperationId()); assertNotNull(operation.getLabel()); operation = taskData.getAttributeMapper().getTaskOperation(operations.get(4)); assertEquals("accept", operation.getOperationId()); assertNotNull(operation.getLabel()); } else { operation = taskData.getAttributeMapper().getTaskOperation(operations.get(3)); assertEquals("accept", operation.getOperationId()); assertNotNull(operation.getLabel()); } } public void testPostTaskDataUnsetResolution() throws Exception { TracTicket ticket = TracTestUtil.createTicket(client, "postTaskDataUnsetResolution"); TaskData taskData = taskDataHandler.getTaskData(repository, ticket.getId() + "", new NullProgressMonitor()); TaskAttribute attribute = taskData.getRoot().getMappedAttribute(TaskAttribute.RESOLUTION); attribute.setValue("fixed"); taskDataHandler.postTaskData(repository, taskData, null, new NullProgressMonitor()); // should not set resolution unless resolve operation is selected taskData = taskDataHandler.getTaskData(repository, ticket.getId() + "", new NullProgressMonitor()); attribute = taskData.getRoot().getMappedAttribute(TaskAttribute.RESOLUTION); assertEquals("", attribute.getValue()); } }
true
true
public void testMarkStaleTasks() throws Exception { SynchronizationSession session; TracTicket ticket = TracTestUtil.createTicket(client, "markStaleTasks"); ITask task = TracTestUtil.createTask(repository, ticket.getId() + ""); long lastModified = TracUtil.toTracTime(task.getModificationDate()); // an empty set should not cause contact to the repository repository.setSynchronizationTimeStamp(null); session = createSession(task); connector.preSynchronization(session, null); assertTrue(session.needsPerformQueries()); assertNull(repository.getSynchronizationTimeStamp()); repository.setSynchronizationTimeStamp(null); session = createSession(task); connector.preSynchronization(session, null); assertTrue(session.needsPerformQueries()); assertEquals(Collections.singleton(task), session.getStaleTasks()); // always returns the ticket because time comparison mode is >= repository.setSynchronizationTimeStamp(lastModified + ""); session = createSession(task); connector.preSynchronization(session, null); // TODO this was fixed so it returns false now but only if the // query returns a single task assertFalse(session.needsPerformQueries()); assertEquals(Collections.emptySet(), session.getStaleTasks()); repository.setSynchronizationTimeStamp((lastModified + 1) + ""); session = createSession(task); connector.preSynchronization(session, null); assertFalse(session.needsPerformQueries()); assertEquals(Collections.emptySet(), session.getStaleTasks()); // change ticket making sure it gets a new change time Thread.sleep(1000); ticket.putBuiltinValue(Key.DESCRIPTION, lastModified + ""); client.updateTicket(ticket, "comment", null); repository.setSynchronizationTimeStamp((lastModified + 1) + ""); session = createSession(task); connector.preSynchronization(session, null); assertTrue(session.needsPerformQueries()); assertEquals(Collections.singleton(task), session.getStaleTasks()); }
public void testMarkStaleTasks() throws Exception { SynchronizationSession session; TracTicket ticket = TracTestUtil.createTicket(client, "markStaleTasks"); ITask task = TracTestUtil.createTask(repository, ticket.getId() + ""); long lastModified = TracUtil.toTracTime(task.getModificationDate()); // an empty set should not cause contact to the repository repository.setSynchronizationTimeStamp(null); session = createSession(task); connector.preSynchronization(session, null); assertTrue(session.needsPerformQueries()); assertNull(repository.getSynchronizationTimeStamp()); repository.setSynchronizationTimeStamp(null); session = createSession(task); connector.preSynchronization(session, null); assertTrue(session.needsPerformQueries()); assertEquals(Collections.singleton(task), session.getStaleTasks()); // always returns the ticket because time comparison mode is >= repository.setSynchronizationTimeStamp(lastModified + ""); session = createSession(task); connector.preSynchronization(session, null); // TODO this was fixed so it returns false now but only if the // query returns a single task assertFalse(session.needsPerformQueries()); assertEquals(Collections.emptySet(), session.getStaleTasks()); repository.setSynchronizationTimeStamp((lastModified + 1) + ""); session = createSession(task); connector.preSynchronization(session, null); assertFalse(session.needsPerformQueries()); assertEquals(Collections.emptySet(), session.getStaleTasks()); // change ticket making sure it gets a new change time Thread.sleep(1500); ticket.putBuiltinValue(Key.DESCRIPTION, lastModified + ""); client.updateTicket(ticket, "comment", null); repository.setSynchronizationTimeStamp((lastModified + 1) + ""); session = createSession(task); connector.preSynchronization(session, null); assertTrue(session.needsPerformQueries()); assertEquals(Collections.singleton(task), session.getStaleTasks()); }
diff --git a/src/prop/hex/gestors/PartidaHexGstr.java b/src/prop/hex/gestors/PartidaHexGstr.java index 3d5cc76..9d063c6 100644 --- a/src/prop/hex/gestors/PartidaHexGstr.java +++ b/src/prop/hex/gestors/PartidaHexGstr.java @@ -1,55 +1,55 @@ package prop.hex.gestors; import prop.hex.domini.models.PartidaHex; import java.io.File; import java.util.HashSet; import java.util.Set; /** * Classe per la gestió de la persistència de PartidaHex en disc, com s'estén de BaseGstr, * únicament fa falta especificar la subcarpeta on guardar les dades de les partides. */ public class PartidaHexGstr extends BaseGstr<PartidaHex> { /** * Constructora, simplement especifica la subcarpeta a on guardar els elements de tipus PartidaHex. */ public PartidaHexGstr() { subcarpeta_dades = "partides"; } /** * Llista els identificadors de les partides jugades per l'usuari amb identificador únic id_usuari. * * @return El conjunt d'identificadors de partides jugades per l'usuari amb identificador únic id_usuari. */ public Set<String> llistaPartidesUsuari( String id_usuari ) { File carpeta = new File( carpeta_dades + '/' + subcarpeta_dades + '/' ); File[] llista_arxius = carpeta.listFiles(); Set<String> noms_elements = new HashSet<String>(); for ( File arxiu : llista_arxius ) { String nom = arxiu.getName(); if ( nom.endsWith( '.' + extensio_fitxers ) ) { String id_partida = nom.substring( 0, nom.length() - ( 1 + extensio_fitxers.length() ) ); String[] identificadors = id_partida.split( "@" ); // Comprovem si l'usuari juga a la partida - if ( identificadors[identificadors.length - 1] == id_usuari || - identificadors[identificadors.length - 2] == id_usuari ) + if ( identificadors[identificadors.length - 1].equals( id_usuari ) || + identificadors[identificadors.length - 2].equals( id_usuari ) ) { // Afegim el nom de l'element sense l'extensió al conjunt d'identificadors noms_elements.add( id_partida ); } } } return noms_elements; } }
true
true
public Set<String> llistaPartidesUsuari( String id_usuari ) { File carpeta = new File( carpeta_dades + '/' + subcarpeta_dades + '/' ); File[] llista_arxius = carpeta.listFiles(); Set<String> noms_elements = new HashSet<String>(); for ( File arxiu : llista_arxius ) { String nom = arxiu.getName(); if ( nom.endsWith( '.' + extensio_fitxers ) ) { String id_partida = nom.substring( 0, nom.length() - ( 1 + extensio_fitxers.length() ) ); String[] identificadors = id_partida.split( "@" ); // Comprovem si l'usuari juga a la partida if ( identificadors[identificadors.length - 1] == id_usuari || identificadors[identificadors.length - 2] == id_usuari ) { // Afegim el nom de l'element sense l'extensió al conjunt d'identificadors noms_elements.add( id_partida ); } } } return noms_elements; }
public Set<String> llistaPartidesUsuari( String id_usuari ) { File carpeta = new File( carpeta_dades + '/' + subcarpeta_dades + '/' ); File[] llista_arxius = carpeta.listFiles(); Set<String> noms_elements = new HashSet<String>(); for ( File arxiu : llista_arxius ) { String nom = arxiu.getName(); if ( nom.endsWith( '.' + extensio_fitxers ) ) { String id_partida = nom.substring( 0, nom.length() - ( 1 + extensio_fitxers.length() ) ); String[] identificadors = id_partida.split( "@" ); // Comprovem si l'usuari juga a la partida if ( identificadors[identificadors.length - 1].equals( id_usuari ) || identificadors[identificadors.length - 2].equals( id_usuari ) ) { // Afegim el nom de l'element sense l'extensió al conjunt d'identificadors noms_elements.add( id_partida ); } } } return noms_elements; }
diff --git a/src/share/classes/com/sun/tools/javafx/antlr/StringLiteralProcessor.java b/src/share/classes/com/sun/tools/javafx/antlr/StringLiteralProcessor.java index ad739915a..0d5d390e5 100644 --- a/src/share/classes/com/sun/tools/javafx/antlr/StringLiteralProcessor.java +++ b/src/share/classes/com/sun/tools/javafx/antlr/StringLiteralProcessor.java @@ -1,212 +1,214 @@ /* * Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.javafx.antlr; import com.sun.tools.javac.util.Log; /** * Convert escapes in string literals * * @author Robert Field * * Stolen liberally from the javac Scanner */ public class StringLiteralProcessor { private final int basepos; /** A character buffer for literals. */ private char[] sbuf; private int sp; /** The input buffer, index of next chacter to be read, * index of one past last character in buffer. */ private final char[] buf; private int bp; private final int buflen; /** The current character. */ private char ch; /** The buffer index of the last converted unicode character */ private int unicodeConversionBp = -1; /** The log to be used for error reporting. */ private final Log log; public static String convert(Log log, int pos, String str) { StringLiteralProcessor slp = new StringLiteralProcessor(log, pos, str); return slp.convert(); } private StringLiteralProcessor(Log log, int pos, String str) { this.log = log; this.basepos = pos; this.buf = str.toCharArray(); this.buflen = buf.length - 1; // skip trailing quote this.bp = 0; // scanChar pre-increments so we skip the leading quote this.sbuf = new char[buflen]; this.sp = 0; } private String convert() { scanChar(); while (bp < buflen) { scanLitChar(); } return new String(sbuf, 0, sp); } /** Report an error at the given position using the provided arguments. */ private void lexError(String key, Object... args) { log.error(basepos+bp+1, key, args); } /** Convert an ASCII digit from its base (8, 10, or 16) * to its value. */ private int digit(int base) { char c = ch; int result = Character.digit(c, base); if (result >= 0 && c > 0x7f) { lexError("illegal.nonascii.digit"); ch = "0123456789abcdef".charAt(result); } return result; } /** Append a character to sbuf. */ private void putChar(char ch) { if (sp == sbuf.length) { char[] newsbuf = new char[sbuf.length * 2]; System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length); sbuf = newsbuf; } sbuf[sp++] = ch; } /** Convert unicode escape; bp points to initial '\' character * (Spec 3.3). */ private void convertUnicode() { if (ch == '\\' && unicodeConversionBp != bp) { bp++; ch = buf[bp]; if (ch == 'u') { do { bp++; ch = buf[bp]; } while (ch == 'u'); int limit = bp + 3; if (limit < buflen) { int d = digit(16); int code = d; while (bp < limit && d >= 0) { bp++; ch = buf[bp]; d = digit(16); code = (code << 4) + d; } if (d >= 0) { ch = (char)code; unicodeConversionBp = bp; return; } } lexError("illegal.unicode.esc"); } else { bp--; ch = '\\'; } } } /** Read next character. */ private void scanChar() { ch = buf[++bp]; if (ch == '\\') { convertUnicode(); } } /** Read next character in character or string literal and copy into sbuf. */ private void scanLitChar() { if (ch == '\\') { if (buf[bp+1] == '\\' && unicodeConversionBp != bp) { bp++; putChar('\\'); scanChar(); } else { scanChar(); switch (ch) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': char leadch = ch; int oct = digit(8); scanChar(); if ('0' <= ch && ch <= '7') { oct = oct * 8 + digit(8); scanChar(); if (leadch <= '3' && '0' <= ch && ch <= '7') { oct = oct * 8 + digit(8); scanChar(); } } putChar((char)oct); break; case 'b': putChar('\b'); scanChar(); break; case 't': putChar('\t'); scanChar(); break; case 'n': putChar('\n'); scanChar(); break; case 'f': putChar('\f'); scanChar(); break; case 'r': putChar('\r'); scanChar(); break; case '\'': putChar('\''); scanChar(); break; case '\"': putChar('\"'); scanChar(); break; + case '{': + putChar('{'); scanChar(); break; case '\\': putChar('\\'); scanChar(); break; default: lexError("illegal.esc.char"); } } } else if (bp != buflen) { putChar(ch); scanChar(); } } }
true
true
private void scanLitChar() { if (ch == '\\') { if (buf[bp+1] == '\\' && unicodeConversionBp != bp) { bp++; putChar('\\'); scanChar(); } else { scanChar(); switch (ch) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': char leadch = ch; int oct = digit(8); scanChar(); if ('0' <= ch && ch <= '7') { oct = oct * 8 + digit(8); scanChar(); if (leadch <= '3' && '0' <= ch && ch <= '7') { oct = oct * 8 + digit(8); scanChar(); } } putChar((char)oct); break; case 'b': putChar('\b'); scanChar(); break; case 't': putChar('\t'); scanChar(); break; case 'n': putChar('\n'); scanChar(); break; case 'f': putChar('\f'); scanChar(); break; case 'r': putChar('\r'); scanChar(); break; case '\'': putChar('\''); scanChar(); break; case '\"': putChar('\"'); scanChar(); break; case '\\': putChar('\\'); scanChar(); break; default: lexError("illegal.esc.char"); } } } else if (bp != buflen) { putChar(ch); scanChar(); } }
private void scanLitChar() { if (ch == '\\') { if (buf[bp+1] == '\\' && unicodeConversionBp != bp) { bp++; putChar('\\'); scanChar(); } else { scanChar(); switch (ch) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': char leadch = ch; int oct = digit(8); scanChar(); if ('0' <= ch && ch <= '7') { oct = oct * 8 + digit(8); scanChar(); if (leadch <= '3' && '0' <= ch && ch <= '7') { oct = oct * 8 + digit(8); scanChar(); } } putChar((char)oct); break; case 'b': putChar('\b'); scanChar(); break; case 't': putChar('\t'); scanChar(); break; case 'n': putChar('\n'); scanChar(); break; case 'f': putChar('\f'); scanChar(); break; case 'r': putChar('\r'); scanChar(); break; case '\'': putChar('\''); scanChar(); break; case '\"': putChar('\"'); scanChar(); break; case '{': putChar('{'); scanChar(); break; case '\\': putChar('\\'); scanChar(); break; default: lexError("illegal.esc.char"); } } } else if (bp != buflen) { putChar(ch); scanChar(); } }
diff --git a/src/com/martinbrook/tesseractuhc/command/TeamCommand.java b/src/com/martinbrook/tesseractuhc/command/TeamCommand.java index 4e25cbe..a738b99 100644 --- a/src/com/martinbrook/tesseractuhc/command/TeamCommand.java +++ b/src/com/martinbrook/tesseractuhc/command/TeamCommand.java @@ -1,79 +1,79 @@ package com.martinbrook.tesseractuhc.command; import org.bukkit.ChatColor; import com.martinbrook.tesseractuhc.MatchPhase; import com.martinbrook.tesseractuhc.TesseractUHC; import com.martinbrook.tesseractuhc.UhcPlayer; import com.martinbrook.tesseractuhc.UhcSpectator; public class TeamCommand extends UhcCommandExecutor { public TeamCommand(TesseractUHC plugin) { super(plugin); } @Override protected String runAsAdmin(UhcSpectator sender, String[] args) { return ERROR_COLOR + "Admins cannot join the match. Please use /deop first."; } @Override protected String runAsSpectator(UhcSpectator sender, String[] args) { return this.runAsPlayer(sender.getPlayer(), args); } @Override protected String runAsPlayer(UhcPlayer sender, String[] args) { if (sender.isParticipant()) return ERROR_COLOR + "You have already joined this match. Please /leave before creating a new team."; if (match.getMatchPhase() != MatchPhase.PRE_MATCH) return ERROR_COLOR + "The match is already underway. You cannot create a team."; if (config.isFFA()) return ERROR_COLOR + "This is a FFA match. There are no teams."; if (!match.roomForAnotherTeam()) return ERROR_COLOR + "There are no more team slots left."; if (args.length < 1) return ERROR_COLOR + "Syntax: /team (team name)"; String name = ""; - for (int i = 1; i < args.length; i++) name += args[i] + " "; + for (int i = 0; i < args.length; i++) name += args[i] + " "; name = name.substring(0,name.length()-1); if (match.existsTeamByName(name)) return ERROR_COLOR +"A team with that exact name already exists."; String root = name.toLowerCase().replaceAll(" ", ""); if (root.length() > 5) root=root.substring(0,5); String identifier = root; int i = 0; while (match.existsTeam(identifier)) identifier = root + Integer.toString(i++); if (!match.addTeam(identifier, name)) return ERROR_COLOR + "Could not add a new team. Use /join to join an existing team."; if (!match.addParticipant(sender, identifier)) return ERROR_COLOR + "An error occurred. The team has been created but you could not be joined to it."; match.broadcast(ChatColor.GOLD + "Team " + ChatColor.AQUA + ChatColor.ITALIC + name + ChatColor.RESET + ChatColor.GOLD + " was created by " + sender.getDisplayName() + ".\n" + "To join, type " + ChatColor.AQUA + ChatColor.ITALIC + "/join " + identifier); return OK_COLOR + "Team created. Your team identifier is " + ChatColor.AQUA + identifier; } }
true
true
protected String runAsPlayer(UhcPlayer sender, String[] args) { if (sender.isParticipant()) return ERROR_COLOR + "You have already joined this match. Please /leave before creating a new team."; if (match.getMatchPhase() != MatchPhase.PRE_MATCH) return ERROR_COLOR + "The match is already underway. You cannot create a team."; if (config.isFFA()) return ERROR_COLOR + "This is a FFA match. There are no teams."; if (!match.roomForAnotherTeam()) return ERROR_COLOR + "There are no more team slots left."; if (args.length < 1) return ERROR_COLOR + "Syntax: /team (team name)"; String name = ""; for (int i = 1; i < args.length; i++) name += args[i] + " "; name = name.substring(0,name.length()-1); if (match.existsTeamByName(name)) return ERROR_COLOR +"A team with that exact name already exists."; String root = name.toLowerCase().replaceAll(" ", ""); if (root.length() > 5) root=root.substring(0,5); String identifier = root; int i = 0; while (match.existsTeam(identifier)) identifier = root + Integer.toString(i++); if (!match.addTeam(identifier, name)) return ERROR_COLOR + "Could not add a new team. Use /join to join an existing team."; if (!match.addParticipant(sender, identifier)) return ERROR_COLOR + "An error occurred. The team has been created but you could not be joined to it."; match.broadcast(ChatColor.GOLD + "Team " + ChatColor.AQUA + ChatColor.ITALIC + name + ChatColor.RESET + ChatColor.GOLD + " was created by " + sender.getDisplayName() + ".\n" + "To join, type " + ChatColor.AQUA + ChatColor.ITALIC + "/join " + identifier); return OK_COLOR + "Team created. Your team identifier is " + ChatColor.AQUA + identifier; }
protected String runAsPlayer(UhcPlayer sender, String[] args) { if (sender.isParticipant()) return ERROR_COLOR + "You have already joined this match. Please /leave before creating a new team."; if (match.getMatchPhase() != MatchPhase.PRE_MATCH) return ERROR_COLOR + "The match is already underway. You cannot create a team."; if (config.isFFA()) return ERROR_COLOR + "This is a FFA match. There are no teams."; if (!match.roomForAnotherTeam()) return ERROR_COLOR + "There are no more team slots left."; if (args.length < 1) return ERROR_COLOR + "Syntax: /team (team name)"; String name = ""; for (int i = 0; i < args.length; i++) name += args[i] + " "; name = name.substring(0,name.length()-1); if (match.existsTeamByName(name)) return ERROR_COLOR +"A team with that exact name already exists."; String root = name.toLowerCase().replaceAll(" ", ""); if (root.length() > 5) root=root.substring(0,5); String identifier = root; int i = 0; while (match.existsTeam(identifier)) identifier = root + Integer.toString(i++); if (!match.addTeam(identifier, name)) return ERROR_COLOR + "Could not add a new team. Use /join to join an existing team."; if (!match.addParticipant(sender, identifier)) return ERROR_COLOR + "An error occurred. The team has been created but you could not be joined to it."; match.broadcast(ChatColor.GOLD + "Team " + ChatColor.AQUA + ChatColor.ITALIC + name + ChatColor.RESET + ChatColor.GOLD + " was created by " + sender.getDisplayName() + ".\n" + "To join, type " + ChatColor.AQUA + ChatColor.ITALIC + "/join " + identifier); return OK_COLOR + "Team created. Your team identifier is " + ChatColor.AQUA + identifier; }
diff --git a/src/org/yawlfoundation/yawl/wsinvoker/WSInvoker.java b/src/org/yawlfoundation/yawl/wsinvoker/WSInvoker.java index 076883b..c280ac4 100644 --- a/src/org/yawlfoundation/yawl/wsinvoker/WSInvoker.java +++ b/src/org/yawlfoundation/yawl/wsinvoker/WSInvoker.java @@ -1,280 +1,280 @@ package org.yawlfoundation.yawl.wsinvoker; import java.beans.PropertyDescriptor; import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.beanutils.PropertyUtils; import org.apache.cxf.aegis.util.stax.JDOMStreamReader; import org.apache.cxf.common.util.StringUtils; import org.apache.cxf.endpoint.Client; import org.apache.cxf.endpoint.Endpoint; import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory; import org.apache.cxf.service.model.BindingInfo; import org.apache.cxf.service.model.BindingMessageInfo; import org.apache.cxf.service.model.BindingOperationInfo; import org.apache.cxf.service.model.MessagePartInfo; import org.apache.cxf.service.model.ServiceInfo; import org.apache.cxf.transport.http.HTTPConduit; import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; import org.apache.log4j.Logger; import org.jdom.Element; import org.jdom.input.DOMBuilder; import org.w3c.dom.Document; import org.xml.sax.SAXException; public class WSInvoker { public static final String WS_SCALARRESPONSE_PARAMNAME = "WSScalarResponse"; public static final String WS_COMPLEXREQUEST_PARAMNAME = "WSComplexRequest"; public static final String WS_COMPLEXRESPONSE_PARAMNAME = "WSComplexResponse"; public static final String WS_COMPLEXRESPONSE_ELEMENTNAME = "message"; private Logger _log = Logger.getLogger(this.getClass()); @SuppressWarnings("unchecked") protected static final Set<Class<?>> SCALAR = new HashSet<Class<?>>(Arrays.asList( String.class, Boolean.class, Byte.class, Character.class, Short.class, Integer.class, Float.class, Long.class, Double.class, BigInteger.class, BigDecimal.class, AtomicBoolean.class, AtomicInteger.class, AtomicLong.class, Date.class, Calendar.class, GregorianCalendar.class, UUID.class )); /** * * @param wsdl * @param serviceName * @param bindingName * @param operationName * @param inputData * @return result values as key-value map * @throws Exception */ public Object invoke(URL wsdl, String serviceName, String bindingName, String operationName, Element inputData) throws Exception { // only enable when debugging, can cause OutOfMemoryError on big messages //_log.warn("Input data: " + new XMLOutputter().outputString(inputData)); JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance(); _log.warn("Reading WSDL document from '" + wsdl + "'"); Client client = factory.createClient(wsdl.toExternalForm()); Endpoint endpoint = client.getEndpoint(); List<ServiceInfo> serviceInfos = endpoint.getService().getServiceInfos(); ServiceInfo serviceInfo = StringUtils.isEmpty(serviceName) ? serviceInfos.get(0) : findService(serviceInfos, serviceName); _log.warn("Service: " + serviceInfo.getName()); Collection<BindingInfo> bindings = serviceInfo.getBindings(); BindingInfo binding = StringUtils.isEmpty(bindingName) ? bindings.iterator().next() : findBinding(bindings, bindingName); _log.warn("Binding: " + binding.getName()); BindingOperationInfo operation = findOperation(binding.getOperations(), operationName); - _log.warn("Operation: " + operation); + _log.warn("Operation: " + operation.getName()); BindingMessageInfo inputMessageInfo = operation.getInput(); List<MessagePartInfo> parts = inputMessageInfo.getMessageParts(); MessagePartInfo partInfo = parts.get(0); Class<?> partClass = partInfo.getTypeClass(); PropertyDescriptor[] partProperties = PropertyUtils.getPropertyDescriptors(partClass); Object inputObject = partClass.newInstance(); List<Element> children = inputData.getChildren(); for (PropertyDescriptor property : partProperties) { String propName = property.getName(); Element input = null; for (Element child : children) { if (child.getName().equalsIgnoreCase(propName)) { input = child; } } if (property.getWriteMethod() == null || input == null) { continue; } Class<?> propertyClass = property.getPropertyType(); Object inputPartObject = Unmarshall(input, propertyClass); _log.warn("param name: " + propName + ", value: " + inputPartObject); property.getWriteMethod().invoke(inputObject, inputPartObject); } Object[] results = client.invoke(operation, inputObject); if (results.length == 0) { return null; } Object result = results[0]; return result; } public static Map<String, Object> ExtractFields(Object invokeResult) throws Exception { Map<String, Object> returns = new HashMap<String, Object>(); if (invokeResult == null) { return returns; } if (SCALAR.contains(invokeResult.getClass())) { returns.put(WS_SCALARRESPONSE_PARAMNAME, invokeResult); } else { PropertyDescriptor[] resultProperties = PropertyUtils.getPropertyDescriptors(invokeResult.getClass()); for (PropertyDescriptor property : resultProperties) { String propName = property.getName(); // check if this is a real bean property if (property.getWriteMethod() == null) { continue; } Object value = property.getReadMethod().invoke(invokeResult); returns.put(propName, value); } } return returns; } protected static Object Unmarshall(final Element xmlElement, final Class<?> clas) throws SAXException { final JDOMStreamReader reader = new JDOMStreamReader(xmlElement); return AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { JAXBContext jc; try { jc = JAXBContext.newInstance(clas); Unmarshaller um = jc.createUnmarshaller(); return um.unmarshal(reader, clas).getValue(); } catch (Exception e) { throw new RuntimeException(e); } } }); } public static Element Marshall(final Object input) throws Exception { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); final Document marshallResult = builder.newDocument(); final StringWriter writer = new StringWriter(); AccessController.doPrivileged(new PrivilegedAction<Boolean>() { public Boolean run() { JAXBContext jc; try { jc = JAXBContext.newInstance(input.getClass()); Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FRAGMENT, true); m.marshal( new JAXBElement(new QName("foo"),input.getClass(), input), marshallResult); return true; } catch (Exception e) { throw new RuntimeException(e); } } }); // convert from org.w3c.Node to jdom DOMBuilder jdomBuilder = new DOMBuilder(); org.jdom.Document jdomDoc = jdomBuilder.build(marshallResult); Element rootElement = jdomDoc.getRootElement().setName(WS_COMPLEXRESPONSE_ELEMENTNAME); rootElement.detach(); return rootElement; } protected static BindingOperationInfo findOperation(Collection<BindingOperationInfo> ops, String opName) { for (BindingOperationInfo op : ops) { if (op.getName().getLocalPart().equalsIgnoreCase(opName)) { return op; } } throw new IllegalArgumentException("Operation " + opName + " not found!"); } protected static ServiceInfo findService(Collection<ServiceInfo> services, String serviceName) { for (ServiceInfo service : services) { if (service.getName().getLocalPart().equalsIgnoreCase(serviceName)) { return service; } } throw new IllegalArgumentException("Service " + serviceName + " not found!"); } protected static BindingInfo findBinding(Collection<BindingInfo> bindings, String bindingName) { for (BindingInfo binding : bindings) { if (binding.getName().getLocalPart().equalsIgnoreCase(bindingName)) { return binding; } } throw new IllegalArgumentException("Binding " + bindingName + " not found!"); } }
true
true
public Object invoke(URL wsdl, String serviceName, String bindingName, String operationName, Element inputData) throws Exception { // only enable when debugging, can cause OutOfMemoryError on big messages //_log.warn("Input data: " + new XMLOutputter().outputString(inputData)); JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance(); _log.warn("Reading WSDL document from '" + wsdl + "'"); Client client = factory.createClient(wsdl.toExternalForm()); Endpoint endpoint = client.getEndpoint(); List<ServiceInfo> serviceInfos = endpoint.getService().getServiceInfos(); ServiceInfo serviceInfo = StringUtils.isEmpty(serviceName) ? serviceInfos.get(0) : findService(serviceInfos, serviceName); _log.warn("Service: " + serviceInfo.getName()); Collection<BindingInfo> bindings = serviceInfo.getBindings(); BindingInfo binding = StringUtils.isEmpty(bindingName) ? bindings.iterator().next() : findBinding(bindings, bindingName); _log.warn("Binding: " + binding.getName()); BindingOperationInfo operation = findOperation(binding.getOperations(), operationName); _log.warn("Operation: " + operation); BindingMessageInfo inputMessageInfo = operation.getInput(); List<MessagePartInfo> parts = inputMessageInfo.getMessageParts(); MessagePartInfo partInfo = parts.get(0); Class<?> partClass = partInfo.getTypeClass(); PropertyDescriptor[] partProperties = PropertyUtils.getPropertyDescriptors(partClass); Object inputObject = partClass.newInstance(); List<Element> children = inputData.getChildren(); for (PropertyDescriptor property : partProperties) { String propName = property.getName(); Element input = null; for (Element child : children) { if (child.getName().equalsIgnoreCase(propName)) { input = child; } } if (property.getWriteMethod() == null || input == null) { continue; } Class<?> propertyClass = property.getPropertyType(); Object inputPartObject = Unmarshall(input, propertyClass); _log.warn("param name: " + propName + ", value: " + inputPartObject); property.getWriteMethod().invoke(inputObject, inputPartObject); } Object[] results = client.invoke(operation, inputObject); if (results.length == 0) { return null; } Object result = results[0]; return result; }
public Object invoke(URL wsdl, String serviceName, String bindingName, String operationName, Element inputData) throws Exception { // only enable when debugging, can cause OutOfMemoryError on big messages //_log.warn("Input data: " + new XMLOutputter().outputString(inputData)); JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance(); _log.warn("Reading WSDL document from '" + wsdl + "'"); Client client = factory.createClient(wsdl.toExternalForm()); Endpoint endpoint = client.getEndpoint(); List<ServiceInfo> serviceInfos = endpoint.getService().getServiceInfos(); ServiceInfo serviceInfo = StringUtils.isEmpty(serviceName) ? serviceInfos.get(0) : findService(serviceInfos, serviceName); _log.warn("Service: " + serviceInfo.getName()); Collection<BindingInfo> bindings = serviceInfo.getBindings(); BindingInfo binding = StringUtils.isEmpty(bindingName) ? bindings.iterator().next() : findBinding(bindings, bindingName); _log.warn("Binding: " + binding.getName()); BindingOperationInfo operation = findOperation(binding.getOperations(), operationName); _log.warn("Operation: " + operation.getName()); BindingMessageInfo inputMessageInfo = operation.getInput(); List<MessagePartInfo> parts = inputMessageInfo.getMessageParts(); MessagePartInfo partInfo = parts.get(0); Class<?> partClass = partInfo.getTypeClass(); PropertyDescriptor[] partProperties = PropertyUtils.getPropertyDescriptors(partClass); Object inputObject = partClass.newInstance(); List<Element> children = inputData.getChildren(); for (PropertyDescriptor property : partProperties) { String propName = property.getName(); Element input = null; for (Element child : children) { if (child.getName().equalsIgnoreCase(propName)) { input = child; } } if (property.getWriteMethod() == null || input == null) { continue; } Class<?> propertyClass = property.getPropertyType(); Object inputPartObject = Unmarshall(input, propertyClass); _log.warn("param name: " + propName + ", value: " + inputPartObject); property.getWriteMethod().invoke(inputObject, inputPartObject); } Object[] results = client.invoke(operation, inputObject); if (results.length == 0) { return null; } Object result = results[0]; return result; }
diff --git a/src/powercrystals/minefactoryreloaded/core/MFRUtil.java b/src/powercrystals/minefactoryreloaded/core/MFRUtil.java index d3e00000..bfb91245 100644 --- a/src/powercrystals/minefactoryreloaded/core/MFRUtil.java +++ b/src/powercrystals/minefactoryreloaded/core/MFRUtil.java @@ -1,292 +1,292 @@ package powercrystals.minefactoryreloaded.core; import java.util.Map.Entry; import buildcraft.api.transport.IPipeEntry; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.liquids.ILiquidTank; import net.minecraftforge.liquids.ITankContainer; import net.minecraftforge.liquids.LiquidContainerRegistry; import net.minecraftforge.liquids.LiquidStack; import powercrystals.core.inventory.IInventoryManager; import powercrystals.core.inventory.InventoryManager; import powercrystals.core.position.BlockPosition; import powercrystals.core.util.UtilInventory; import powercrystals.minefactoryreloaded.api.IToolHammer; import powercrystals.minefactoryreloaded.api.IDeepStorageUnit; import powercrystals.minefactoryreloaded.core.ITankContainerBucketable; import powercrystals.minefactoryreloaded.tile.base.TileEntityFactory; public class MFRUtil { public static ItemStack consumeItem(ItemStack stack) { if(stack.stackSize == 1) { if(stack.getItem().hasContainerItem()) { return stack.getItem().getContainerItemStack(stack); } else { return null; } } else { stack.splitStack(1); return stack; } } public static boolean isHoldingWrench(EntityPlayer player) { if(player.inventory.getCurrentItem() == null) { return false; } Item currentItem = Item.itemsList[player.inventory.getCurrentItem().itemID]; if(currentItem != null && currentItem instanceof IToolHammer) { return true; } return false; } public static boolean manuallyFillTank(ITankContainerBucketable itcb, EntityPlayer entityplayer) { ItemStack ci = entityplayer.inventory.getCurrentItem(); LiquidStack liquid = LiquidContainerRegistry.getLiquidForFilledItem(ci); if(liquid != null) { if(itcb.fill(ForgeDirection.UNKNOWN, liquid, false) == liquid.amount) { itcb.fill(ForgeDirection.UNKNOWN, liquid, true); if(!entityplayer.capabilities.isCreativeMode) { entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, consumeItem(ci)); } return true; } } return false; } public static boolean manuallyDrainTank(ITankContainerBucketable itcb, EntityPlayer entityplayer) { ItemStack ci = entityplayer.inventory.getCurrentItem(); if(LiquidContainerRegistry.isEmptyContainer(ci)) { for(ILiquidTank tank : itcb.getTanks(ForgeDirection.UNKNOWN)) { LiquidStack tankLiquid = tank.getLiquid(); ItemStack filledBucket = LiquidContainerRegistry.fillLiquidContainer(tankLiquid, ci); if(LiquidContainerRegistry.isFilledContainer(filledBucket)) { LiquidStack bucketLiquid = LiquidContainerRegistry.getLiquidForFilledItem(filledBucket); if(entityplayer.capabilities.isCreativeMode) { tank.drain(bucketLiquid.amount, true); return true; } else if(ci.stackSize == 1) { tank.drain(bucketLiquid.amount, true); entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, filledBucket); return true; } else if(entityplayer.inventory.addItemStackToInventory(filledBucket)) { tank.drain(bucketLiquid.amount, true); ci.stackSize -= 1; return true; } } } } return false; } public static void pumpLiquid(ILiquidTank tank, TileEntityFactory from) { if(tank != null && tank.getLiquid() != null && tank.getLiquid().amount > 0) { LiquidStack l = tank.getLiquid().copy(); l.amount = Math.min(l.amount, LiquidContainerRegistry.BUCKET_VOLUME); for(BlockPosition adj : new BlockPosition(from).getAdjacent(true)) { TileEntity tile = from.worldObj.getBlockTileEntity(adj.x, adj.y, adj.z); if(tile != null && tile instanceof ITankContainer) { int filled = ((ITankContainer)tile).fill(adj.orientation.getOpposite(), l, true); tank.drain(filled, true); l.amount -= filled; if(l.amount <= 0) { break; } } } } } public static void mergeStacks(ItemStack to, ItemStack from) { if(to == null || from == null) return; if(to.itemID != from.itemID || to.getItemDamage() != from.getItemDamage()) return; if(to.getTagCompound() != null || from.getTagCompound() != null) return; int amountToCopy = Math.min(to.getMaxStackSize() - to.stackSize, from.stackSize); to.stackSize += amountToCopy; from.stackSize -= amountToCopy; } public static ItemStack dropStackDirected(TileEntityFactory from, ItemStack s, ForgeDirection towards) { if(s == null) { return null; } s = s.copy(); BlockPosition bp = new BlockPosition(from.xCoord, from.yCoord, from.zCoord); bp.orientation = towards; bp.moveForwards(1); TileEntity te = from.worldObj.getBlockTileEntity(bp.x, bp.y, bp.z); if(te != null && te instanceof IInventory) { IInventoryManager manager = InventoryManager.create((IInventory)te, towards.getOpposite()); s = manager.addItem(s); } else if(te != null && te instanceof IPipeEntry && ((IPipeEntry)te).acceptItems()) { ((IPipeEntry)te).entityEntering(s.copy(), towards); s.stackSize = 0; } if(s != null && s.stackSize > 0 && !from.worldObj.isBlockSolidOnSide(bp.x, bp.y, bp.z, towards.getOpposite())) { dropStackOnGround(s, BlockPosition.fromFactoryTile(from), from.worldObj, towards); } return s; } public static void dropStack(TileEntityFactory from, ItemStack s) { if(s == null) { return; } s = s.copy(); if(from.worldObj.isRemote || s.stackSize <= 0) { return; } for(ForgeDirection o : UtilInventory.findPipes(from.worldObj, from.xCoord, from.yCoord, from.zCoord)) { BlockPosition bp = new BlockPosition(from.xCoord, from.yCoord, from.zCoord); bp.orientation = o; bp.moveForwards(1); TileEntity te = from.worldObj.getBlockTileEntity(bp.x, bp.y, bp.z); if(te != null && te instanceof IPipeEntry && ((IPipeEntry)te).acceptItems()) { ((IPipeEntry)te).entityEntering(s, o); return; } } for(Entry<ForgeDirection, IInventory> chest : UtilInventory.findChests(from.worldObj, from.xCoord, from.yCoord, from.zCoord).entrySet()) { if(chest.getValue().getInvName() == "Engine") { continue; } if(chest.getValue() instanceof IDeepStorageUnit) { IDeepStorageUnit idsu = (IDeepStorageUnit)chest.getValue(); // don't put s in a DSU if it has NBT data if(s.getTagCompound() != null) { continue; } // don't put s in a DSU if the stored quantity is nonzero and it's mismatched with the stored item type if(idsu.getStoredItemType() != null && (idsu.getStoredItemType().itemID != s.itemID || idsu.getStoredItemType().getItemDamage() != s.getItemDamage())) { continue; } } IInventoryManager manager = InventoryManager.create((IInventory)chest.getValue(), chest.getKey().getOpposite()); s = manager.addItem(s); - if(s.stackSize == 0) + if(s == null || s.stackSize == 0) { return; } } - if(s.stackSize > 0) + if(s != null && s.stackSize > 0) { dropStackOnGround(s, BlockPosition.fromFactoryTile(from), from.worldObj, from.getDropDirection()); } } private static void dropStackOnGround(ItemStack stack, BlockPosition from, World world, ForgeDirection towards) { float dropOffsetX = 0.0F; float dropOffsetY = 0.0F; float dropOffsetZ = 0.0F; switch(towards) { case UNKNOWN: case UP: dropOffsetX = 0.5F; dropOffsetY = 1.5F; dropOffsetZ = 0.5F; break; case DOWN: dropOffsetX = 0.5F; dropOffsetY = -0.75F; dropOffsetZ = 0.5F; break; case NORTH: dropOffsetX = 0.5F; dropOffsetY = 0.5F; dropOffsetZ = -0.5F; break; case SOUTH: dropOffsetX = 0.5F; dropOffsetY = 0.5F; dropOffsetZ = 1.5F; break; case EAST: dropOffsetX = 1.5F; dropOffsetY = 0.5F; dropOffsetZ = 0.5F; break; case WEST: dropOffsetX = -0.5F; dropOffsetY = 0.5F; dropOffsetZ = 0.5F; break; default: break; } EntityItem entityitem = new EntityItem(world, from.x + dropOffsetX, from.y + dropOffsetY, from.z + dropOffsetZ, stack.copy()); entityitem.motionX = 0.0D; if(towards != ForgeDirection.DOWN) entityitem.motionY = 0.3D; entityitem.motionZ = 0.0D; entityitem.delayBeforeCanPickup = 20; world.spawnEntityInWorld(entityitem); stack.stackSize = 0; } }
false
true
public static void dropStack(TileEntityFactory from, ItemStack s) { if(s == null) { return; } s = s.copy(); if(from.worldObj.isRemote || s.stackSize <= 0) { return; } for(ForgeDirection o : UtilInventory.findPipes(from.worldObj, from.xCoord, from.yCoord, from.zCoord)) { BlockPosition bp = new BlockPosition(from.xCoord, from.yCoord, from.zCoord); bp.orientation = o; bp.moveForwards(1); TileEntity te = from.worldObj.getBlockTileEntity(bp.x, bp.y, bp.z); if(te != null && te instanceof IPipeEntry && ((IPipeEntry)te).acceptItems()) { ((IPipeEntry)te).entityEntering(s, o); return; } } for(Entry<ForgeDirection, IInventory> chest : UtilInventory.findChests(from.worldObj, from.xCoord, from.yCoord, from.zCoord).entrySet()) { if(chest.getValue().getInvName() == "Engine") { continue; } if(chest.getValue() instanceof IDeepStorageUnit) { IDeepStorageUnit idsu = (IDeepStorageUnit)chest.getValue(); // don't put s in a DSU if it has NBT data if(s.getTagCompound() != null) { continue; } // don't put s in a DSU if the stored quantity is nonzero and it's mismatched with the stored item type if(idsu.getStoredItemType() != null && (idsu.getStoredItemType().itemID != s.itemID || idsu.getStoredItemType().getItemDamage() != s.getItemDamage())) { continue; } } IInventoryManager manager = InventoryManager.create((IInventory)chest.getValue(), chest.getKey().getOpposite()); s = manager.addItem(s); if(s.stackSize == 0) { return; } } if(s.stackSize > 0) { dropStackOnGround(s, BlockPosition.fromFactoryTile(from), from.worldObj, from.getDropDirection()); } }
public static void dropStack(TileEntityFactory from, ItemStack s) { if(s == null) { return; } s = s.copy(); if(from.worldObj.isRemote || s.stackSize <= 0) { return; } for(ForgeDirection o : UtilInventory.findPipes(from.worldObj, from.xCoord, from.yCoord, from.zCoord)) { BlockPosition bp = new BlockPosition(from.xCoord, from.yCoord, from.zCoord); bp.orientation = o; bp.moveForwards(1); TileEntity te = from.worldObj.getBlockTileEntity(bp.x, bp.y, bp.z); if(te != null && te instanceof IPipeEntry && ((IPipeEntry)te).acceptItems()) { ((IPipeEntry)te).entityEntering(s, o); return; } } for(Entry<ForgeDirection, IInventory> chest : UtilInventory.findChests(from.worldObj, from.xCoord, from.yCoord, from.zCoord).entrySet()) { if(chest.getValue().getInvName() == "Engine") { continue; } if(chest.getValue() instanceof IDeepStorageUnit) { IDeepStorageUnit idsu = (IDeepStorageUnit)chest.getValue(); // don't put s in a DSU if it has NBT data if(s.getTagCompound() != null) { continue; } // don't put s in a DSU if the stored quantity is nonzero and it's mismatched with the stored item type if(idsu.getStoredItemType() != null && (idsu.getStoredItemType().itemID != s.itemID || idsu.getStoredItemType().getItemDamage() != s.getItemDamage())) { continue; } } IInventoryManager manager = InventoryManager.create((IInventory)chest.getValue(), chest.getKey().getOpposite()); s = manager.addItem(s); if(s == null || s.stackSize == 0) { return; } } if(s != null && s.stackSize > 0) { dropStackOnGround(s, BlockPosition.fromFactoryTile(from), from.worldObj, from.getDropDirection()); } }
diff --git a/com.ibm.wala.core/src/com/ibm/wala/eclipse/AbstractJavaAnalysisAction.java b/com.ibm.wala.core/src/com/ibm/wala/eclipse/AbstractJavaAnalysisAction.java index ee82e969d..7ecd4e036 100644 --- a/com.ibm.wala.core/src/com/ibm/wala/eclipse/AbstractJavaAnalysisAction.java +++ b/com.ibm.wala.core/src/com/ibm/wala/eclipse/AbstractJavaAnalysisAction.java @@ -1,193 +1,197 @@ /******************************************************************************* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.wala.eclipse; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import org.eclipse.core.resources.ResourcesPlugin; 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.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jface.action.IAction; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IActionDelegate; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.progress.IProgressService; import com.ibm.wala.classLoader.Module; import com.ibm.wala.eclipse.util.EclipseProjectPath; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.debug.Assertions; /** * An Eclipse action that analyzes a Java selection */ public abstract class AbstractJavaAnalysisAction implements IObjectActionDelegate, IRunnableWithProgress { private ISelection currentSelection; public AbstractJavaAnalysisAction() { super(); } /** * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) */ public void setActivePart(IAction action, IWorkbenchPart targetPart) { } /** * Compute an analysis scope for the current selection */ public static AnalysisScope computeScope(IStructuredSelection selection) throws IOException { return computeScope(selection, false, true); } public static AnalysisScope computeScope(final IStructuredSelection selection, final boolean includeSource, final boolean includeClassFiles) throws IOException { if (selection == null) { throw new IllegalArgumentException("null selection"); } final Collection<EclipseProjectPath> projectPaths = new LinkedList<EclipseProjectPath>(); Job job = new Job("Compute project paths") { @Override protected IStatus run(IProgressMonitor monitor) { for (Iterator it = selection.iterator(); it.hasNext();) { Object object = it.next(); if (object instanceof IJavaElement) { IJavaElement e = (IJavaElement) object; IJavaProject jp = e.getJavaProject(); try { projectPaths.add(EclipseProjectPath.make(jp, includeSource, includeClassFiles)); } catch (CoreException e1) { e1.printStackTrace(); // skip and continue } catch (IOException e2) { e2.printStackTrace(); return new Status(IStatus.ERROR, "", "", e2); } } else { Assertions.UNREACHABLE(object.getClass()); } } return Status.OK_STATUS; } }; // lock the whole workspace job.setRule(ResourcesPlugin.getWorkspace().getRoot()); job.schedule(); try { job.join(); IStatus result = job.getResult(); if (result.getSeverity() == IStatus.ERROR) { - IOException exception = (IOException) result.getException(); - throw exception; + Throwable exception = result.getException(); + if (exception instanceof IOException) { + throw (IOException)exception; + } else if (exception instanceof RuntimeException) { + throw (RuntimeException)exception; + } } } catch (InterruptedException e) { e.printStackTrace(); assert false; } AnalysisScope scope = mergeProjectPaths(projectPaths); return scope; } /** * compute the java projects represented by the current selection */ protected Collection<IJavaProject> computeJavaProjects() { IStructuredSelection selection = (IStructuredSelection) currentSelection; Collection<IJavaProject> projects = HashSetFactory.make(); for (Iterator it = selection.iterator(); it.hasNext();) { Object object = it.next(); if (object instanceof IJavaElement) { IJavaElement e = (IJavaElement) object; IJavaProject jp = e.getJavaProject(); projects.add(jp); } else { Assertions.UNREACHABLE(object.getClass()); } } return projects; } /** * create an analysis scope as the union of a bunch of EclipseProjectPath * * @throws IOException */ private static AnalysisScope mergeProjectPaths(Collection<EclipseProjectPath> projectPaths) throws IOException { AnalysisScope scope = AnalysisScope.createJavaAnalysisScope(); Collection<Module> seen = HashSetFactory.make(); // to avoid duplicates, we first add all application modules, then extension // modules, then primordial buildScope(ClassLoaderReference.Application, projectPaths, scope, seen); buildScope(ClassLoaderReference.Extension, projectPaths, scope, seen); buildScope(ClassLoaderReference.Primordial, projectPaths, scope, seen); return scope; } private static void buildScope(ClassLoaderReference loader, Collection<EclipseProjectPath> projectPaths, AnalysisScope scope, Collection<Module> seen) throws IOException { for (EclipseProjectPath path : projectPaths) { AnalysisScope pScope = path.toAnalysisScope((File) null); for (Module m : pScope.getModules(loader)) { if (!seen.contains(m)) { seen.add(m); scope.addToScope(loader, m); } } } } /** * @see IActionDelegate#run(IAction) */ public void run(IAction action) { IProgressService progressService = PlatformUI.getWorkbench().getProgressService(); try { progressService.busyCursorWhile(this); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } /** * @see IActionDelegate#selectionChanged(IAction, ISelection) */ public void selectionChanged(IAction action, ISelection selection) { currentSelection = selection; } public ISelection getCurrentSelection() { return currentSelection; } }
true
true
public static AnalysisScope computeScope(final IStructuredSelection selection, final boolean includeSource, final boolean includeClassFiles) throws IOException { if (selection == null) { throw new IllegalArgumentException("null selection"); } final Collection<EclipseProjectPath> projectPaths = new LinkedList<EclipseProjectPath>(); Job job = new Job("Compute project paths") { @Override protected IStatus run(IProgressMonitor monitor) { for (Iterator it = selection.iterator(); it.hasNext();) { Object object = it.next(); if (object instanceof IJavaElement) { IJavaElement e = (IJavaElement) object; IJavaProject jp = e.getJavaProject(); try { projectPaths.add(EclipseProjectPath.make(jp, includeSource, includeClassFiles)); } catch (CoreException e1) { e1.printStackTrace(); // skip and continue } catch (IOException e2) { e2.printStackTrace(); return new Status(IStatus.ERROR, "", "", e2); } } else { Assertions.UNREACHABLE(object.getClass()); } } return Status.OK_STATUS; } }; // lock the whole workspace job.setRule(ResourcesPlugin.getWorkspace().getRoot()); job.schedule(); try { job.join(); IStatus result = job.getResult(); if (result.getSeverity() == IStatus.ERROR) { IOException exception = (IOException) result.getException(); throw exception; } } catch (InterruptedException e) { e.printStackTrace(); assert false; } AnalysisScope scope = mergeProjectPaths(projectPaths); return scope; }
public static AnalysisScope computeScope(final IStructuredSelection selection, final boolean includeSource, final boolean includeClassFiles) throws IOException { if (selection == null) { throw new IllegalArgumentException("null selection"); } final Collection<EclipseProjectPath> projectPaths = new LinkedList<EclipseProjectPath>(); Job job = new Job("Compute project paths") { @Override protected IStatus run(IProgressMonitor monitor) { for (Iterator it = selection.iterator(); it.hasNext();) { Object object = it.next(); if (object instanceof IJavaElement) { IJavaElement e = (IJavaElement) object; IJavaProject jp = e.getJavaProject(); try { projectPaths.add(EclipseProjectPath.make(jp, includeSource, includeClassFiles)); } catch (CoreException e1) { e1.printStackTrace(); // skip and continue } catch (IOException e2) { e2.printStackTrace(); return new Status(IStatus.ERROR, "", "", e2); } } else { Assertions.UNREACHABLE(object.getClass()); } } return Status.OK_STATUS; } }; // lock the whole workspace job.setRule(ResourcesPlugin.getWorkspace().getRoot()); job.schedule(); try { job.join(); IStatus result = job.getResult(); if (result.getSeverity() == IStatus.ERROR) { Throwable exception = result.getException(); if (exception instanceof IOException) { throw (IOException)exception; } else if (exception instanceof RuntimeException) { throw (RuntimeException)exception; } } } catch (InterruptedException e) { e.printStackTrace(); assert false; } AnalysisScope scope = mergeProjectPaths(projectPaths); return scope; }
diff --git a/MPDroid/src/com/namelessdev/mpdroid/fragments/FSFragment.java b/MPDroid/src/com/namelessdev/mpdroid/fragments/FSFragment.java index 28137917..916c2216 100644 --- a/MPDroid/src/com/namelessdev/mpdroid/fragments/FSFragment.java +++ b/MPDroid/src/com/namelessdev/mpdroid/fragments/FSFragment.java @@ -1,229 +1,229 @@ /* * Copyright (C) 2010-2014 The MPDroid Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.namelessdev.mpdroid.fragments; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.TextView; import com.namelessdev.mpdroid.R; import com.namelessdev.mpdroid.library.ILibraryFragmentActivity; import com.namelessdev.mpdroid.tools.Tools; import org.a0z.mpd.Directory; import org.a0z.mpd.FilesystemTreeEntry; import org.a0z.mpd.Item; import org.a0z.mpd.MPDCommand; import org.a0z.mpd.Music; import org.a0z.mpd.PlaylistFile; import org.a0z.mpd.exception.MPDServerException; import java.util.ArrayList; import java.util.List; public class FSFragment extends BrowseFragment { private static final String EXTRA_DIRECTORY = "directory"; private Directory currentDirectory = null; private String directory = null; private int numSubdirs = 0; // number of subdirectories including ".." public FSFragment() { super(R.string.addDirectory, R.string.addedDirectoryToPlaylist, MPDCommand.MPD_SEARCH_FILENAME); } @Override protected void add(Item item, boolean replace, boolean play) { try { final Directory ToAdd = currentDirectory.getDirectory(item.getName()); if (ToAdd != null) { // Valid directory app.oMPDAsyncHelper.oMPD.add(ToAdd, replace, play); Tools.notifyUser(String.format( getResources().getString(R.string.addedDirectoryToPlaylist), item), FSFragment.this.getActivity()); } else { app.oMPDAsyncHelper.oMPD.add((FilesystemTreeEntry) item, replace, play); Tools.notifyUser(getResources().getString(R.string.songAdded, item), FSFragment.this.getActivity()); } } catch (MPDServerException e) { e.printStackTrace(); } } @Override protected void add(Item item, String playlist) { try { Directory ToAdd = currentDirectory.getDirectory(item.getName()); if (ToAdd != null) { // Valid directory app.oMPDAsyncHelper.oMPD.addToPlaylist(playlist, ToAdd); Tools.notifyUser(String.format( getResources().getString(R.string.addedDirectoryToPlaylist), item), FSFragment.this.getActivity()); } else { if (item instanceof Music) { ArrayList<Music> songs = new ArrayList<Music>(); songs.add((Music) item); app.oMPDAsyncHelper.oMPD.addToPlaylist(playlist, songs); Tools.notifyUser(getResources().getString(R.string.songAdded, item), FSFragment.this.getActivity()); } if (item instanceof PlaylistFile) { app.oMPDAsyncHelper.oMPD.getPlaylist() .load(((PlaylistFile) item).getFullpath()); } } } catch (MPDServerException e) { e.printStackTrace(); } } @Override protected void asyncUpdate() { if (!TextUtils.isEmpty(directory)) { currentDirectory = app.oMPDAsyncHelper.oMPD.getRootDirectory().makeDirectory(directory); } else { currentDirectory = app.oMPDAsyncHelper.oMPD.getRootDirectory(); } try { currentDirectory.refreshData(); } catch (MPDServerException e) { e.printStackTrace(); } ArrayList<Item> newItems = new ArrayList<Item>(); // add parent directory: if (!"".equals(currentDirectory.getFullpath())) { Directory parent = new Directory(currentDirectory.getParent()); if (parent != null) { parent.setName(".."); newItems.add(parent); } } newItems.addAll(currentDirectory.getDirectories()); numSubdirs = newItems.size(); // stors number if subdirs newItems.addAll(currentDirectory.getFiles()); // Do not show playlists for root directory - if (directory != null) { + if (!TextUtils.isEmpty(directory)) { newItems.addAll(currentDirectory.getPlaylistFiles()); } items = newItems; } // Disable the indexer for FSFragment @SuppressWarnings("unchecked") protected ListAdapter getCustomListAdapter() { return new ArrayAdapter<Item>(getActivity(), R.layout.fs_list_item, R.id.text1, (List<Item>) items) { @Override public View getView(int position, View convertView, ViewGroup parent) { final View v = super.getView(position, convertView, parent); final TextView subtext = (TextView) v.findViewById(R.id.text2); final Item item = items.get(position); String filename; if (item instanceof Music) { filename = ((Music) item).getFilename(); if (!TextUtils.isEmpty(filename) && !item.toString().equals(filename)) { subtext.setVisibility(View.VISIBLE); subtext.setText(filename); } else { subtext.setVisibility(View.GONE); } } else { subtext.setVisibility(View.GONE); } return v; } }; } @Override public String getTitle() { if (TextUtils.isEmpty(directory)) { try { return getString(R.string.files); } catch (IllegalStateException e) { // Can't get the translated string if we are not attached ... // Stupid workaround return "/"; } } else { return directory; } } public FSFragment init(String path) { directory = path; return this; } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); if (icicle != null) init(icicle.getString(EXTRA_DIRECTORY)); } @Override public void onItemClick(AdapterView<?> l, View v, int position, long id) { // click on a file, not dir if (position > numSubdirs - 1 || numSubdirs == 0) { final FilesystemTreeEntry item = (FilesystemTreeEntry) items.get(position); app.oMPDAsyncHelper.execAsync(new Runnable() { @Override public void run() { try { int songId = -1; if (item instanceof Music) { app.oMPDAsyncHelper.oMPD.getPlaylist().add(item); } else if (item instanceof PlaylistFile) { app.oMPDAsyncHelper.oMPD.getPlaylist().load(item.getFullpath()); } if (songId > -1) { app.oMPDAsyncHelper.oMPD.skipToId(songId); } } catch (MPDServerException e) { e.printStackTrace(); } } }); } else { final String dir = ((Directory) items.toArray()[position]).getFullpath(); ((ILibraryFragmentActivity) getActivity()).pushLibraryFragment( new FSFragment().init(dir), "filesystem"); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putString(EXTRA_DIRECTORY, directory); super.onSaveInstanceState(outState); } }
true
true
protected void asyncUpdate() { if (!TextUtils.isEmpty(directory)) { currentDirectory = app.oMPDAsyncHelper.oMPD.getRootDirectory().makeDirectory(directory); } else { currentDirectory = app.oMPDAsyncHelper.oMPD.getRootDirectory(); } try { currentDirectory.refreshData(); } catch (MPDServerException e) { e.printStackTrace(); } ArrayList<Item> newItems = new ArrayList<Item>(); // add parent directory: if (!"".equals(currentDirectory.getFullpath())) { Directory parent = new Directory(currentDirectory.getParent()); if (parent != null) { parent.setName(".."); newItems.add(parent); } } newItems.addAll(currentDirectory.getDirectories()); numSubdirs = newItems.size(); // stors number if subdirs newItems.addAll(currentDirectory.getFiles()); // Do not show playlists for root directory if (directory != null) { newItems.addAll(currentDirectory.getPlaylistFiles()); } items = newItems; }
protected void asyncUpdate() { if (!TextUtils.isEmpty(directory)) { currentDirectory = app.oMPDAsyncHelper.oMPD.getRootDirectory().makeDirectory(directory); } else { currentDirectory = app.oMPDAsyncHelper.oMPD.getRootDirectory(); } try { currentDirectory.refreshData(); } catch (MPDServerException e) { e.printStackTrace(); } ArrayList<Item> newItems = new ArrayList<Item>(); // add parent directory: if (!"".equals(currentDirectory.getFullpath())) { Directory parent = new Directory(currentDirectory.getParent()); if (parent != null) { parent.setName(".."); newItems.add(parent); } } newItems.addAll(currentDirectory.getDirectories()); numSubdirs = newItems.size(); // stors number if subdirs newItems.addAll(currentDirectory.getFiles()); // Do not show playlists for root directory if (!TextUtils.isEmpty(directory)) { newItems.addAll(currentDirectory.getPlaylistFiles()); } items = newItems; }