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/liquibase-core/src/main/java/liquibase/database/structure/UniqueConstraint.java b/liquibase-core/src/main/java/liquibase/database/structure/UniqueConstraint.java index 8bbd64bc..493cd938 100644 --- a/liquibase-core/src/main/java/liquibase/database/structure/UniqueConstraint.java +++ b/liquibase-core/src/main/java/liquibase/database/structure/UniqueConstraint.java @@ -1,158 +1,158 @@ package liquibase.database.structure; import liquibase.util.StringUtils; import java.util.ArrayList; import java.util.List; public class UniqueConstraint implements DatabaseObject, Comparable<UniqueConstraint> { private String name; private Table table; private List<String> columns = new ArrayList<String>(); private boolean deferrable; private boolean initiallyDeferred; private boolean disabled; // Setting tablespace attribute for UC's index. private String tablespace; public DatabaseObject[] getContainingObjects() { List<DatabaseObject> columns = new ArrayList<DatabaseObject>(); for (String column : this.columns) { columns.add(new Column().setName(column).setTable(table)); } return columns.toArray(new DatabaseObject[columns.size()]); } public String getName() { return name; } public void setName(String constraintName) { this.name = constraintName; } public Table getTable() { return table; } public void setTable(Table table) { this.table = table; } public List<String> getColumns() { return columns; } public boolean isDeferrable() { return deferrable; } public void setDeferrable(boolean deferrable) { this.deferrable = deferrable; } public boolean isInitiallyDeferred() { return initiallyDeferred; } public void setInitiallyDeferred(boolean initiallyDeferred) { this.initiallyDeferred = initiallyDeferred; } public String getColumnNames() { return StringUtils.join(columns, ", "); } public void setDisabled(boolean disabled) { this.disabled = disabled; } public boolean isDisabled() { return disabled; } public String getTablespace() { return tablespace; } public void setTablespace(String tablespace) { this.tablespace = tablespace; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (null == this.getColumnNames()) return false; UniqueConstraint that = (UniqueConstraint) o; boolean result = false; result = !(getColumnNames() != null ? !getColumnNames() .equalsIgnoreCase(that.getColumnNames()) : that .getColumnNames() != null) && isDeferrable() == that.isDeferrable() && isInitiallyDeferred() == that.isInitiallyDeferred() && isDisabled() == that.isDisabled(); // Need check for nulls here due to NullPointerException using // Postgres if (result) { if (null == this.getTable()) { result = null == that.getTable(); - } else if (null == this.getTable()) { + } else if (null == that.getTable()) { result = false; } else { result = this.getTable().getName().equals( that.getTable().getName()); } } return result; } /** * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(UniqueConstraint o) { // Need check for nulls here due to NullPointerException using Postgres String thisTableName; String thatTableName; thisTableName = null == this.getTable() ? "" : this.getTable() .getName(); thatTableName = null == o.getTable() ? "" : o.getTable().getName(); int returnValue = thisTableName.compareTo(thatTableName); if (returnValue == 0) { returnValue = this.getName().compareTo(o.getName()); } if (returnValue == 0) { returnValue = this.getColumnNames().compareTo(o.getColumnNames()); } return returnValue; } @Override public int hashCode() { int result = 0; if (this.table != null) { result = this.table.hashCode(); } if (this.name != null) { result = 31 * result + this.name.toUpperCase().hashCode(); } if (getColumnNames() != null) { result = 31 * result + getColumnNames().hashCode(); } return result; } @Override public String toString() { return getName() + " on " + getTable().getName() + "(" + getColumnNames() + ")"; } }
true
true
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (null == this.getColumnNames()) return false; UniqueConstraint that = (UniqueConstraint) o; boolean result = false; result = !(getColumnNames() != null ? !getColumnNames() .equalsIgnoreCase(that.getColumnNames()) : that .getColumnNames() != null) && isDeferrable() == that.isDeferrable() && isInitiallyDeferred() == that.isInitiallyDeferred() && isDisabled() == that.isDisabled(); // Need check for nulls here due to NullPointerException using // Postgres if (result) { if (null == this.getTable()) { result = null == that.getTable(); } else if (null == this.getTable()) { result = false; } else { result = this.getTable().getName().equals( that.getTable().getName()); } } return result; }
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (null == this.getColumnNames()) return false; UniqueConstraint that = (UniqueConstraint) o; boolean result = false; result = !(getColumnNames() != null ? !getColumnNames() .equalsIgnoreCase(that.getColumnNames()) : that .getColumnNames() != null) && isDeferrable() == that.isDeferrable() && isInitiallyDeferred() == that.isInitiallyDeferred() && isDisabled() == that.isDisabled(); // Need check for nulls here due to NullPointerException using // Postgres if (result) { if (null == this.getTable()) { result = null == that.getTable(); } else if (null == that.getTable()) { result = false; } else { result = this.getTable().getName().equals( that.getTable().getName()); } } return result; }
diff --git a/src/de/snertlab/xdccBee/ui/Application.java b/src/de/snertlab/xdccBee/ui/Application.java index 18aa1a4..e9bac8d 100644 --- a/src/de/snertlab/xdccBee/ui/Application.java +++ b/src/de/snertlab/xdccBee/ui/Application.java @@ -1,217 +1,217 @@ /* * Project: xdccBee * Copyright (C) 2009 [email protected], * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.snertlab.xdccBee.ui; import java.io.IOException; import java.util.Properties; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.StatusLineManager; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.window.ApplicationWindow; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import de.snertlab.xdccBee.messages.XdccBeeMessages; import de.snertlab.xdccBee.settings.ServerSettings; import de.snertlab.xdccBee.settings.Settings; import de.snertlab.xdccBee.tools.CocoaUIEnhancer; import de.snertlab.xdccBee.ui.actions.ActionAbout; import de.snertlab.xdccBee.ui.actions.ActionPreferences; import de.snertlab.xdccBee.ui.actions.ActionQuit; /** * @author snert * */ public class Application extends ApplicationWindow { public static final String VERSION_STRING = readVersionNrFromProperties(); private static Application window; private ViewMain viewMain; public static void main(String args[]) { try { //INFO: Unter MacOsx muss jar wie folgt gestartet werden: java -XstartOnFirstThread -jar window = new Application(); window.setBlockOnOpen(true); window.open(); if(Display.getCurrent() != null && ! Display.getCurrent().isDisposed()){ Display.getCurrent().dispose(); } } catch (Exception e) { throw new RuntimeException(e); } } public static Application getWindow() { return window; } public static boolean isMac() { if ( System.getProperty( "os.name" ).equals( "Mac OS X" ) ) { //$NON-NLS-1$ //$NON-NLS-2$ return true; } return false; } public Application() { super(null); addToolBar(SWT.FLAT | SWT.WRAP); addMenuBar(); addStatusLine(); } @Override protected Control createContents(Composite parent) { if(isMac()) macMenu(); //Geht leider nicht in addMenuBar da shell noch nich da ist Composite container = new Composite(parent, SWT.NONE); container.setLayout(new FormLayout()); viewMain = new ViewMain(); viewMain.createContents(container); return container; } private void macMenu(){ try { Listener listener = new Listener() { @Override public void handleEvent(Event event) { new ActionQuit(false).run(); } }; CocoaUIEnhancer enhancer = new CocoaUIEnhancer( XdccBeeMessages.getString("Application_TITLE") ); //$NON-NLS-1$ enhancer.hookApplicationMenu( getShell().getDisplay(), listener, new ActionAbout(getShell()), new ActionPreferences(getShell())); } catch (Throwable e) { throw new RuntimeException(e); } } private void winMenu(MenuManager menuManager) { MenuManager fileMenu = new MenuManager(XdccBeeMessages.getString("Application_MENU_FILE")); //$NON-NLS-1$ MenuManager helpMenu = new MenuManager(XdccBeeMessages.getString("Application_MENU_HELP")); //$NON-NLS-1$ menuManager.add( fileMenu ); menuManager.add( helpMenu ); fileMenu.add( new ActionPreferences(getShell()) ); fileMenu.add( new ActionQuit(true) ); helpMenu.add( new ActionAbout(getShell()) ); } @Override protected MenuManager createMenuManager() { MenuManager menuManager = new MenuManager("menu"); //$NON-NLS-1$ if( ! isMac() ){ winMenu(menuManager); } return menuManager; } @Override protected ToolBarManager createToolBarManager(int style) { ToolBarManager toolBarManager = new ToolBarManager(style); return toolBarManager; } @Override protected StatusLineManager createStatusLineManager() { StatusLineManager statusLineManager = new StatusLineManager(); return statusLineManager; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(XdccBeeMessages.getString("Application_TITLE")); //$NON-NLS-1$ newShell.setSize(getSettings().getMainWindowSize()); if(getSettings().getMainWindowPosition().x !=0 || getSettings().getMainWindowPosition().y !=0 ){ newShell.setLocation(getSettings().getMainWindowPosition()); }else{ centerShell(newShell); } newShell.addDisposeListener( new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { - new ActionQuit(true).run(); + new ActionQuit(false).run(); } }); } private void centerShell(Shell newShell) { Rectangle pDisplayBounds = newShell.getDisplay().getBounds(); int nLeft = (pDisplayBounds.width - getInitialSize().x) / 2; int nTop = (pDisplayBounds.height - getInitialSize().y) / 2; newShell.setBounds(nLeft, nTop, getInitialSize().x, getInitialSize().y); } public static void placeDialogInCenter(Shell parent, Shell shell){ Rectangle parentSize = parent.getBounds(); Rectangle mySize = shell.getBounds(); int locationX, locationY; locationX = (parentSize.width - mySize.width)/2+parentSize.x; locationY = (parentSize.height - mySize.height)/2+parentSize.y; shell.setLocation(new Point(locationX, locationY)); } @Override protected Point getInitialSize() { return getSettings().getMainWindowSize(); } public static Settings getSettings(){ return Settings.getInstance(); } public static ServerSettings getServerSettings(){ return ServerSettings.getInstance(); } public ViewMain getViewMain() { return viewMain; } private static String readVersionNrFromProperties(){ Properties prop = loadVersionProperties(); String version = ""; //$NON-NLS-1$ String major = (String)prop.get("build.major.number"); //$NON-NLS-1$ String minor = (String)prop.get("build.minor.number"); //$NON-NLS-1$ String patch = (String)prop.get("build.patch.number"); //$NON-NLS-1$ String revision = (String)prop.get("build.revision.number"); //$NON-NLS-1$ version = "Version " + major + "." + minor + "." + patch + " Build(" + revision + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ return version; } private static Properties loadVersionProperties(){ try { Properties properties = new Properties(); properties.load(Application.class.getResourceAsStream("version.properties")); //$NON-NLS-1$ return properties; } catch (IOException e) { throw new RuntimeException(e); } } }
true
true
protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(XdccBeeMessages.getString("Application_TITLE")); //$NON-NLS-1$ newShell.setSize(getSettings().getMainWindowSize()); if(getSettings().getMainWindowPosition().x !=0 || getSettings().getMainWindowPosition().y !=0 ){ newShell.setLocation(getSettings().getMainWindowPosition()); }else{ centerShell(newShell); } newShell.addDisposeListener( new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { new ActionQuit(true).run(); } }); }
protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(XdccBeeMessages.getString("Application_TITLE")); //$NON-NLS-1$ newShell.setSize(getSettings().getMainWindowSize()); if(getSettings().getMainWindowPosition().x !=0 || getSettings().getMainWindowPosition().y !=0 ){ newShell.setLocation(getSettings().getMainWindowPosition()); }else{ centerShell(newShell); } newShell.addDisposeListener( new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { new ActionQuit(false).run(); } }); }
diff --git a/com.heroku.eclipse.ui/src/com/heroku/eclipse/ui/views/HerokuApplicationManagerViewPart.java b/com.heroku.eclipse.ui/src/com/heroku/eclipse/ui/views/HerokuApplicationManagerViewPart.java index 19d1e1b..0ed40f1 100644 --- a/com.heroku.eclipse.ui/src/com/heroku/eclipse/ui/views/HerokuApplicationManagerViewPart.java +++ b/com.heroku.eclipse.ui/src/com/heroku/eclipse/ui/views/HerokuApplicationManagerViewPart.java @@ -1,1068 +1,1071 @@ package com.heroku.eclipse.ui.views; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.egit.ui.UIPreferences; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.TrayDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.IElementComparer; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; 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.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.IMemento; import org.eclipse.ui.IViewSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.browser.IWebBrowser; import org.eclipse.ui.browser.IWorkbenchBrowserSupport; import org.eclipse.ui.console.ConsolePlugin; import org.eclipse.ui.console.MessageConsole; import org.eclipse.ui.console.MessageConsoleStream; import org.eclipse.ui.part.ViewPart; import org.osgi.framework.ServiceRegistration; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import org.osgi.service.log.LogService; import com.heroku.api.App; import com.heroku.eclipse.core.services.HerokuProperties; import com.heroku.eclipse.core.services.HerokuServices; import com.heroku.eclipse.core.services.HerokuServices.APP_FIELDS; import com.heroku.eclipse.core.services.HerokuServices.IMPORT_TYPES; import com.heroku.eclipse.core.services.exceptions.HerokuServiceException; import com.heroku.eclipse.core.services.model.HerokuProc; import com.heroku.eclipse.ui.Activator; import com.heroku.eclipse.ui.git.HerokuCredentialsProvider; import com.heroku.eclipse.ui.messages.Messages; import com.heroku.eclipse.ui.utils.AppComparator; import com.heroku.eclipse.ui.utils.HerokuUtils; import com.heroku.eclipse.ui.utils.IconKeys; import com.heroku.eclipse.ui.utils.LabelProviderFactory; import com.heroku.eclipse.ui.utils.RunnableWithReturn; import com.heroku.eclipse.ui.utils.ViewerOperations; import com.heroku.eclipse.ui.views.dialog.WebsiteOpener; /** * The main view of the Heroclipse plugin * * @author [email protected] */ public class HerokuApplicationManagerViewPart extends ViewPart implements WebsiteOpener { /** * The ID of the view as specified by the extension. */ public static final String ID = "com.heroku.eclipse.ui.views.HerokuApplicationManager"; //$NON-NLS-1$ private TreeViewer viewer; private static HerokuServices herokuService; private List<ServiceRegistration<EventHandler>> handlerRegistrations; private Map<String, List<HerokuProc>> appProcesses = Collections.synchronizedMap(new HashMap<String, List<HerokuProc>>()); private Map<String, String> procApps = Collections.synchronizedMap(new HashMap<String, String>()); private Map<String, Thread> logThreads = new HashMap<String, Thread>(); private Timer refreshTimer = new Timer(true); private TimerTask refreshTask; private TreeViewerColumn urlColumn; private TreeViewerColumn gitColumn; private TreeViewerColumn nameColumn; private Action refreshAction; @Override public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); herokuService = Activator.getDefault().getService(); } public void createPartControl(Composite parent) { viewer = new TreeViewer(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); viewer.setContentProvider(new ContentProviderImpl()); viewer.getTree().setHeaderVisible(true); viewer.getTree().setLinesVisible(true); viewer.setComparer(new ElementComparerImpl()); viewer.setComparator(new AppComparator()); { nameColumn = new TreeViewerColumn(viewer, SWT.NONE); nameColumn.setLabelProvider(LabelProviderFactory.createName(herokuService, new RunnableWithReturn<List<HerokuProc>, App>() { @Override public List<HerokuProc> run(App argument) { return appProcesses.get(argument.getId()); } })); TreeColumn col = nameColumn.getColumn(); col.setText(Messages.getString("HerokuAppManagerViewPart_Name")); //$NON-NLS-1$ col.setWidth(200); col.addSelectionListener(getSelectionAdapter(col)); col.setData(AppComparator.SORT_IDENTIFIER, APP_FIELDS.APP_NAME); } { gitColumn = new TreeViewerColumn(viewer, SWT.NONE); gitColumn.setLabelProvider(LabelProviderFactory.createApp_GitUrl()); TreeColumn col = gitColumn.getColumn(); col.setText(Messages.getString("HerokuAppManagerViewPart_GitUrl")); //$NON-NLS-1$ col.setWidth(200); col.setData(AppComparator.SORT_IDENTIFIER, APP_FIELDS.APP_GIT_URL); col.addSelectionListener(getSelectionAdapter(col)); } { urlColumn = new TreeViewerColumn(viewer, SWT.NONE); urlColumn.setLabelProvider(LabelProviderFactory.createApp_Url()); TreeColumn col = urlColumn.getColumn(); col.setText(Messages.getString("HerokuAppManagerViewPart_AppUrl")); //$NON-NLS-1$ col.setWidth(200); col.setData(AppComparator.SORT_IDENTIFIER, APP_FIELDS.APP_WEB_URL); col.addSelectionListener(getSelectionAdapter(col)); } { MenuManager mgr = createContextMenu(); Menu menu = mgr.createContextMenu(parent); viewer.getControl().setMenu(menu); } viewer.addOpenListener(new IOpenListener() { @Override public void open(OpenEvent event) { try { App app = getSelectedAppOrProcApp(); if (app != null) { openEditor(app); } } catch (HerokuServiceException e1) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to display app info", e1); //$NON-NLS-1$ HerokuUtils.herokuError(getShell(), e1); } } }); // sorting by name per default viewer.getTree().setSortColumn(nameColumn.getColumn()); viewer.getTree().setSortDirection(SWT.UP); viewer.refresh(); createToolbar(); // register our action to global refresher getViewSite().getActionBars().setGlobalActionHandler(ActionFactory.REFRESH.getId(), refreshAction); refreshApplications(new NullProgressMonitor(), false); subscribeToEvents(); } private void createToolbar() { refreshAction = new Action(null, IconKeys.getImageDescriptor(IconKeys.ICON_APPSLIST_REFRESH)) { public void run() { refreshApplications(new NullProgressMonitor(), true); } }; refreshAction.setToolTipText(Messages.getString("HerokuAppManagerViewPart_Refresh_Tooltip")); //$NON-NLS-1$ refreshAction.setEnabled(true); // Create the local tool bar IToolBarManager tbm = getViewSite().getActionBars().getToolBarManager(); tbm.add(new Separator(Activator.PLUGIN_ID)); tbm.appendToGroup(Activator.PLUGIN_ID, refreshAction); tbm.update(false); } private void openEditor(App app) { try { getSite().getWorkbenchWindow().getActivePage().openEditor(new ApplicationEditorInput(app), ApplicationInfoEditor.ID, true); } catch (PartInitException e) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to open editor for app " + app.getName(), e); //$NON-NLS-1$ HerokuUtils.internalError(getShell(), e); } } private SelectionAdapter getSelectionAdapter(final TreeColumn column) { SelectionAdapter selectionAdapter = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { int dir = viewer.getTree().getSortDirection(); if (viewer.getTree().getSortColumn() == column) { dir = dir == SWT.UP ? SWT.DOWN : SWT.UP; } else { dir = SWT.DOWN; } viewer.getTree().setSortColumn(column); viewer.getTree().setSortDirection(dir); viewer.refresh(); } }; return selectionAdapter; } private void scheduleRefresh() { refreshTask = new TimerTask() { @Override public void run() { refreshApplications(new NullProgressMonitor(), true); } }; refreshTimer.schedule(refreshTask, Integer.parseInt(HerokuProperties.getString("heroku.eclipse.appsList.refreshInterval"))); //$NON-NLS-1$ } App getSelectedApp() { IStructuredSelection s = (IStructuredSelection) viewer.getSelection(); return !s.isEmpty() && s.getFirstElement() instanceof App ? (App) s.getFirstElement() : null; } HerokuProc getSelectedProc() { IStructuredSelection s = (IStructuredSelection) viewer.getSelection(); return !s.isEmpty() && s.getFirstElement() instanceof HerokuProc ? (HerokuProc) s.getFirstElement() : null; } App getSelectedAppOrProcApp() throws HerokuServiceException { App app = getSelectedApp(); if (app == null) { HerokuProc proc = getSelectedProc(); if (proc != null) { app = herokuService.getApp(new NullProgressMonitor(), proc.getHerokuProc().getAppName()); } } return app; } Shell getShell() { return getSite().getWorkbenchWindow().getShell(); } private MenuManager createContextMenu() { Action refresh = new Action(Messages.getString("HerokuAppManagerViewPart_Refresh")) { //$NON-NLS-1$ @Override public void run() { refreshApplications(new NullProgressMonitor(), true); } }; final Action appInfo = new Action( Messages.getString("HerokuAppManagerViewPart_AppInfoShort"), IconKeys.getImageDescriptor(IconKeys.ICON_APPINFO_EDITOR_ICON)) { //$NON-NLS-1$ @Override public void run() { try { App app = getSelectedAppOrProcApp(); if (app != null) { openEditor(app); } } catch (HerokuServiceException e) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to display app info", e); //$NON-NLS-1$ HerokuUtils.internalError(getShell(), e); } } }; final Action importApp = new Action(Messages.getString("HerokuAppManagerViewPart_Import")) { //$NON-NLS-1$ @Override public void run() { App app = getSelectedApp(); if (app != null) { if (MessageDialog .openQuestion( getShell(), Messages.getString("HerokuAppManagerViewPart_Import"), Messages.getFormattedString("HerokuAppManagerViewPart_Question_Import", app.getName()))) { //$NON-NLS-1$ //$NON-NLS-2$ try { importApp(app); } catch (HerokuServiceException e) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to import app " + app.getName(), e); //$NON-NLS-1$ HerokuUtils.internalError(getShell(), e); } } } } }; final Action open = new Action(Messages.getString("HerokuAppManagerViewPart_Open")) { //$NON-NLS-1$ @Override public void run() { App app = getSelectedApp(); if (app != null) { openInternal(app); } } }; final Action restart = new Action(Messages.getString("HerokuAppManagerViewPart_Restart")) { //$NON-NLS-1$ @Override public void run() { final App app = getSelectedApp(); if (app != null) { if (MessageDialog .openQuestion( getShell(), Messages.getString("HerokuAppManagerViewPart_Restart"), Messages.getFormattedString("HerokuAppManagerViewPart_Question_Restart", app.getName()))) { //$NON-NLS-1$ //$NON-NLS-2$ try { PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(Messages.getFormattedString("HerokuAppManagerViewPart_Progress_RestartingApp", app.getName()), 2); //$NON-NLS-1$ monitor.worked(1); try { herokuService.restartApplication(monitor, app); monitor.worked(1); monitor.done(); } catch (HerokuServiceException e) { // rethrow to outer space throw new InvocationTargetException(e); } } }); refreshApplications(new NullProgressMonitor(), true); } catch (InvocationTargetException e) { HerokuServiceException se = extractHerokuException(e, "unknown error when trying to restart app " + app.getName()); //$NON-NLS-1$ if (se != null) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to restart app " + app.getName(), e); //$NON-NLS-1$ HerokuUtils.herokuError(getShell(), e); } } catch (InterruptedException e) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to restart app " + app.getName(), e); //$NON-NLS-1$ HerokuUtils.internalError(getShell(), e); } } } else { final HerokuProc proc = getSelectedProc(); if (proc != null) { if (MessageDialog .openQuestion( getShell(), Messages.getString("HerokuAppManagerViewPart_Restart"), Messages.getFormattedString("HerokuAppManagerViewPart_Question_RestartProc", proc.getDynoName()))) { //$NON-NLS-1$ //$NON-NLS-2$ try { PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask( Messages.getFormattedString("HerokuAppManagerViewPart_Progress_RestartingProc", proc.getDynoName()), 2); //$NON-NLS-1$ monitor.worked(1); try { herokuService.restartDyno(monitor, proc); monitor.worked(1); monitor.done(); } catch (HerokuServiceException e) { // rethrow to outer space throw new InvocationTargetException(e); } } }); refreshApplications(new NullProgressMonitor(), true); } catch (InvocationTargetException e) { HerokuServiceException se = extractHerokuException(e, "unknown error when trying to restart all '" + proc.getDynoName() + "' processes"); //$NON-NLS-1$ //$NON-NLS-2$ if (se != null) { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to restart all '" + proc.getDynoName() + "' processes", e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.herokuError(getShell(), e); } } catch (InterruptedException e) { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to restart all '" + proc.getDynoName() + "' processes", e); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); HerokuUtils.internalError(getShell(), e); } } } } } }; final Action viewLogs = new Action(Messages.getString("HerokuAppManagerViewPart_ViewLogs")) { //$NON-NLS-1$ @Override public void run() { final App app = getSelectedApp(); if (app != null) { openLog(app.getId(), app.getName(), null); } else { // opening log for the entire process group HerokuProc proc = getSelectedProc(); openLog(proc.getUniqueId(), proc.getHerokuProc().getAppName(), proc.getDynoName()); } } }; final Action scale = new Action(Messages.getString("HerokuAppManagerViewPart_Scale")) { //$NON-NLS-1$ @Override public void run() { TrayDialog d = new TrayDialog(getShell()) { private Text processField; private Spinner quantityField; private String appName; @Override protected Control createDialogArea(Composite parent) { int quantity = 0; String dynoName = ""; //$NON-NLS-1$ App app = getSelectedApp(); if (app != null) { List<HerokuProc> procs = appProcesses.get(app.getId()); appName = app.getName(); // if the app has only one process type, prepopulate for (HerokuProc herokuProc : procs) { if (dynoName.equals("")) { //$NON-NLS-1$ dynoName = herokuProc.getDynoName(); quantity++; } else if (!herokuProc.getDynoName().equals(dynoName)) { dynoName = ""; //$NON-NLS-1$ quantity = 0; break; } + else { + quantity++; + } } } else { HerokuProc proc = getSelectedProc(); dynoName = proc.getDynoName(); quantity = findDynoProcs(proc).size(); appName = proc.getHerokuProc().getAppName(); } Composite container = (Composite) super.createDialogArea(parent); getShell().setText(Messages.getString("HerokuAppManagerViewPart_Scale_Title")); //$NON-NLS-1$ Composite area = new Composite(container, SWT.NONE); area.setLayout(new GridLayout(2, false)); area.setLayoutData(new GridData(GridData.FILL_BOTH)); { Label l = new Label(area, SWT.NONE); l.setText(Messages.getString("HerokuAppManagerViewPart_Scale_Process")); //$NON-NLS-1$ processField = new Text(area, SWT.BORDER); processField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); processField.setText(dynoName); } { Label l = new Label(area, SWT.NONE); l.setText(Messages.getString("HerokuAppManagerViewPart_Scale_ScaleTo")); //$NON-NLS-1$ quantityField = new Spinner(area, SWT.BORDER); quantityField.setMinimum(0); quantityField.setMaximum(Integer.parseInt(HerokuProperties.getString("heroku.eclipse.dynos.maxQuantity"))); //$NON-NLS-1$ quantityField.setSelection(quantity); quantityField.setIncrement(1); quantityField.pack(); } return container; } @Override protected void okPressed() { final String process = processField.getText().trim(); final String quantity = quantityField.getText(); if (HerokuUtils.isNotEmpty(process)) { try { PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(Messages.getFormattedString("HerokuAppManagerViewPart_Progress_Scaling", process), 3); //$NON-NLS-1$ monitor.worked(1); try { herokuService.scaleProcess(monitor, appName, process, Integer.parseInt(quantity)); monitor.worked(1); refreshApplications(monitor, true); monitor.done(); } catch (HerokuServiceException e) { // rethrow to outer space throw new InvocationTargetException(e); } } }); super.okPressed(); } catch (InvocationTargetException e) { if ((e.getCause() instanceof HerokuServiceException)) { HerokuServiceException e1 = (HerokuServiceException) e.getCause(); if (e1.getErrorCode() == HerokuServiceException.NOT_ACCEPTABLE) { HerokuUtils .userError( getShell(), Messages.getString("HerokuAppManagerViewPart_Scale_Error_BuyCredits_Title"), Messages.getString("HerokuAppManagerViewPart_Scale_Error_BuyCredits")); //$NON-NLS-1$ //$NON-NLS-2$ } else if (e1.getErrorCode() == HerokuServiceException.NOT_FOUND) { HerokuUtils .userError( getShell(), Messages.getString("HerokuAppManagerViewPart_Scale_Error_UnknownDyno_Title"), Messages.getFormattedString("HerokuAppManagerViewPart_Scale_Error_UnknownDyno", process)); //$NON-NLS-1$ //$NON-NLS-2$ } else { HerokuUtils.herokuError(getShell(), e); } } else { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to scale process " + process + " for app " + appName, e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.internalError(getShell(), e); } } catch (InterruptedException e) { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to scale process " + process + " for app " + appName, e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.internalError(getShell(), e); } } else { HerokuUtils .userError( getShell(), Messages.getString("HerokuAppManagerViewPart_Scale_Error_MissingInput_Title"), Messages.getString("HerokuAppManagerViewPart_Scale_Error_MissingInput")); //$NON-NLS-1$ //$NON-NLS-2$ processField.setFocus(); } } }; d.open(); } }; final Action destroy = new Action(Messages.getString("HerokuAppManagerViewPart_Destroy")) { //$NON-NLS-1$ @Override public void run() { App app = getSelectedApp(); if (app != null) { if (MessageDialog .openQuestion( getShell(), Messages.getString("HerokuAppManagerViewPart_Destroy"), Messages.getFormattedString("HerokuAppManagerViewPart_Question_Destroy", app.getName()))) { //$NON-NLS-1$ //$NON-NLS-2$ try { herokuService.destroyApplication(new NullProgressMonitor(), app); } catch (HerokuServiceException e) { if (e.getErrorCode() == HerokuServiceException.NOT_ALLOWED) { HerokuUtils .userError( getShell(), Messages.getString("HerokuAppManagerViewPart_Error_DestroyOwner_Title"), Messages.getFormattedString("HerokuAppManagerViewPart_Error_DestroyOwner", app.getName(), app.getOwnerEmail())); //$NON-NLS-1$ //$NON-NLS-2$ } else { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to destroy app " + app.getName(), e); //$NON-NLS-1$ HerokuUtils.herokuError(getShell(), e); } } } } } }; MenuManager mgr = new MenuManager(); mgr.add(refresh); mgr.add(new Separator()); mgr.add(appInfo); mgr.add(importApp); mgr.add(open); mgr.add(restart); mgr.add(viewLogs); mgr.add(scale); mgr.add(destroy); mgr.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { NullProgressMonitor pm = new NullProgressMonitor(); IStructuredSelection s = (IStructuredSelection) viewer.getSelection(); boolean enabled = !s.isEmpty(); importApp.setEnabled(enabled); open.setEnabled(enabled); restart.setEnabled(enabled); viewLogs.setEnabled(enabled); // owner restricted actions scale.setEnabled(false); destroy.setEnabled(false); if (enabled) { if (s.getFirstElement() instanceof App) { App app = (App) s.getFirstElement(); try { if (herokuService.isOwnApp(pm, app)) { scale.setEnabled(true); destroy.setEnabled(true); } } catch (HerokuServiceException e) { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to determine if app " + app.getName() + " is owned by myself", e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.herokuError(getShell(), e); } } else if (s.getFirstElement() instanceof HerokuProc) { HerokuProc proc = (HerokuProc) s.getFirstElement(); importApp.setEnabled(false); open.setEnabled(false); try { App app = herokuService.getApp(pm, proc.getHerokuProc().getAppName()); if (herokuService.isOwnApp(pm, app)) { scale.setEnabled(true); } } catch (HerokuServiceException e) { Activator .getDefault() .getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to determine if app " + proc.getHerokuProc().getAppName() + " is owned by myself", e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.herokuError(getShell(), e); } } } } }); return mgr; } private void openLog(final String uniqueId, final String appName, final String procName) { String consoleName = ""; //$NON-NLS-1$ String streamName = "logstream-"; //$NON-NLS-1$ if (procName == null) { consoleName = Messages.getFormattedString("HerokuAppManagerViewPart_AppConsole_Title", appName); //$NON-NLS-1$ streamName += "app-" + uniqueId; //$NON-NLS-1$ } else { consoleName += Messages.getFormattedString("HerokuAppManagerViewPart_ProcConsole_Title", appName, procName); //$NON-NLS-1$ streamName += "proc-" + uniqueId; //$NON-NLS-1$ } MessageConsole console = HerokuUtils.findConsole(consoleName); ConsolePlugin.getDefault().getConsoleManager().showConsoleView(console); console.activate(); // only open new log stream if we have not opened it before if (!logThreads.containsKey(streamName)) { final MessageConsoleStream out = console.newMessageStream(); Thread t = new Thread(streamName) { AtomicBoolean wantsFun = new AtomicBoolean(true); @Override public void run() { while (wantsFun.get()) { byte[] buffer = new byte[1024]; int bytesRead; try { InputStream is; if (procName == null) { is = herokuService.getApplicationLogStream(new NullProgressMonitor(), appName); } else { is = herokuService.getProcessLogStream(new NullProgressMonitor(), appName, procName); } while ((bytesRead = is.read(buffer)) != -1) { if (out.isClosed()) { break; } out.write(buffer, 0, bytesRead); } } catch (IOException e) { HerokuUtils.internalError(getShell(), e); } catch (HerokuServiceException e) { HerokuUtils.herokuError(getShell(), e); } } } @Override public void interrupt() { wantsFun.set(false); try { out.close(); } catch (IOException e) { e.printStackTrace(); } super.interrupt(); } }; t.setDaemon(true); t.start(); logThreads.put(streamName, t); } } @Override public void openInternal(App application) { try { IWorkbenchBrowserSupport wbb = getSite().getWorkbenchWindow().getWorkbench().getBrowserSupport(); IWebBrowser browser = wbb.createBrowser(IWorkbenchBrowserSupport.AS_EDITOR, application.getName(), application.getName(), Messages.getFormattedString("HerokuAppManagerViewPart_HerokuApp", //$NON-NLS-1$ application.getName())); browser.openURL(new URL(application.getWebUrl())); } catch (PartInitException e) { HerokuUtils.internalError(getShell(), e); } catch (MalformedURLException e) { HerokuUtils.internalError(getShell(), e); } } private void subscribeToEvents() { EventHandler sessionInvalidationHandler = new EventHandler() { @Override public void handleEvent(Event event) { refreshApplications(new NullProgressMonitor(), true); } }; EventHandler newApplicationHandler = new EventHandler() { @Override public void handleEvent(Event event) { refreshApplications(new NullProgressMonitor(), true); } }; EventHandler renameApplicationHandler = new EventHandler() { @Override public void handleEvent(Event event) { refreshApplications(new NullProgressMonitor(), true); } }; EventHandler transferApplicationHandler = new EventHandler() { @Override public void handleEvent(Event event) { refreshApplications(new NullProgressMonitor(), true); } }; EventHandler destroyedApplicationHandler = new EventHandler() { @Override public void handleEvent(Event event) { refreshApplications(new NullProgressMonitor(), true); } }; handlerRegistrations = new ArrayList<ServiceRegistration<EventHandler>>(); handlerRegistrations.add(Activator.getDefault().registerEvenHandler(sessionInvalidationHandler, HerokuServices.TOPIC_SESSION_INVALID)); handlerRegistrations.add(Activator.getDefault().registerEvenHandler(newApplicationHandler, HerokuServices.TOPIC_APPLICATION_NEW)); handlerRegistrations.add(Activator.getDefault().registerEvenHandler(renameApplicationHandler, HerokuServices.TOPIC_APPLICATION_RENAMED)); handlerRegistrations.add(Activator.getDefault().registerEvenHandler(transferApplicationHandler, HerokuServices.TOPIC_APPLICATION_TRANSFERED)); handlerRegistrations.add(Activator.getDefault().registerEvenHandler(destroyedApplicationHandler, HerokuServices.TOPIC_APPLICATION_DESTROYED)); } private void refreshApplications(final IProgressMonitor pm, final boolean refreshProcs) { try { if (herokuService.isReady(pm)) { final Job o = new Job(Messages.getString("HerokuAppManagerViewPart_RefreshApps")) { //$NON-NLS-1$ @Override protected IStatus run(IProgressMonitor monitor) { try { if (saveRefreshApplications(pm, refreshProcs)) { // 2nd run: refresh procs now as well saveRefreshApplications(pm, true); } } catch (HerokuServiceException e) { if (Display.getCurrent() != null) { HerokuUtils.herokuError(Display.getCurrent().getActiveShell(), e); } else { e.printStackTrace(); } return Status.CANCEL_STATUS; } catch (Throwable e) { if (Display.getCurrent() != null) { HerokuUtils.internalError(Display.getCurrent().getActiveShell(), e); } else { e.printStackTrace(); } return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; o.schedule(); } } catch (HerokuServiceException e) { HerokuUtils.herokuError(getShell(), e); } } private boolean saveRefreshApplications(IProgressMonitor pm, boolean refreshProcs) throws HerokuServiceException { boolean rv = true; appProcesses.clear(); procApps.clear(); if (herokuService.isReady(pm)) { List<App> applications = herokuService.listApps(pm); if (refreshProcs) { // || applications.size() < 10) { for (App a : applications) { List<HerokuProc> procs = herokuService.listProcesses(pm, a); appProcesses.put(a.getId(), procs); if (procs.size() > 0) { if (!procApps.containsKey(procs.get(0).getUniqueId())) { procApps.put(procs.get(0).getUniqueId(), a.getId()); } } } rv = false; } HerokuUtils.runOnDisplay(true, viewer, applications, ViewerOperations.input(viewer)); } else { HerokuUtils.runOnDisplay(true, viewer, new Object[0], ViewerOperations.input(viewer)); } if (refreshTask != null) { refreshTask.cancel(); } return rv; // scheduleRefresh(); } public void setFocus() { viewer.getControl().setFocus(); } @Override public void dispose() { appProcesses.clear(); procApps.clear(); refreshTimer.cancel(); if (logThreads != null) { for (Thread t : logThreads.values()) { t.interrupt(); } logThreads.clear(); } if (handlerRegistrations != null) { for (ServiceRegistration<EventHandler> r : handlerRegistrations) { r.unregister(); } } super.dispose(); } class ContentProviderImpl implements ITreeContentProvider { @Override public void dispose() { } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } @Override public Object[] getElements(Object inputElement) { return ((List<?>) inputElement).toArray(); } @Override public Object[] getChildren(Object parentElement) { if (parentElement instanceof App) { List<HerokuProc> l = appProcesses.get(((App) parentElement).getId()); if (l != null) { return l.toArray(); } } return new Object[0]; } @Override public Object getParent(Object element) { // TODO We could implement this but it is not required return null; } @Override public boolean hasChildren(Object element) { return getChildren(element).length > 0; } } static class ElementComparerImpl implements IElementComparer { @Override public boolean equals(Object a, Object b) { if (a instanceof HerokuProc && b instanceof HerokuProc) { return hashCode(a) == hashCode(b); } else if (a instanceof App && b instanceof App) { return hashCode(a) == hashCode(b); } return a.equals(b); } @Override public int hashCode(Object element) { if (element instanceof App) { return ((App) element).getId().hashCode(); } else if (element instanceof HerokuProc) { return ((HerokuProc) element).getUniqueId().hashCode(); } return element.hashCode(); } } private void importApp(final App app) throws HerokuServiceException { if (app != null) { final String destinationDir = org.eclipse.egit.ui.Activator.getDefault().getPreferenceStore().getString(UIPreferences.DEFAULT_REPO_DIR); final int timeout = org.eclipse.egit.ui.Activator.getDefault().getPreferenceStore().getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT); final HerokuCredentialsProvider cred = new HerokuCredentialsProvider(HerokuProperties.getString("heroku.eclipse.git.defaultUser"), ""); //$NON-NLS-1$ //$NON-NLS-2$ try { herokuService.materializeGitApp(new NullProgressMonitor(), app, IMPORT_TYPES.AUTODETECT, null, destinationDir, timeout, Messages.getFormattedString("HerokuAppCreate_CreatingApp", app.getName()), cred); //$NON-NLS-1$ } catch (HerokuServiceException e) { if (e.getErrorCode() == HerokuServiceException.INVALID_LOCAL_GIT_LOCATION) { HerokuUtils .userError( getShell(), Messages.getString("HerokuAppCreateNamePage_Error_GitLocationInvalid_Title"), Messages.getFormattedString("HerokuAppCreateNamePage_Error_GitLocationInvalid", destinationDir + System.getProperty("file.separator") + app.getName())); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ } else { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "internal error during git checkout, aborting ...", e); //$NON-NLS-1$ HerokuUtils.internalError(getShell(), e); } } } } private List<HerokuProc> findDynoProcs(HerokuProc proc) { // create process list for the given dyno List<HerokuProc> allProcs = appProcesses.get(procApps.get(proc.getUniqueId())); final String dynoName = proc.getDynoName(); final List<HerokuProc> dynoProcs = new ArrayList<HerokuProc>(); for (HerokuProc herokuProc : allProcs) { if (herokuProc.getDynoName().equals(dynoName)) { dynoProcs.add(herokuProc); } } return dynoProcs; } private HerokuServiceException extractHerokuException(Exception e, String defaultError) { Exception rv = e; if (e instanceof InvocationTargetException) { rv = (Exception) e.getCause(); } if (rv instanceof HerokuServiceException) { // "Operation cancelled" means that the user pressed "cancel", so we // ignore that in terms of the thrown exception and return null if (((HerokuServiceException) rv).getErrorCode() != HerokuServiceException.OPERATION_CANCELLED) { return (HerokuServiceException) rv; } } else { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, defaultError, e); HerokuUtils.internalError(getShell(), e); } return null; } }
true
true
private MenuManager createContextMenu() { Action refresh = new Action(Messages.getString("HerokuAppManagerViewPart_Refresh")) { //$NON-NLS-1$ @Override public void run() { refreshApplications(new NullProgressMonitor(), true); } }; final Action appInfo = new Action( Messages.getString("HerokuAppManagerViewPart_AppInfoShort"), IconKeys.getImageDescriptor(IconKeys.ICON_APPINFO_EDITOR_ICON)) { //$NON-NLS-1$ @Override public void run() { try { App app = getSelectedAppOrProcApp(); if (app != null) { openEditor(app); } } catch (HerokuServiceException e) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to display app info", e); //$NON-NLS-1$ HerokuUtils.internalError(getShell(), e); } } }; final Action importApp = new Action(Messages.getString("HerokuAppManagerViewPart_Import")) { //$NON-NLS-1$ @Override public void run() { App app = getSelectedApp(); if (app != null) { if (MessageDialog .openQuestion( getShell(), Messages.getString("HerokuAppManagerViewPart_Import"), Messages.getFormattedString("HerokuAppManagerViewPart_Question_Import", app.getName()))) { //$NON-NLS-1$ //$NON-NLS-2$ try { importApp(app); } catch (HerokuServiceException e) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to import app " + app.getName(), e); //$NON-NLS-1$ HerokuUtils.internalError(getShell(), e); } } } } }; final Action open = new Action(Messages.getString("HerokuAppManagerViewPart_Open")) { //$NON-NLS-1$ @Override public void run() { App app = getSelectedApp(); if (app != null) { openInternal(app); } } }; final Action restart = new Action(Messages.getString("HerokuAppManagerViewPart_Restart")) { //$NON-NLS-1$ @Override public void run() { final App app = getSelectedApp(); if (app != null) { if (MessageDialog .openQuestion( getShell(), Messages.getString("HerokuAppManagerViewPart_Restart"), Messages.getFormattedString("HerokuAppManagerViewPart_Question_Restart", app.getName()))) { //$NON-NLS-1$ //$NON-NLS-2$ try { PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(Messages.getFormattedString("HerokuAppManagerViewPart_Progress_RestartingApp", app.getName()), 2); //$NON-NLS-1$ monitor.worked(1); try { herokuService.restartApplication(monitor, app); monitor.worked(1); monitor.done(); } catch (HerokuServiceException e) { // rethrow to outer space throw new InvocationTargetException(e); } } }); refreshApplications(new NullProgressMonitor(), true); } catch (InvocationTargetException e) { HerokuServiceException se = extractHerokuException(e, "unknown error when trying to restart app " + app.getName()); //$NON-NLS-1$ if (se != null) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to restart app " + app.getName(), e); //$NON-NLS-1$ HerokuUtils.herokuError(getShell(), e); } } catch (InterruptedException e) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to restart app " + app.getName(), e); //$NON-NLS-1$ HerokuUtils.internalError(getShell(), e); } } } else { final HerokuProc proc = getSelectedProc(); if (proc != null) { if (MessageDialog .openQuestion( getShell(), Messages.getString("HerokuAppManagerViewPart_Restart"), Messages.getFormattedString("HerokuAppManagerViewPart_Question_RestartProc", proc.getDynoName()))) { //$NON-NLS-1$ //$NON-NLS-2$ try { PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask( Messages.getFormattedString("HerokuAppManagerViewPart_Progress_RestartingProc", proc.getDynoName()), 2); //$NON-NLS-1$ monitor.worked(1); try { herokuService.restartDyno(monitor, proc); monitor.worked(1); monitor.done(); } catch (HerokuServiceException e) { // rethrow to outer space throw new InvocationTargetException(e); } } }); refreshApplications(new NullProgressMonitor(), true); } catch (InvocationTargetException e) { HerokuServiceException se = extractHerokuException(e, "unknown error when trying to restart all '" + proc.getDynoName() + "' processes"); //$NON-NLS-1$ //$NON-NLS-2$ if (se != null) { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to restart all '" + proc.getDynoName() + "' processes", e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.herokuError(getShell(), e); } } catch (InterruptedException e) { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to restart all '" + proc.getDynoName() + "' processes", e); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); HerokuUtils.internalError(getShell(), e); } } } } } }; final Action viewLogs = new Action(Messages.getString("HerokuAppManagerViewPart_ViewLogs")) { //$NON-NLS-1$ @Override public void run() { final App app = getSelectedApp(); if (app != null) { openLog(app.getId(), app.getName(), null); } else { // opening log for the entire process group HerokuProc proc = getSelectedProc(); openLog(proc.getUniqueId(), proc.getHerokuProc().getAppName(), proc.getDynoName()); } } }; final Action scale = new Action(Messages.getString("HerokuAppManagerViewPart_Scale")) { //$NON-NLS-1$ @Override public void run() { TrayDialog d = new TrayDialog(getShell()) { private Text processField; private Spinner quantityField; private String appName; @Override protected Control createDialogArea(Composite parent) { int quantity = 0; String dynoName = ""; //$NON-NLS-1$ App app = getSelectedApp(); if (app != null) { List<HerokuProc> procs = appProcesses.get(app.getId()); appName = app.getName(); // if the app has only one process type, prepopulate for (HerokuProc herokuProc : procs) { if (dynoName.equals("")) { //$NON-NLS-1$ dynoName = herokuProc.getDynoName(); quantity++; } else if (!herokuProc.getDynoName().equals(dynoName)) { dynoName = ""; //$NON-NLS-1$ quantity = 0; break; } } } else { HerokuProc proc = getSelectedProc(); dynoName = proc.getDynoName(); quantity = findDynoProcs(proc).size(); appName = proc.getHerokuProc().getAppName(); } Composite container = (Composite) super.createDialogArea(parent); getShell().setText(Messages.getString("HerokuAppManagerViewPart_Scale_Title")); //$NON-NLS-1$ Composite area = new Composite(container, SWT.NONE); area.setLayout(new GridLayout(2, false)); area.setLayoutData(new GridData(GridData.FILL_BOTH)); { Label l = new Label(area, SWT.NONE); l.setText(Messages.getString("HerokuAppManagerViewPart_Scale_Process")); //$NON-NLS-1$ processField = new Text(area, SWT.BORDER); processField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); processField.setText(dynoName); } { Label l = new Label(area, SWT.NONE); l.setText(Messages.getString("HerokuAppManagerViewPart_Scale_ScaleTo")); //$NON-NLS-1$ quantityField = new Spinner(area, SWT.BORDER); quantityField.setMinimum(0); quantityField.setMaximum(Integer.parseInt(HerokuProperties.getString("heroku.eclipse.dynos.maxQuantity"))); //$NON-NLS-1$ quantityField.setSelection(quantity); quantityField.setIncrement(1); quantityField.pack(); } return container; } @Override protected void okPressed() { final String process = processField.getText().trim(); final String quantity = quantityField.getText(); if (HerokuUtils.isNotEmpty(process)) { try { PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(Messages.getFormattedString("HerokuAppManagerViewPart_Progress_Scaling", process), 3); //$NON-NLS-1$ monitor.worked(1); try { herokuService.scaleProcess(monitor, appName, process, Integer.parseInt(quantity)); monitor.worked(1); refreshApplications(monitor, true); monitor.done(); } catch (HerokuServiceException e) { // rethrow to outer space throw new InvocationTargetException(e); } } }); super.okPressed(); } catch (InvocationTargetException e) { if ((e.getCause() instanceof HerokuServiceException)) { HerokuServiceException e1 = (HerokuServiceException) e.getCause(); if (e1.getErrorCode() == HerokuServiceException.NOT_ACCEPTABLE) { HerokuUtils .userError( getShell(), Messages.getString("HerokuAppManagerViewPart_Scale_Error_BuyCredits_Title"), Messages.getString("HerokuAppManagerViewPart_Scale_Error_BuyCredits")); //$NON-NLS-1$ //$NON-NLS-2$ } else if (e1.getErrorCode() == HerokuServiceException.NOT_FOUND) { HerokuUtils .userError( getShell(), Messages.getString("HerokuAppManagerViewPart_Scale_Error_UnknownDyno_Title"), Messages.getFormattedString("HerokuAppManagerViewPart_Scale_Error_UnknownDyno", process)); //$NON-NLS-1$ //$NON-NLS-2$ } else { HerokuUtils.herokuError(getShell(), e); } } else { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to scale process " + process + " for app " + appName, e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.internalError(getShell(), e); } } catch (InterruptedException e) { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to scale process " + process + " for app " + appName, e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.internalError(getShell(), e); } } else { HerokuUtils .userError( getShell(), Messages.getString("HerokuAppManagerViewPart_Scale_Error_MissingInput_Title"), Messages.getString("HerokuAppManagerViewPart_Scale_Error_MissingInput")); //$NON-NLS-1$ //$NON-NLS-2$ processField.setFocus(); } } }; d.open(); } }; final Action destroy = new Action(Messages.getString("HerokuAppManagerViewPart_Destroy")) { //$NON-NLS-1$ @Override public void run() { App app = getSelectedApp(); if (app != null) { if (MessageDialog .openQuestion( getShell(), Messages.getString("HerokuAppManagerViewPart_Destroy"), Messages.getFormattedString("HerokuAppManagerViewPart_Question_Destroy", app.getName()))) { //$NON-NLS-1$ //$NON-NLS-2$ try { herokuService.destroyApplication(new NullProgressMonitor(), app); } catch (HerokuServiceException e) { if (e.getErrorCode() == HerokuServiceException.NOT_ALLOWED) { HerokuUtils .userError( getShell(), Messages.getString("HerokuAppManagerViewPart_Error_DestroyOwner_Title"), Messages.getFormattedString("HerokuAppManagerViewPart_Error_DestroyOwner", app.getName(), app.getOwnerEmail())); //$NON-NLS-1$ //$NON-NLS-2$ } else { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to destroy app " + app.getName(), e); //$NON-NLS-1$ HerokuUtils.herokuError(getShell(), e); } } } } } }; MenuManager mgr = new MenuManager(); mgr.add(refresh); mgr.add(new Separator()); mgr.add(appInfo); mgr.add(importApp); mgr.add(open); mgr.add(restart); mgr.add(viewLogs); mgr.add(scale); mgr.add(destroy); mgr.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { NullProgressMonitor pm = new NullProgressMonitor(); IStructuredSelection s = (IStructuredSelection) viewer.getSelection(); boolean enabled = !s.isEmpty(); importApp.setEnabled(enabled); open.setEnabled(enabled); restart.setEnabled(enabled); viewLogs.setEnabled(enabled); // owner restricted actions scale.setEnabled(false); destroy.setEnabled(false); if (enabled) { if (s.getFirstElement() instanceof App) { App app = (App) s.getFirstElement(); try { if (herokuService.isOwnApp(pm, app)) { scale.setEnabled(true); destroy.setEnabled(true); } } catch (HerokuServiceException e) { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to determine if app " + app.getName() + " is owned by myself", e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.herokuError(getShell(), e); } } else if (s.getFirstElement() instanceof HerokuProc) { HerokuProc proc = (HerokuProc) s.getFirstElement(); importApp.setEnabled(false); open.setEnabled(false); try { App app = herokuService.getApp(pm, proc.getHerokuProc().getAppName()); if (herokuService.isOwnApp(pm, app)) { scale.setEnabled(true); } } catch (HerokuServiceException e) { Activator .getDefault() .getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to determine if app " + proc.getHerokuProc().getAppName() + " is owned by myself", e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.herokuError(getShell(), e); } } } } }); return mgr; }
private MenuManager createContextMenu() { Action refresh = new Action(Messages.getString("HerokuAppManagerViewPart_Refresh")) { //$NON-NLS-1$ @Override public void run() { refreshApplications(new NullProgressMonitor(), true); } }; final Action appInfo = new Action( Messages.getString("HerokuAppManagerViewPart_AppInfoShort"), IconKeys.getImageDescriptor(IconKeys.ICON_APPINFO_EDITOR_ICON)) { //$NON-NLS-1$ @Override public void run() { try { App app = getSelectedAppOrProcApp(); if (app != null) { openEditor(app); } } catch (HerokuServiceException e) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to display app info", e); //$NON-NLS-1$ HerokuUtils.internalError(getShell(), e); } } }; final Action importApp = new Action(Messages.getString("HerokuAppManagerViewPart_Import")) { //$NON-NLS-1$ @Override public void run() { App app = getSelectedApp(); if (app != null) { if (MessageDialog .openQuestion( getShell(), Messages.getString("HerokuAppManagerViewPart_Import"), Messages.getFormattedString("HerokuAppManagerViewPart_Question_Import", app.getName()))) { //$NON-NLS-1$ //$NON-NLS-2$ try { importApp(app); } catch (HerokuServiceException e) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to import app " + app.getName(), e); //$NON-NLS-1$ HerokuUtils.internalError(getShell(), e); } } } } }; final Action open = new Action(Messages.getString("HerokuAppManagerViewPart_Open")) { //$NON-NLS-1$ @Override public void run() { App app = getSelectedApp(); if (app != null) { openInternal(app); } } }; final Action restart = new Action(Messages.getString("HerokuAppManagerViewPart_Restart")) { //$NON-NLS-1$ @Override public void run() { final App app = getSelectedApp(); if (app != null) { if (MessageDialog .openQuestion( getShell(), Messages.getString("HerokuAppManagerViewPart_Restart"), Messages.getFormattedString("HerokuAppManagerViewPart_Question_Restart", app.getName()))) { //$NON-NLS-1$ //$NON-NLS-2$ try { PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(Messages.getFormattedString("HerokuAppManagerViewPart_Progress_RestartingApp", app.getName()), 2); //$NON-NLS-1$ monitor.worked(1); try { herokuService.restartApplication(monitor, app); monitor.worked(1); monitor.done(); } catch (HerokuServiceException e) { // rethrow to outer space throw new InvocationTargetException(e); } } }); refreshApplications(new NullProgressMonitor(), true); } catch (InvocationTargetException e) { HerokuServiceException se = extractHerokuException(e, "unknown error when trying to restart app " + app.getName()); //$NON-NLS-1$ if (se != null) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to restart app " + app.getName(), e); //$NON-NLS-1$ HerokuUtils.herokuError(getShell(), e); } } catch (InterruptedException e) { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to restart app " + app.getName(), e); //$NON-NLS-1$ HerokuUtils.internalError(getShell(), e); } } } else { final HerokuProc proc = getSelectedProc(); if (proc != null) { if (MessageDialog .openQuestion( getShell(), Messages.getString("HerokuAppManagerViewPart_Restart"), Messages.getFormattedString("HerokuAppManagerViewPart_Question_RestartProc", proc.getDynoName()))) { //$NON-NLS-1$ //$NON-NLS-2$ try { PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask( Messages.getFormattedString("HerokuAppManagerViewPart_Progress_RestartingProc", proc.getDynoName()), 2); //$NON-NLS-1$ monitor.worked(1); try { herokuService.restartDyno(monitor, proc); monitor.worked(1); monitor.done(); } catch (HerokuServiceException e) { // rethrow to outer space throw new InvocationTargetException(e); } } }); refreshApplications(new NullProgressMonitor(), true); } catch (InvocationTargetException e) { HerokuServiceException se = extractHerokuException(e, "unknown error when trying to restart all '" + proc.getDynoName() + "' processes"); //$NON-NLS-1$ //$NON-NLS-2$ if (se != null) { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to restart all '" + proc.getDynoName() + "' processes", e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.herokuError(getShell(), e); } } catch (InterruptedException e) { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to restart all '" + proc.getDynoName() + "' processes", e); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); HerokuUtils.internalError(getShell(), e); } } } } } }; final Action viewLogs = new Action(Messages.getString("HerokuAppManagerViewPart_ViewLogs")) { //$NON-NLS-1$ @Override public void run() { final App app = getSelectedApp(); if (app != null) { openLog(app.getId(), app.getName(), null); } else { // opening log for the entire process group HerokuProc proc = getSelectedProc(); openLog(proc.getUniqueId(), proc.getHerokuProc().getAppName(), proc.getDynoName()); } } }; final Action scale = new Action(Messages.getString("HerokuAppManagerViewPart_Scale")) { //$NON-NLS-1$ @Override public void run() { TrayDialog d = new TrayDialog(getShell()) { private Text processField; private Spinner quantityField; private String appName; @Override protected Control createDialogArea(Composite parent) { int quantity = 0; String dynoName = ""; //$NON-NLS-1$ App app = getSelectedApp(); if (app != null) { List<HerokuProc> procs = appProcesses.get(app.getId()); appName = app.getName(); // if the app has only one process type, prepopulate for (HerokuProc herokuProc : procs) { if (dynoName.equals("")) { //$NON-NLS-1$ dynoName = herokuProc.getDynoName(); quantity++; } else if (!herokuProc.getDynoName().equals(dynoName)) { dynoName = ""; //$NON-NLS-1$ quantity = 0; break; } else { quantity++; } } } else { HerokuProc proc = getSelectedProc(); dynoName = proc.getDynoName(); quantity = findDynoProcs(proc).size(); appName = proc.getHerokuProc().getAppName(); } Composite container = (Composite) super.createDialogArea(parent); getShell().setText(Messages.getString("HerokuAppManagerViewPart_Scale_Title")); //$NON-NLS-1$ Composite area = new Composite(container, SWT.NONE); area.setLayout(new GridLayout(2, false)); area.setLayoutData(new GridData(GridData.FILL_BOTH)); { Label l = new Label(area, SWT.NONE); l.setText(Messages.getString("HerokuAppManagerViewPart_Scale_Process")); //$NON-NLS-1$ processField = new Text(area, SWT.BORDER); processField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); processField.setText(dynoName); } { Label l = new Label(area, SWT.NONE); l.setText(Messages.getString("HerokuAppManagerViewPart_Scale_ScaleTo")); //$NON-NLS-1$ quantityField = new Spinner(area, SWT.BORDER); quantityField.setMinimum(0); quantityField.setMaximum(Integer.parseInt(HerokuProperties.getString("heroku.eclipse.dynos.maxQuantity"))); //$NON-NLS-1$ quantityField.setSelection(quantity); quantityField.setIncrement(1); quantityField.pack(); } return container; } @Override protected void okPressed() { final String process = processField.getText().trim(); final String quantity = quantityField.getText(); if (HerokuUtils.isNotEmpty(process)) { try { PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(Messages.getFormattedString("HerokuAppManagerViewPart_Progress_Scaling", process), 3); //$NON-NLS-1$ monitor.worked(1); try { herokuService.scaleProcess(monitor, appName, process, Integer.parseInt(quantity)); monitor.worked(1); refreshApplications(monitor, true); monitor.done(); } catch (HerokuServiceException e) { // rethrow to outer space throw new InvocationTargetException(e); } } }); super.okPressed(); } catch (InvocationTargetException e) { if ((e.getCause() instanceof HerokuServiceException)) { HerokuServiceException e1 = (HerokuServiceException) e.getCause(); if (e1.getErrorCode() == HerokuServiceException.NOT_ACCEPTABLE) { HerokuUtils .userError( getShell(), Messages.getString("HerokuAppManagerViewPart_Scale_Error_BuyCredits_Title"), Messages.getString("HerokuAppManagerViewPart_Scale_Error_BuyCredits")); //$NON-NLS-1$ //$NON-NLS-2$ } else if (e1.getErrorCode() == HerokuServiceException.NOT_FOUND) { HerokuUtils .userError( getShell(), Messages.getString("HerokuAppManagerViewPart_Scale_Error_UnknownDyno_Title"), Messages.getFormattedString("HerokuAppManagerViewPart_Scale_Error_UnknownDyno", process)); //$NON-NLS-1$ //$NON-NLS-2$ } else { HerokuUtils.herokuError(getShell(), e); } } else { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to scale process " + process + " for app " + appName, e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.internalError(getShell(), e); } } catch (InterruptedException e) { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to scale process " + process + " for app " + appName, e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.internalError(getShell(), e); } } else { HerokuUtils .userError( getShell(), Messages.getString("HerokuAppManagerViewPart_Scale_Error_MissingInput_Title"), Messages.getString("HerokuAppManagerViewPart_Scale_Error_MissingInput")); //$NON-NLS-1$ //$NON-NLS-2$ processField.setFocus(); } } }; d.open(); } }; final Action destroy = new Action(Messages.getString("HerokuAppManagerViewPart_Destroy")) { //$NON-NLS-1$ @Override public void run() { App app = getSelectedApp(); if (app != null) { if (MessageDialog .openQuestion( getShell(), Messages.getString("HerokuAppManagerViewPart_Destroy"), Messages.getFormattedString("HerokuAppManagerViewPart_Question_Destroy", app.getName()))) { //$NON-NLS-1$ //$NON-NLS-2$ try { herokuService.destroyApplication(new NullProgressMonitor(), app); } catch (HerokuServiceException e) { if (e.getErrorCode() == HerokuServiceException.NOT_ALLOWED) { HerokuUtils .userError( getShell(), Messages.getString("HerokuAppManagerViewPart_Error_DestroyOwner_Title"), Messages.getFormattedString("HerokuAppManagerViewPart_Error_DestroyOwner", app.getName(), app.getOwnerEmail())); //$NON-NLS-1$ //$NON-NLS-2$ } else { Activator.getDefault().getLogger().log(LogService.LOG_ERROR, "unknown error when trying to destroy app " + app.getName(), e); //$NON-NLS-1$ HerokuUtils.herokuError(getShell(), e); } } } } } }; MenuManager mgr = new MenuManager(); mgr.add(refresh); mgr.add(new Separator()); mgr.add(appInfo); mgr.add(importApp); mgr.add(open); mgr.add(restart); mgr.add(viewLogs); mgr.add(scale); mgr.add(destroy); mgr.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { NullProgressMonitor pm = new NullProgressMonitor(); IStructuredSelection s = (IStructuredSelection) viewer.getSelection(); boolean enabled = !s.isEmpty(); importApp.setEnabled(enabled); open.setEnabled(enabled); restart.setEnabled(enabled); viewLogs.setEnabled(enabled); // owner restricted actions scale.setEnabled(false); destroy.setEnabled(false); if (enabled) { if (s.getFirstElement() instanceof App) { App app = (App) s.getFirstElement(); try { if (herokuService.isOwnApp(pm, app)) { scale.setEnabled(true); destroy.setEnabled(true); } } catch (HerokuServiceException e) { Activator.getDefault().getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to determine if app " + app.getName() + " is owned by myself", e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.herokuError(getShell(), e); } } else if (s.getFirstElement() instanceof HerokuProc) { HerokuProc proc = (HerokuProc) s.getFirstElement(); importApp.setEnabled(false); open.setEnabled(false); try { App app = herokuService.getApp(pm, proc.getHerokuProc().getAppName()); if (herokuService.isOwnApp(pm, app)) { scale.setEnabled(true); } } catch (HerokuServiceException e) { Activator .getDefault() .getLogger() .log(LogService.LOG_ERROR, "unknown error when trying to determine if app " + proc.getHerokuProc().getAppName() + " is owned by myself", e); //$NON-NLS-1$ //$NON-NLS-2$ HerokuUtils.herokuError(getShell(), e); } } } } }); return mgr; }
diff --git a/app/src/processing/app/windows/Platform.java b/app/src/processing/app/windows/Platform.java index 52a49868f..9bd02826d 100644 --- a/app/src/processing/app/windows/Platform.java +++ b/app/src/processing/app/windows/Platform.java @@ -1,212 +1,212 @@ /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2008 Ben Fry and Casey Reas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app.windows; import java.io.*; import javax.swing.*; import processing.app.Base; import processing.app.windows.Registry.REGISTRY_ROOT_KEY; // http://developer.apple.com/documentation/QuickTime/Conceptual/QT7Win_Update_Guide/Chapter03/chapter_3_section_1.html // HKEY_LOCAL_MACHINE\SOFTWARE\Apple Computer, Inc.\QuickTime\QTSysDir // HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit\CurrentVersion -> 1.6 (String) // HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit\CurrentVersion\1.6\JavaHome -> c:\jdk-1.6.0_05 public class Platform extends processing.app.Platform { static final String openCommand = System.getProperty("user.dir").replace('/', '\\') + "\\processing.exe \"%1\""; static final String doc = "Processing.Document"; public void init(Base base) { super.init(base); try { String knownCommand = Registry.getStringValue(REGISTRY_ROOT_KEY.CLASSES_ROOT, doc + "\\shell\\open\\command", ""); //System.out.println("known is " + knownCommand); if (knownCommand == null) { String prompt = "Processing is not set to handle .pde files.\n" + "Would you like to make it the default?"; int result = - JOptionPane.showConfirmDialog(this, prompt, "Reassign .pde files", + JOptionPane.showConfirmDialog(null, prompt, "Reassign .pde files", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { setAssociations(); } } else if (!knownCommand.equals(openCommand)) { // If the value is set differently, just change the registry setting. String prompt = "This version of Processing is not the default application\n" + "to open .pde files. Would you like to make it the default?"; int result = - JOptionPane.showConfirmDialog(this, prompt, "Reassign .pde files", + JOptionPane.showConfirmDialog(null, prompt, "Reassign .pde files", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { setAssociations(); } } } catch (Exception e) { e.printStackTrace(); } } /** * Associate .pde files with this version of Processing. */ protected void setAssociations() throws UnsupportedEncodingException { if (Registry.createKey(REGISTRY_ROOT_KEY.CLASSES_ROOT, "", ".pde") && Registry.setStringValue(REGISTRY_ROOT_KEY.CLASSES_ROOT, ".pde", "", doc) && Registry.createKey(REGISTRY_ROOT_KEY.CLASSES_ROOT, "", doc) && Registry.setStringValue(REGISTRY_ROOT_KEY.CLASSES_ROOT, doc, "", "Processing Source Code") && Registry.createKey(REGISTRY_ROOT_KEY.CLASSES_ROOT, doc, "shell") && Registry.createKey(REGISTRY_ROOT_KEY.CLASSES_ROOT, doc + "\\shell", "open") && Registry.createKey(REGISTRY_ROOT_KEY.CLASSES_ROOT, doc + "\\shell\\open", "command") && Registry.setStringValue(REGISTRY_ROOT_KEY.CLASSES_ROOT, doc + "\\shell\\open\\command", "", openCommand)) { // everything ok } else { // not ok } } // looking for Documents and Settings/blah/Application Data/Processing public File getSettingsFolder() throws Exception { // HKEY_CURRENT_USER\Software\Microsoft // \Windows\CurrentVersion\Explorer\Shell Folders // Value Name: AppData // Value Type: REG_SZ // Value Data: path String keyPath = "Software\\Microsoft\\Windows\\CurrentVersion" + "\\Explorer\\Shell Folders"; String appDataPath = Registry.getStringValue(REGISTRY_ROOT_KEY.CURRENT_USER, keyPath, "AppData"); File dataFolder = new File(appDataPath, "Processing"); return dataFolder; } // looking for Documents and Settings/blah/My Documents/Processing // (though using a reg key since it's different on other platforms) public File getDefaultSketchbookFolder() throws Exception { // http://support.microsoft.com/?kbid=221837&sd=RMVP // http://support.microsoft.com/kb/242557/en-us // The path to the My Documents folder is stored in the following // registry key, where path is the complete path to your storage location // HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders // Value Name: Personal // Value Type: REG_SZ // Value Data: path // in some instances, this may be overridden by a policy, in which case check: // HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders String keyPath = "Software\\Microsoft\\Windows\\CurrentVersion" + "\\Explorer\\Shell Folders"; String personalPath = Registry.getStringValue(REGISTRY_ROOT_KEY.CURRENT_USER, keyPath, "Personal"); return new File(personalPath, "Processing"); } public void openURL(String url) throws Exception { // this is not guaranteed to work, because who knows if the // path will always be c:\progra~1 et al. also if the user has // a different browser set as their default (which would // include me) it'd be annoying to be dropped into ie. //Runtime.getRuntime().exec("c:\\progra~1\\intern~1\\iexplore " // + currentDir // the following uses a shell execute to launch the .html file // note that under cygwin, the .html files have to be chmodded +x // after they're unpacked from the zip file. i don't know why, // and don't understand what this does in terms of windows // permissions. without the chmod, the command prompt says // "Access is denied" in both cygwin and the "dos" prompt. //Runtime.getRuntime().exec("cmd /c " + currentDir + "\\reference\\" + // referenceFile + ".html"); if (url.startsWith("http://")) { // open dos prompt, give it 'start' command, which will // open the url properly. start by itself won't work since // it appears to need cmd Runtime.getRuntime().exec("cmd /c start " + url); } else { // just launching the .html file via the shell works // but make sure to chmod +x the .html files first // also place quotes around it in case there's a space // in the user.dir part of the url Runtime.getRuntime().exec("cmd /c \"" + url + "\""); } } public boolean openFolderAvailable() { return true; } public void openFolder(File file) throws Exception { String folder = file.getAbsolutePath(); // doesn't work //Runtime.getRuntime().exec("cmd /c \"" + folder + "\""); // works fine on winxp, prolly win2k as well Runtime.getRuntime().exec("explorer \"" + folder + "\""); // not tested //Runtime.getRuntime().exec("start explorer \"" + folder + "\""); } }
false
true
public void init(Base base) { super.init(base); try { String knownCommand = Registry.getStringValue(REGISTRY_ROOT_KEY.CLASSES_ROOT, doc + "\\shell\\open\\command", ""); //System.out.println("known is " + knownCommand); if (knownCommand == null) { String prompt = "Processing is not set to handle .pde files.\n" + "Would you like to make it the default?"; int result = JOptionPane.showConfirmDialog(this, prompt, "Reassign .pde files", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { setAssociations(); } } else if (!knownCommand.equals(openCommand)) { // If the value is set differently, just change the registry setting. String prompt = "This version of Processing is not the default application\n" + "to open .pde files. Would you like to make it the default?"; int result = JOptionPane.showConfirmDialog(this, prompt, "Reassign .pde files", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { setAssociations(); } } } catch (Exception e) { e.printStackTrace(); } }
public void init(Base base) { super.init(base); try { String knownCommand = Registry.getStringValue(REGISTRY_ROOT_KEY.CLASSES_ROOT, doc + "\\shell\\open\\command", ""); //System.out.println("known is " + knownCommand); if (knownCommand == null) { String prompt = "Processing is not set to handle .pde files.\n" + "Would you like to make it the default?"; int result = JOptionPane.showConfirmDialog(null, prompt, "Reassign .pde files", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { setAssociations(); } } else if (!knownCommand.equals(openCommand)) { // If the value is set differently, just change the registry setting. String prompt = "This version of Processing is not the default application\n" + "to open .pde files. Would you like to make it the default?"; int result = JOptionPane.showConfirmDialog(null, prompt, "Reassign .pde files", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { setAssociations(); } } } catch (Exception e) { e.printStackTrace(); } }
diff --git a/groovy/src/test/java/org/sonar/plugins/groovy/GroovyIT.java b/groovy/src/test/java/org/sonar/plugins/groovy/GroovyIT.java index 517e16e5f..1369c3027 100644 --- a/groovy/src/test/java/org/sonar/plugins/groovy/GroovyIT.java +++ b/groovy/src/test/java/org/sonar/plugins/groovy/GroovyIT.java @@ -1,163 +1,167 @@ /* * Sonar Groovy Plugin * Copyright (C) 2010 SonarSource * [email protected] * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.groovy; import org.junit.BeforeClass; import org.junit.Test; import org.sonar.wsclient.Sonar; import org.sonar.wsclient.services.Measure; import org.sonar.wsclient.services.ResourceQuery; import static junit.framework.Assert.assertNull; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.core.Is.is; public class GroovyIT { private static Sonar sonar; private static final String PROJECT_CODENARC = "org.codenarc:CodeNarc"; private static final String PACKAGE_REPORT = "org.codenarc:CodeNarc:org.codenarc.report"; private static final String FILE_REPORT_WRITER = "org.codenarc:CodeNarc:org.codenarc.report.HtmlReportWriter"; @BeforeClass public static void buildServer() { sonar = Sonar.create("http://localhost:9000"); } @Test public void codenarcIsAnalyzed() { assertThat(sonar.find(new ResourceQuery(PROJECT_CODENARC)).getName(), is("CodeNarc")); assertThat(sonar.find(new ResourceQuery(PROJECT_CODENARC)).getVersion(), is("0.9")); assertThat(sonar.find(new ResourceQuery(PACKAGE_REPORT)).getName(), is("org.codenarc.report")); } @Test public void projectsMetrics() { assertThat(getProjectMeasure("ncloc").getIntValue(), is(4199)); assertThat(getProjectMeasure("lines").getIntValue(), is(9439)); assertThat(getProjectMeasure("files").getIntValue(), is(198)); assertThat(getProjectMeasure("classes").getIntValue(), is(135)); assertThat(getProjectMeasure("packages").getIntValue(), is(22)); assertThat(getProjectMeasure("functions").getIntValue(), is(365)); assertThat(getProjectMeasure("comment_lines_density").getValue(), is(40.5)); assertThat(getProjectMeasure("comment_lines").getIntValue(), is(2856)); assertThat(getProjectMeasure("duplicated_lines").getIntValue(), is(54)); assertThat(getProjectMeasure("duplicated_blocks").getIntValue(), is(2)); assertThat(getProjectMeasure("duplicated_lines_density").getValue(), is(0.6)); assertThat(getProjectMeasure("duplicated_files").getIntValue(), is(2)); assertThat(getProjectMeasure("complexity").getIntValue(), is(816)); assertThat(getProjectMeasure("function_complexity").getValue(), is(2.2)); assertThat(getProjectMeasure("class_complexity").getValue(), is(6.0)); assertThat(getProjectMeasure("violations").getIntValue(), is(12)); assertThat(getProjectMeasure("violations_density").getValue(), is(99.3)); assertThat(getProjectMeasure("class_complexity_distribution").getData(), is("0=138;5=31;10=19;20=7;30=1;60=0;90=0")); assertThat(getProjectMeasure("function_complexity_distribution").getData(), is("1=177;2=133;4=38;6=11;8=1;10=4;12=1")); // We are getting different results for different Java versions : 1.6.0_21 and 1.5.0_16 - assertThat(getProjectMeasure("coverage").getValue(), anyOf(is(89.8), is(90.0))); + assertThat("coverage", getProjectMeasure("coverage").getValue(), anyOf( + is(89.8), + is(90.0), + is(89.9) // java 1.6.0_20 + )); assertThat(getProjectMeasure("line_coverage").getValue(), anyOf(is(98.9), is(98.8))); assertThat(getProjectMeasure("lines_to_cover").getValue(), anyOf(is(1802.0), is(1806.0), is(1805.0))); assertThat(getProjectMeasure("uncovered_lines").getValue(), anyOf(is(20.0), is(21.0), is(19.0))); assertThat(getProjectMeasure("tests").getValue(), is(1201.0)); assertThat(getProjectMeasure("test_success_density").getValue(), is(99.9)); } @Test public void packagesMetrics() { assertThat(getPackageMeasure("ncloc").getIntValue(), is(540)); assertThat(getPackageMeasure("lines").getIntValue(), is(807)); assertThat(getPackageMeasure("files").getIntValue(), is(6)); assertThat(getPackageMeasure("classes").getIntValue(), is(6)); assertThat(getPackageMeasure("packages").getIntValue(), is(1)); assertThat(getPackageMeasure("functions").getIntValue(), is(56)); assertThat(getPackageMeasure("comment_lines_density").getValue(), is(17.8)); assertThat(getPackageMeasure("comment_lines").getIntValue(), is(117)); assertThat(getPackageMeasure("duplicated_lines").getIntValue(), is(0)); assertThat(getPackageMeasure("duplicated_blocks").getIntValue(), is(0)); assertThat(getPackageMeasure("duplicated_lines_density").getValue(), is(0.0)); assertThat(getPackageMeasure("duplicated_files").getIntValue(), is(0)); assertThat(getPackageMeasure("complexity").getIntValue(), is(96)); assertThat(getPackageMeasure("function_complexity").getValue(), is(1.7)); assertThat(getPackageMeasure("class_complexity").getValue(), is(16.0)); assertThat(getPackageMeasure("violations").getIntValue(), is(4)); assertThat(getPackageMeasure("violations_density").getValue(), is(97.8)); assertThat(getPackageMeasure("class_complexity_distribution").getData(), is("0=2;5=0;10=2;20=1;30=1;60=0;90=0")); assertThat(getPackageMeasure("function_complexity_distribution").getData(), is("1=31;2=20;4=5;6=0;8=0;10=0;12=0")); // We are getting different results for different Java versions : 1.6.0_21 and 1.5.0_16 assertThat(getPackageMeasure("coverage").getValue(), anyOf(is(88.8), is(89.1))); assertThat(getPackageMeasure("line_coverage").getValue(), anyOf(is(99.7), is(99.3))); assertThat(getPackageMeasure("lines_to_cover").getValue(), anyOf(is(304.0), is(303.0), is(305.0))); assertThat(getPackageMeasure("uncovered_lines").getValue(), anyOf(is(1.0), is(2.0))); assertThat(getPackageMeasure("tests").getValue(), is(60.0)); assertThat(getPackageMeasure("test_success_density").getValue(), is(100.0)); } @Test public void filesMetrics() { assertThat(getFileMeasure("ncloc").getIntValue(), is(238)); assertThat(getFileMeasure("lines").getIntValue(), is(319)); assertThat(getFileMeasure("files").getIntValue(), is(1)); assertThat(getFileMeasure("classes").getIntValue(), is(1)); assertNull(getFileMeasure("packages")); assertThat(getFileMeasure("functions").getIntValue(), is(18)); assertThat(getFileMeasure("comment_lines_density").getValue(), is(12.8)); assertThat(getFileMeasure("comment_lines").getIntValue(), is(35)); assertNull(getFileMeasure("duplicated_lines")); assertNull(getFileMeasure("duplicated_blocks")); assertNull(getFileMeasure("duplicated_files")); assertNull(getFileMeasure("duplicated_lines_density")); assertThat(getFileMeasure("complexity").getIntValue(), is(36)); assertThat(getFileMeasure("function_complexity").getValue(), is(2.0)); assertThat(getFileMeasure("class_complexity").getValue(), is(36.0)); assertThat(getFileMeasure("violations").getIntValue(), is(4)); assertThat(getFileMeasure("violations_density").getValue(), is(95.0)); assertNull(getFileMeasure("class_complexity_distribution")); assertNull(getFileMeasure("function_complexity_distribution")); // We are getting different results for different Java versions : 1.6.0_21 and 1.5.0_16 assertThat(getFileMeasure("coverage").getValue(), anyOf(is(87.1), is(87.7))); assertThat(getFileMeasure("line_coverage").getValue(), is(100.0)); assertThat(getFileMeasure("lines_to_cover").getValue(), anyOf(is(148.0), is(149.0))); assertThat(getFileMeasure("uncovered_lines").getValue(), is(0.0)); assertNull(getFileMeasure("tests")); assertNull(getFileMeasure("test_success_density")); } private Measure getFileMeasure(String metricKey) { return sonar.find(ResourceQuery.createForMetrics(FILE_REPORT_WRITER, metricKey)).getMeasure(metricKey); } private Measure getPackageMeasure(String metricKey) { return sonar.find(ResourceQuery.createForMetrics(PACKAGE_REPORT, metricKey)).getMeasure(metricKey); } private Measure getProjectMeasure(String metricKey) { return sonar.find(ResourceQuery.createForMetrics(PROJECT_CODENARC, metricKey)).getMeasure(metricKey); } }
true
true
public void projectsMetrics() { assertThat(getProjectMeasure("ncloc").getIntValue(), is(4199)); assertThat(getProjectMeasure("lines").getIntValue(), is(9439)); assertThat(getProjectMeasure("files").getIntValue(), is(198)); assertThat(getProjectMeasure("classes").getIntValue(), is(135)); assertThat(getProjectMeasure("packages").getIntValue(), is(22)); assertThat(getProjectMeasure("functions").getIntValue(), is(365)); assertThat(getProjectMeasure("comment_lines_density").getValue(), is(40.5)); assertThat(getProjectMeasure("comment_lines").getIntValue(), is(2856)); assertThat(getProjectMeasure("duplicated_lines").getIntValue(), is(54)); assertThat(getProjectMeasure("duplicated_blocks").getIntValue(), is(2)); assertThat(getProjectMeasure("duplicated_lines_density").getValue(), is(0.6)); assertThat(getProjectMeasure("duplicated_files").getIntValue(), is(2)); assertThat(getProjectMeasure("complexity").getIntValue(), is(816)); assertThat(getProjectMeasure("function_complexity").getValue(), is(2.2)); assertThat(getProjectMeasure("class_complexity").getValue(), is(6.0)); assertThat(getProjectMeasure("violations").getIntValue(), is(12)); assertThat(getProjectMeasure("violations_density").getValue(), is(99.3)); assertThat(getProjectMeasure("class_complexity_distribution").getData(), is("0=138;5=31;10=19;20=7;30=1;60=0;90=0")); assertThat(getProjectMeasure("function_complexity_distribution").getData(), is("1=177;2=133;4=38;6=11;8=1;10=4;12=1")); // We are getting different results for different Java versions : 1.6.0_21 and 1.5.0_16 assertThat(getProjectMeasure("coverage").getValue(), anyOf(is(89.8), is(90.0))); assertThat(getProjectMeasure("line_coverage").getValue(), anyOf(is(98.9), is(98.8))); assertThat(getProjectMeasure("lines_to_cover").getValue(), anyOf(is(1802.0), is(1806.0), is(1805.0))); assertThat(getProjectMeasure("uncovered_lines").getValue(), anyOf(is(20.0), is(21.0), is(19.0))); assertThat(getProjectMeasure("tests").getValue(), is(1201.0)); assertThat(getProjectMeasure("test_success_density").getValue(), is(99.9)); }
public void projectsMetrics() { assertThat(getProjectMeasure("ncloc").getIntValue(), is(4199)); assertThat(getProjectMeasure("lines").getIntValue(), is(9439)); assertThat(getProjectMeasure("files").getIntValue(), is(198)); assertThat(getProjectMeasure("classes").getIntValue(), is(135)); assertThat(getProjectMeasure("packages").getIntValue(), is(22)); assertThat(getProjectMeasure("functions").getIntValue(), is(365)); assertThat(getProjectMeasure("comment_lines_density").getValue(), is(40.5)); assertThat(getProjectMeasure("comment_lines").getIntValue(), is(2856)); assertThat(getProjectMeasure("duplicated_lines").getIntValue(), is(54)); assertThat(getProjectMeasure("duplicated_blocks").getIntValue(), is(2)); assertThat(getProjectMeasure("duplicated_lines_density").getValue(), is(0.6)); assertThat(getProjectMeasure("duplicated_files").getIntValue(), is(2)); assertThat(getProjectMeasure("complexity").getIntValue(), is(816)); assertThat(getProjectMeasure("function_complexity").getValue(), is(2.2)); assertThat(getProjectMeasure("class_complexity").getValue(), is(6.0)); assertThat(getProjectMeasure("violations").getIntValue(), is(12)); assertThat(getProjectMeasure("violations_density").getValue(), is(99.3)); assertThat(getProjectMeasure("class_complexity_distribution").getData(), is("0=138;5=31;10=19;20=7;30=1;60=0;90=0")); assertThat(getProjectMeasure("function_complexity_distribution").getData(), is("1=177;2=133;4=38;6=11;8=1;10=4;12=1")); // We are getting different results for different Java versions : 1.6.0_21 and 1.5.0_16 assertThat("coverage", getProjectMeasure("coverage").getValue(), anyOf( is(89.8), is(90.0), is(89.9) // java 1.6.0_20 )); assertThat(getProjectMeasure("line_coverage").getValue(), anyOf(is(98.9), is(98.8))); assertThat(getProjectMeasure("lines_to_cover").getValue(), anyOf(is(1802.0), is(1806.0), is(1805.0))); assertThat(getProjectMeasure("uncovered_lines").getValue(), anyOf(is(20.0), is(21.0), is(19.0))); assertThat(getProjectMeasure("tests").getValue(), is(1201.0)); assertThat(getProjectMeasure("test_success_density").getValue(), is(99.9)); }
diff --git a/src/com/feelthebeats/js/ftb2om/ConverterMain.java b/src/com/feelthebeats/js/ftb2om/ConverterMain.java index 1b6aea6..ad41ea1 100644 --- a/src/com/feelthebeats/js/ftb2om/ConverterMain.java +++ b/src/com/feelthebeats/js/ftb2om/ConverterMain.java @@ -1,107 +1,107 @@ package com.feelthebeats.js.ftb2om; import java.io.*; import java.util.*; public class ConverterMain { public static final String ERROR_ARGUMENTS = "Required arguments: [input file] [output file] [BPM]"; public static final String ERROR_IO = "ERROR: File not found, or error opening file."; public static final String MSG_GREET = "ftb->osumania converter by JS. [email protected]"; public static final String MSG_SCANNING = "Scanning input file..."; public static final String MSG_SCANNING_DONE = "Done scanning. Generating converted text..."; public static final String MSG_DONE = "Done! Now make a new file in osu if you haven't already, and paste the text in."; private static File inFile; private static File outFile; private static BufferedReader reader; private static PrintWriter writer; private static double mainBpm; private static LinkedList<BPM> bpms; private static LinkedList<Note> notes; public static void main(String[] args) { System.out.println(MSG_GREET); bpms = new LinkedList<BPM>(); notes = new LinkedList<Note>(); if (args.length != 3) { System.out.println(ERROR_ARGUMENTS); } else { inFile = new File(args[0]); outFile = new File(args[1]); mainBpm = Double.parseDouble(args[2]); try { reader = new BufferedReader(new FileReader(inFile)); writer = new PrintWriter(outFile); System.out.println(MSG_SCANNING); String readLine; while ((readLine = reader.readLine()) != null) { if (readLine.startsWith("###")) continue; else if (readLine.startsWith("BPM")) { String[] bpmData = readLine.split(" "); bpms.add(new BPM( (int) Math.round(Double.parseDouble(bpmData[1])), mainBpm * Double.parseDouble(bpmData[2]) / 120 )); } else { String[] noteData = readLine.split(" "); String[] noteTimeData = noteData[0].split("-"); double beatLength = 0; int noteTimeStart = (int) Math.round(Double.parseDouble(noteTimeData[0])); if (noteTimeData.length > 1) { int noteTimeEnd = (int) Math.round(Double.parseDouble(noteTimeData[1])); boolean bpmFound = false; for (ListIterator<BPM> bpmIterator = bpms.listIterator(); bpmIterator.hasNext(); ) { BPM bpm = bpmIterator.next(); - if (bpm.getTime() > noteTimeStart) { + if (bpms.size() > 1 && bpm.getTime() > noteTimeStart) { bpm = bpmIterator.previous(); bpm = bpmIterator.previous(); - double noteTimeLength = (noteTimeEnd - noteTimeStart); - beatLength = noteTimeLength * bpm.getValue() / 60000; bpmFound = true; } + double noteTimeLength = (noteTimeEnd - noteTimeStart); + beatLength = noteTimeLength * bpm.getValue() / 60000; if (bpmFound) break; } } notes.add(new Note( noteTimeStart, Integer.parseInt(noteData[2]), beatLength )); } } System.out.println(MSG_SCANNING_DONE); writer.println("[TimingPoints]"); while (!bpms.isEmpty()) { BPM bpm = bpms.remove(); writer.println(bpm.getTime() + "," + 60000 / ((bpm.getValue() != 0) ? bpm.getValue() : 0.01) + ",4,1,0,100,1,0" ); } writer.println(); writer.println("[HitObjects]"); while (!notes.isEmpty()) { Note note = notes.remove(); int noteX = (512 / 14) * ((note.getColumn() - 1) * 2 + 1); int noteY = 192; writer.println(noteX + "," + noteY + "," + note.getTime() + ((note.getBeatLength() > 0) - ? (",2,0,B|" + noteX + ":32,8," + note.getBeatLength() * 70/4) : ",1,0") + ? (",2,0,B|" + noteX + ":32,8," + note.getBeatLength() * 70 / 4) : ",1,0") ); } writer.close(); reader.close(); System.out.println(MSG_DONE); } catch (IOException e) { System.out.println(ERROR_IO); } } } }
false
true
public static void main(String[] args) { System.out.println(MSG_GREET); bpms = new LinkedList<BPM>(); notes = new LinkedList<Note>(); if (args.length != 3) { System.out.println(ERROR_ARGUMENTS); } else { inFile = new File(args[0]); outFile = new File(args[1]); mainBpm = Double.parseDouble(args[2]); try { reader = new BufferedReader(new FileReader(inFile)); writer = new PrintWriter(outFile); System.out.println(MSG_SCANNING); String readLine; while ((readLine = reader.readLine()) != null) { if (readLine.startsWith("###")) continue; else if (readLine.startsWith("BPM")) { String[] bpmData = readLine.split(" "); bpms.add(new BPM( (int) Math.round(Double.parseDouble(bpmData[1])), mainBpm * Double.parseDouble(bpmData[2]) / 120 )); } else { String[] noteData = readLine.split(" "); String[] noteTimeData = noteData[0].split("-"); double beatLength = 0; int noteTimeStart = (int) Math.round(Double.parseDouble(noteTimeData[0])); if (noteTimeData.length > 1) { int noteTimeEnd = (int) Math.round(Double.parseDouble(noteTimeData[1])); boolean bpmFound = false; for (ListIterator<BPM> bpmIterator = bpms.listIterator(); bpmIterator.hasNext(); ) { BPM bpm = bpmIterator.next(); if (bpm.getTime() > noteTimeStart) { bpm = bpmIterator.previous(); bpm = bpmIterator.previous(); double noteTimeLength = (noteTimeEnd - noteTimeStart); beatLength = noteTimeLength * bpm.getValue() / 60000; bpmFound = true; } if (bpmFound) break; } } notes.add(new Note( noteTimeStart, Integer.parseInt(noteData[2]), beatLength )); } } System.out.println(MSG_SCANNING_DONE); writer.println("[TimingPoints]"); while (!bpms.isEmpty()) { BPM bpm = bpms.remove(); writer.println(bpm.getTime() + "," + 60000 / ((bpm.getValue() != 0) ? bpm.getValue() : 0.01) + ",4,1,0,100,1,0" ); } writer.println(); writer.println("[HitObjects]"); while (!notes.isEmpty()) { Note note = notes.remove(); int noteX = (512 / 14) * ((note.getColumn() - 1) * 2 + 1); int noteY = 192; writer.println(noteX + "," + noteY + "," + note.getTime() + ((note.getBeatLength() > 0) ? (",2,0,B|" + noteX + ":32,8," + note.getBeatLength() * 70/4) : ",1,0") ); } writer.close(); reader.close(); System.out.println(MSG_DONE); } catch (IOException e) { System.out.println(ERROR_IO); } } }
public static void main(String[] args) { System.out.println(MSG_GREET); bpms = new LinkedList<BPM>(); notes = new LinkedList<Note>(); if (args.length != 3) { System.out.println(ERROR_ARGUMENTS); } else { inFile = new File(args[0]); outFile = new File(args[1]); mainBpm = Double.parseDouble(args[2]); try { reader = new BufferedReader(new FileReader(inFile)); writer = new PrintWriter(outFile); System.out.println(MSG_SCANNING); String readLine; while ((readLine = reader.readLine()) != null) { if (readLine.startsWith("###")) continue; else if (readLine.startsWith("BPM")) { String[] bpmData = readLine.split(" "); bpms.add(new BPM( (int) Math.round(Double.parseDouble(bpmData[1])), mainBpm * Double.parseDouble(bpmData[2]) / 120 )); } else { String[] noteData = readLine.split(" "); String[] noteTimeData = noteData[0].split("-"); double beatLength = 0; int noteTimeStart = (int) Math.round(Double.parseDouble(noteTimeData[0])); if (noteTimeData.length > 1) { int noteTimeEnd = (int) Math.round(Double.parseDouble(noteTimeData[1])); boolean bpmFound = false; for (ListIterator<BPM> bpmIterator = bpms.listIterator(); bpmIterator.hasNext(); ) { BPM bpm = bpmIterator.next(); if (bpms.size() > 1 && bpm.getTime() > noteTimeStart) { bpm = bpmIterator.previous(); bpm = bpmIterator.previous(); bpmFound = true; } double noteTimeLength = (noteTimeEnd - noteTimeStart); beatLength = noteTimeLength * bpm.getValue() / 60000; if (bpmFound) break; } } notes.add(new Note( noteTimeStart, Integer.parseInt(noteData[2]), beatLength )); } } System.out.println(MSG_SCANNING_DONE); writer.println("[TimingPoints]"); while (!bpms.isEmpty()) { BPM bpm = bpms.remove(); writer.println(bpm.getTime() + "," + 60000 / ((bpm.getValue() != 0) ? bpm.getValue() : 0.01) + ",4,1,0,100,1,0" ); } writer.println(); writer.println("[HitObjects]"); while (!notes.isEmpty()) { Note note = notes.remove(); int noteX = (512 / 14) * ((note.getColumn() - 1) * 2 + 1); int noteY = 192; writer.println(noteX + "," + noteY + "," + note.getTime() + ((note.getBeatLength() > 0) ? (",2,0,B|" + noteX + ":32,8," + note.getBeatLength() * 70 / 4) : ",1,0") ); } writer.close(); reader.close(); System.out.println(MSG_DONE); } catch (IOException e) { System.out.println(ERROR_IO); } } }
diff --git a/xjc/src/com/sun/tools/xjc/reader/xmlschema/bindinfo/BIConversion.java b/xjc/src/com/sun/tools/xjc/reader/xmlschema/bindinfo/BIConversion.java index c0912005..6111e049 100644 --- a/xjc/src/com/sun/tools/xjc/reader/xmlschema/bindinfo/BIConversion.java +++ b/xjc/src/com/sun/tools/xjc/reader/xmlschema/bindinfo/BIConversion.java @@ -1,335 +1,335 @@ /* * 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. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License 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 * https://jwsdp.dev.java.net/CDDLv1.0.html 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] */ package com.sun.tools.xjc.reader.xmlschema.bindinfo; import javax.xml.bind.DatatypeConverter; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.namespace.QName; import com.sun.codemodel.JClass; import com.sun.codemodel.JClassAlreadyExistsException; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JExpr; import com.sun.codemodel.JExpression; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JPackage; import com.sun.codemodel.JType; import com.sun.codemodel.JVar; import com.sun.tools.xjc.ErrorReceiver; import com.sun.tools.xjc.model.CAdapter; import com.sun.tools.xjc.model.CBuiltinLeafInfo; import com.sun.tools.xjc.model.TypeUse; import com.sun.tools.xjc.model.TypeUseFactory; import com.sun.tools.xjc.reader.Const; import com.sun.tools.xjc.reader.Ring; import com.sun.tools.xjc.reader.TypeUtil; import com.sun.tools.xjc.reader.xmlschema.ClassSelector; import com.sun.xml.bind.v2.WellKnownNamespace; import com.sun.xml.xsom.XSSimpleType; import org.xml.sax.Locator; /** * Conversion declaration. * * <p> * A conversion declaration specifies how an XML type gets mapped * to a Java type. * * @author * Kohsuke Kawaguchi ([email protected]) */ public abstract class BIConversion extends AbstractDeclarationImpl { @Deprecated public BIConversion( Locator loc ) { super(loc); } protected BIConversion() { } /** * Gets the {@link TypeUse} object that this conversion represents. * <p> * The returned {@link TypeUse} object is properly adapted. * * @param owner * A {@link BIConversion} is always associated with one * {@link XSSimpleType}, but that's not always available * when a {@link BIConversion} is built. So we pass this * as a parameter to this method. */ public abstract TypeUse getTypeUse( XSSimpleType owner ); public QName getName() { return NAME; } /** Name of the conversion declaration. */ public static final QName NAME = new QName( Const.JAXB_NSURI, "conversion" ); /** * Implementation that returns a statically-determined constant {@link TypeUse}. */ public static final class Static extends BIConversion { /** * Always non-null. */ private final TypeUse transducer; public Static(Locator loc, TypeUse transducer) { super(loc); this.transducer = transducer; } public TypeUse getTypeUse(XSSimpleType owner) { return transducer; } } /** * User-specified &lt;javaType> customization. * * The parse/print methods are allowed to be null, * and their default values are determined based on the * owner of the token. */ @XmlRootElement(name="javaType") public static class User extends BIConversion { @XmlAttribute private String parseMethod; @XmlAttribute private String printMethod; @XmlAttribute(name="name") private String type = "java.lang.String"; /** * If null, computed from {@link #type}. * Sometimes this can be set instead of {@link #type}. */ private JType inMemoryType; public User(Locator loc, String parseMethod, String printMethod, JType inMemoryType) { super(loc); this.parseMethod = parseMethod; this.printMethod = printMethod; this.inMemoryType = inMemoryType; } public User() { } /** * Cache used by {@link #getTypeUse(XSSimpleType)} to improve the performance. */ private TypeUse typeUse; public TypeUse getTypeUse(XSSimpleType owner) { if(typeUse!=null) return typeUse; JCodeModel cm = getCodeModel(); if(inMemoryType==null) inMemoryType = TypeUtil.getType(cm,type,Ring.get(ErrorReceiver.class),getLocation()); JDefinedClass adapter = generateAdapter(parseMethodFor(owner),printMethodFor(owner),owner); // XmlJavaType customization always converts between string and an user-defined type. typeUse = TypeUseFactory.adapt(CBuiltinLeafInfo.STRING,new CAdapter(adapter)); return typeUse; } /** * generate the adapter class. */ private JDefinedClass generateAdapter(String parseMethod, String printMethod,XSSimpleType owner) { JDefinedClass adapter = null; int id = 1; while(adapter==null) { try { JPackage pkg = Ring.get(ClassSelector.class).getClassScope().getOwnerPackage(); adapter = pkg._class("Adapter"+id); } catch (JClassAlreadyExistsException e) { // try another name in search for an unique name. // this isn't too efficient, but we expect people to usually use // a very small number of adapters. id++; } } JClass bim = inMemoryType.boxify(); adapter._extends(getCodeModel().ref(XmlAdapter.class).narrow(String.class).narrow(bim)); JMethod unmarshal = adapter.method(JMod.PUBLIC, bim, "unmarshal"); JVar $value = unmarshal.param(String.class, "value"); JExpression inv; if( parseMethod.equals("new") ) { // "new" indicates that the constructor of the target type // will do the unmarshalling. // RESULT: new <type>() inv = JExpr._new(bim).arg($value); } else { int idx = parseMethod.lastIndexOf('.'); if(idx<0) { // parseMethod specifies the static method of the target type // which will do the unmarshalling. // because of an error check at the constructor, // we can safely assume that this cast works. inv = bim.staticInvoke(parseMethod).arg($value); } else { inv = JExpr.direct(parseMethod+"(value)"); } } unmarshal.body()._return(inv); JMethod marshal = adapter.method(JMod.PUBLIC, String.class, "marshal"); $value = marshal.param(bim,"value"); - if(this.printMethod==null) { + if(printMethod.startsWith("javax.xml.bind.DatatypeConverter.")) { // UGLY: if this conversion is the system-driven conversion, // check for null marshal.body()._if($value.eq(JExpr._null()))._then()._return(JExpr._null()); } int idx = printMethod.lastIndexOf('.'); if(idx<0) { // printMethod specifies a method in the target type // which performs the serialization. // RESULT: <value>.<method>() inv = $value.invoke(printMethod); } else { // RESULT: <className>.<method>(<value>) if(this.printMethod==null) { // HACK HACK HACK JType t = inMemoryType.unboxify(); inv = JExpr.direct(printMethod+"(("+findBaseConversion(owner).toLowerCase()+")("+t.fullName()+")value)"); } else inv = JExpr.direct(printMethod+"(value)"); } marshal.body()._return(inv); return adapter; } private String printMethodFor(XSSimpleType owner) { if(printMethod!=null) return printMethod; String method = getConversionMethod("print",owner); if(method!=null) return method; return "toString"; } private String parseMethodFor(XSSimpleType owner) { if(parseMethod!=null) return parseMethod; String method = getConversionMethod("parse", owner); if(method!=null) { // this cast is necessary for conversion between primitive Java types return '('+inMemoryType.unboxify().fullName()+')'+method; } return "new"; } private static final String[] knownBases = new String[]{ "Float", "Double", "Byte", "Short", "Int", "Long", "Boolean" }; private String getConversionMethod(String methodPrefix, XSSimpleType owner) { String bc = findBaseConversion(owner); if(bc==null) return null; return DatatypeConverter.class.getName()+'.'+methodPrefix+bc; } private String findBaseConversion(XSSimpleType owner) { // find the base simple type mapping. for( XSSimpleType st=owner; st!=null; st = st.getSimpleBaseType() ) { if( !WellKnownNamespace.XML_SCHEMA.equals(st.getTargetNamespace()) ) continue; // user-defined type String name = st.getName().intern(); for( String s : knownBases ) if(name.equalsIgnoreCase(s)) return s; } return null; } public QName getName() { return NAME; } /** Name of the conversion declaration. */ public static final QName NAME = new QName( Const.JAXB_NSURI, "javaType" ); } @XmlRootElement(name="javaType",namespace=Const.XJC_EXTENSION_URI) public static class UserAdapter extends BIConversion { @XmlAttribute(name="name") private String type = null; @XmlAttribute private String adapter = null; private TypeUse typeUse; public TypeUse getTypeUse(XSSimpleType owner) { if(typeUse!=null) return typeUse; JCodeModel cm = getCodeModel(); JDefinedClass a; try { a = cm._class(adapter); a.hide(); // we assume this is given by the user a._extends(cm.ref(XmlAdapter.class).narrow(String.class).narrow( cm.ref(type))); } catch (JClassAlreadyExistsException e) { a = e.getExistingClass(); } // TODO: it's not correct to say that it adapts from String, // but OTOH I don't think we can compute that. typeUse = TypeUseFactory.adapt( CBuiltinLeafInfo.STRING, new CAdapter(a)); return typeUse; } } }
true
true
private JDefinedClass generateAdapter(String parseMethod, String printMethod,XSSimpleType owner) { JDefinedClass adapter = null; int id = 1; while(adapter==null) { try { JPackage pkg = Ring.get(ClassSelector.class).getClassScope().getOwnerPackage(); adapter = pkg._class("Adapter"+id); } catch (JClassAlreadyExistsException e) { // try another name in search for an unique name. // this isn't too efficient, but we expect people to usually use // a very small number of adapters. id++; } } JClass bim = inMemoryType.boxify(); adapter._extends(getCodeModel().ref(XmlAdapter.class).narrow(String.class).narrow(bim)); JMethod unmarshal = adapter.method(JMod.PUBLIC, bim, "unmarshal"); JVar $value = unmarshal.param(String.class, "value"); JExpression inv; if( parseMethod.equals("new") ) { // "new" indicates that the constructor of the target type // will do the unmarshalling. // RESULT: new <type>() inv = JExpr._new(bim).arg($value); } else { int idx = parseMethod.lastIndexOf('.'); if(idx<0) { // parseMethod specifies the static method of the target type // which will do the unmarshalling. // because of an error check at the constructor, // we can safely assume that this cast works. inv = bim.staticInvoke(parseMethod).arg($value); } else { inv = JExpr.direct(parseMethod+"(value)"); } } unmarshal.body()._return(inv); JMethod marshal = adapter.method(JMod.PUBLIC, String.class, "marshal"); $value = marshal.param(bim,"value"); if(this.printMethod==null) { // UGLY: if this conversion is the system-driven conversion, // check for null marshal.body()._if($value.eq(JExpr._null()))._then()._return(JExpr._null()); } int idx = printMethod.lastIndexOf('.'); if(idx<0) { // printMethod specifies a method in the target type // which performs the serialization. // RESULT: <value>.<method>() inv = $value.invoke(printMethod); } else { // RESULT: <className>.<method>(<value>) if(this.printMethod==null) { // HACK HACK HACK JType t = inMemoryType.unboxify(); inv = JExpr.direct(printMethod+"(("+findBaseConversion(owner).toLowerCase()+")("+t.fullName()+")value)"); } else inv = JExpr.direct(printMethod+"(value)"); } marshal.body()._return(inv); return adapter; }
private JDefinedClass generateAdapter(String parseMethod, String printMethod,XSSimpleType owner) { JDefinedClass adapter = null; int id = 1; while(adapter==null) { try { JPackage pkg = Ring.get(ClassSelector.class).getClassScope().getOwnerPackage(); adapter = pkg._class("Adapter"+id); } catch (JClassAlreadyExistsException e) { // try another name in search for an unique name. // this isn't too efficient, but we expect people to usually use // a very small number of adapters. id++; } } JClass bim = inMemoryType.boxify(); adapter._extends(getCodeModel().ref(XmlAdapter.class).narrow(String.class).narrow(bim)); JMethod unmarshal = adapter.method(JMod.PUBLIC, bim, "unmarshal"); JVar $value = unmarshal.param(String.class, "value"); JExpression inv; if( parseMethod.equals("new") ) { // "new" indicates that the constructor of the target type // will do the unmarshalling. // RESULT: new <type>() inv = JExpr._new(bim).arg($value); } else { int idx = parseMethod.lastIndexOf('.'); if(idx<0) { // parseMethod specifies the static method of the target type // which will do the unmarshalling. // because of an error check at the constructor, // we can safely assume that this cast works. inv = bim.staticInvoke(parseMethod).arg($value); } else { inv = JExpr.direct(parseMethod+"(value)"); } } unmarshal.body()._return(inv); JMethod marshal = adapter.method(JMod.PUBLIC, String.class, "marshal"); $value = marshal.param(bim,"value"); if(printMethod.startsWith("javax.xml.bind.DatatypeConverter.")) { // UGLY: if this conversion is the system-driven conversion, // check for null marshal.body()._if($value.eq(JExpr._null()))._then()._return(JExpr._null()); } int idx = printMethod.lastIndexOf('.'); if(idx<0) { // printMethod specifies a method in the target type // which performs the serialization. // RESULT: <value>.<method>() inv = $value.invoke(printMethod); } else { // RESULT: <className>.<method>(<value>) if(this.printMethod==null) { // HACK HACK HACK JType t = inMemoryType.unboxify(); inv = JExpr.direct(printMethod+"(("+findBaseConversion(owner).toLowerCase()+")("+t.fullName()+")value)"); } else inv = JExpr.direct(printMethod+"(value)"); } marshal.body()._return(inv); return adapter; }
diff --git a/src/main/java/com/github/droidfu/cachefu/CachedList.java b/src/main/java/com/github/droidfu/cachefu/CachedList.java index 2c2f577..0028598 100644 --- a/src/main/java/com/github/droidfu/cachefu/CachedList.java +++ b/src/main/java/com/github/droidfu/cachefu/CachedList.java @@ -1,253 +1,256 @@ package com.github.droidfu.cachefu; import java.io.IOException; import java.util.ArrayList; import android.os.Parcel; import android.os.Parcelable; /** * Superclass of all list objects to be stored in {@link ModelCache}. * * Operates just as standard cached object, and contains an array list of objects. * * <b>Must</b> be initialized with the class of the objects stored, as this is used in * parcelling/unparcelling. * * In order to ensure thread-safe use of list (such as iteration), use the {@link #getList()} * method, creating a copy of the list in its current state. * * @author michaelengland * * @param <CO> * Type of cached models to be stored in list */ public class CachedList<CO extends CachedModel> extends CachedModel { /** * Class type of object list */ protected Class<? extends CachedModel> clazz; /** * List of objects. */ protected ArrayList<CO> list; /** * Simple parameter-less constructor. <b>Must</b> also have parameter-less constructor in * subclasses in order for parceling to work. * * <b>Do not use this constructor when creating a list, use one setting class instead.</b> */ public CachedList() { list = new ArrayList<CO>(); } /** * Constructor setting variables from parcel. Same as using a blank constructor and calling * readFromParcel. * * @param source * Parcel to be read from. * @throws IOException */ public CachedList(Parcel source) throws IOException { super(source); } /** * Constructor initializing class of objects stored. * * @param clazz * Required for parcelling and unparcelling of list */ public CachedList(Class<? extends CachedModel> clazz) { this.clazz = clazz; list = new ArrayList<CO>(); } /** * Constructor initializing class of objects stored as well as initial length of list. * * @param clazz * Required for parcelling and unparcelling of list * @param initialLength * Initial length of list */ public CachedList(Class<? extends CachedModel> clazz, int initialLength) { this.clazz = clazz; list = new ArrayList<CO>(initialLength); } /** * Constructor initializing class of objects stored as well as id used in key generation. * * @param clazz * Required for parcelling and unparcelling of list * @param id * ID of new list (used when generating cache key). */ public CachedList(Class<? extends CachedModel> clazz, String id) { super(id); this.clazz = clazz; list = new ArrayList<CO>(); } /** * Synchronized method to get a copy of the list in its current state. This should be used when * iterating over the list in order to avoid thread-unsafe operations. * * @return Copy of list in its current state */ public synchronized ArrayList<CO> getList() { return new ArrayList<CO>(list); } /** * Synchronized method used to append an object to the list. * * @param cachedObject * Object to add to list */ public synchronized void add(CO cachedObject) { list.add(cachedObject); } /** * Synchronized method used to set an object at a location in the list. * * @param index * Index of item to set * @param cachedObject * Object to set in list */ public synchronized void set(int index, CO cachedObject) { list.set(index, cachedObject); } /** * Synchronized method used to get an object from the live list. * * @param index * Index of item in list * @return Item in list */ public synchronized CO get(int index) { return list.get(index); } /** * Synchronized method used to return size of list. * * @return Size of list */ public synchronized int size() { return list.size(); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public synchronized boolean equals(Object o) { if (!(o instanceof CachedList)) { return false; } @SuppressWarnings("rawtypes") CachedList that = (CachedList) o; return clazz.equals(that.clazz) && list.equals(that.list); } /** * @see com.github.droidfu.cachefu.CachedModel#createKey(java.lang.String) */ @Override public synchronized String createKey(String id) { return "list_" + id; } @Override public boolean reload(ModelCache modelCache) { // First reload list object boolean result = super.reload(modelCache); - // Then reload each item in list - for (CachedModel listModel : list) { + // Then reload each item in list. Sometimes a ConcurrentModificationException occurs. + // Changed implementation so that it doesn't use an Iterator any more. + // Uglier but hopefully that will solve the issue. + for (int i = 0; i < list.size(); i++) { + CachedModel listModel = list.get(i); if (listModel.reload(modelCache)) { result = true; } } return result; } /** * @see com.github.droidfu.cachefu.CachedModel#reloadFromCachedModel(com.github.droidfu.cachefu.ModelCache, * com.github.droidfu.cachefu.CachedModel) */ @Override public synchronized boolean reloadFromCachedModel(ModelCache modelCache, CachedModel cachedModel) { @SuppressWarnings("unchecked") CachedList<CO> cachedList = (CachedList<CO>) cachedModel; clazz = cachedList.clazz; list = cachedList.list; return false; } /** * Creator object used for parcelling */ public static final Creator<CachedList<CachedModel>> CREATOR = new Parcelable.Creator<CachedList<CachedModel>>() { /** * @see android.os.Parcelable.Creator#createFromParcel(android.os.Parcel) */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public CachedList<CachedModel> createFromParcel(Parcel source) { try { return new CachedList(source); } catch (IOException e) { e.printStackTrace(); return null; } } /** * @see android.os.Parcelable.Creator#newArray(int) */ @SuppressWarnings("unchecked") @Override public CachedList<CachedModel>[] newArray(int size) { return new CachedList[size]; } }; /** * @see com.github.droidfu.cachefu.CachedModel#readFromParcel(android.os.Parcel) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void readFromParcel(Parcel source) throws IOException { super.readFromParcel(source); // Read class from parcel, then load class and use creator to generate new object from data String className = source.readString(); try { clazz = (Class<? extends CachedModel>) Class.forName(className); list = source.createTypedArrayList((Creator) clazz.getField("CREATOR").get(this)); } catch (Exception e) { e.printStackTrace(); } } /** * @see com.github.droidfu.cachefu.CachedModel#writeToParcel(android.os.Parcel, int) */ @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); // Write class name to parcel before object, so can be loaded correctly back in dest.writeString(clazz.getCanonicalName()); dest.writeTypedList(list); } }
true
true
public boolean reload(ModelCache modelCache) { // First reload list object boolean result = super.reload(modelCache); // Then reload each item in list for (CachedModel listModel : list) { if (listModel.reload(modelCache)) { result = true; } } return result; }
public boolean reload(ModelCache modelCache) { // First reload list object boolean result = super.reload(modelCache); // Then reload each item in list. Sometimes a ConcurrentModificationException occurs. // Changed implementation so that it doesn't use an Iterator any more. // Uglier but hopefully that will solve the issue. for (int i = 0; i < list.size(); i++) { CachedModel listModel = list.get(i); if (listModel.reload(modelCache)) { result = true; } } return result; }
diff --git a/src/main/java/com/onarandombox/MultiverseSignPortals/MultiverseSignPortals.java b/src/main/java/com/onarandombox/MultiverseSignPortals/MultiverseSignPortals.java index aa770dc..f767311 100644 --- a/src/main/java/com/onarandombox/MultiverseSignPortals/MultiverseSignPortals.java +++ b/src/main/java/com/onarandombox/MultiverseSignPortals/MultiverseSignPortals.java @@ -1,142 +1,142 @@ /* * Multiverse 2 Copyright (c) the Multiverse Team 2011. * Multiverse 2 is licensed under the BSD License. * For more information please check the README.md file included * with this project. */ package com.onarandombox.MultiverseSignPortals; import com.dumptruckman.minecraft.util.Logging; import com.onarandombox.MultiverseCore.MultiverseCore; import com.onarandombox.MultiverseCore.api.MVPlugin; import com.onarandombox.MultiverseSignPortals.listeners.MVSPBlockListener; import com.onarandombox.MultiverseSignPortals.listeners.MVSPPlayerListener; import com.onarandombox.MultiverseSignPortals.listeners.MVSPPluginListener; import com.onarandombox.MultiverseSignPortals.listeners.MVSPVersionListener; import com.onarandombox.MultiverseSignPortals.utils.PortalDetector; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import java.util.logging.Level; public class MultiverseSignPortals extends JavaPlugin implements MVPlugin { protected MultiverseCore core; protected MVSPPlayerListener playerListener; protected MVSPPluginListener pluginListener; protected MVSPBlockListener blockListener; private final static int requiresProtocol = 7; private PortalDetector portalDetector; public void onEnable() { this.core = (MultiverseCore) getServer().getPluginManager().getPlugin("Multiverse-Core"); // Test if the Core was found, if not we'll disable this plugin. if (this.core == null) { Logging.info("Multiverse-Core not found, will keep looking."); getServer().getPluginManager().disablePlugin(this); return; } if (this.core.getProtocolVersion() < requiresProtocol) { Logging.severe("Your Multiverse-Core is OUT OF DATE"); Logging.severe("This version of SignPortals requires Protocol Level: " + requiresProtocol); Logging.severe("Your of Core Protocol Level is: " + this.core.getProtocolVersion()); Logging.severe("Grab an updated copy at: "); - Logging.severe("http://bukkit.onarandombox.com/?dir=multiverse-core"); + Logging.severe("http://dev.bukkit.org/bukkit-plugins/multiverse-core/"); getServer().getPluginManager().disablePlugin(this); return; } this.core.incrementPluginCount(); // Init our listeners this.pluginListener = new MVSPPluginListener(this); this.playerListener = new MVSPPlayerListener(this); this.blockListener = new MVSPBlockListener(this); // Init our events PluginManager pm = this.getServer().getPluginManager(); pm.registerEvents(this.pluginListener, this); pm.registerEvents(this.playerListener, this); pm.registerEvents(this.blockListener, this); pm.registerEvents(new MVSPVersionListener(this), this); this.portalDetector = new PortalDetector(this); Logging.log(true, Level.INFO, " Enabled - By %s", getAuthors()); } public void onDisable() { // The Usual Logging.info("- Disabled"); } /** This fires before I get Enabled. */ public void onLoad() { Logging.init(this); this.getDataFolder().mkdirs(); } /** * Parse the Authors Array into a readable String with ',' and 'and'. * * @return An comma separated string of authors */ private String getAuthors() { String authors = ""; for (int i = 0; i < this.getDescription().getAuthors().size(); i++) { if (i == this.getDescription().getAuthors().size() - 1) { authors += " and " + this.getDescription().getAuthors().get(i); } else { authors += ", " + this.getDescription().getAuthors().get(i); } } return authors.substring(2); } @Override public void log(Level level, String msg) { Logging.log(level, msg); } // No longer using, use getVersionInfo instead. @Override @Deprecated public String dumpVersionInfo(String buffer) { buffer += logAndAddToPasteBinBuffer(this.getVersionInfo()); return buffer; } public String getVersionInfo() { return new StringBuilder("[Multiverse-SignPortals] Multiverse-SignPortals Version: ").append(this.getDescription().getVersion()).append('\n').toString(); } // No longer using, use getVersionInfo instead. @Deprecated private String logAndAddToPasteBinBuffer(String string) { this.log(Level.INFO, string); return Logging.getPrefixedMessage(string, false); } @Override public MultiverseCore getCore() { return this.core; } @Override public void setCore(MultiverseCore core) { this.core = core; } @Override public int getProtocolVersion() { return 1; } public PortalDetector getPortalDetector() { return this.portalDetector; } }
true
true
public void onEnable() { this.core = (MultiverseCore) getServer().getPluginManager().getPlugin("Multiverse-Core"); // Test if the Core was found, if not we'll disable this plugin. if (this.core == null) { Logging.info("Multiverse-Core not found, will keep looking."); getServer().getPluginManager().disablePlugin(this); return; } if (this.core.getProtocolVersion() < requiresProtocol) { Logging.severe("Your Multiverse-Core is OUT OF DATE"); Logging.severe("This version of SignPortals requires Protocol Level: " + requiresProtocol); Logging.severe("Your of Core Protocol Level is: " + this.core.getProtocolVersion()); Logging.severe("Grab an updated copy at: "); Logging.severe("http://bukkit.onarandombox.com/?dir=multiverse-core"); getServer().getPluginManager().disablePlugin(this); return; } this.core.incrementPluginCount(); // Init our listeners this.pluginListener = new MVSPPluginListener(this); this.playerListener = new MVSPPlayerListener(this); this.blockListener = new MVSPBlockListener(this); // Init our events PluginManager pm = this.getServer().getPluginManager(); pm.registerEvents(this.pluginListener, this); pm.registerEvents(this.playerListener, this); pm.registerEvents(this.blockListener, this); pm.registerEvents(new MVSPVersionListener(this), this); this.portalDetector = new PortalDetector(this); Logging.log(true, Level.INFO, " Enabled - By %s", getAuthors()); }
public void onEnable() { this.core = (MultiverseCore) getServer().getPluginManager().getPlugin("Multiverse-Core"); // Test if the Core was found, if not we'll disable this plugin. if (this.core == null) { Logging.info("Multiverse-Core not found, will keep looking."); getServer().getPluginManager().disablePlugin(this); return; } if (this.core.getProtocolVersion() < requiresProtocol) { Logging.severe("Your Multiverse-Core is OUT OF DATE"); Logging.severe("This version of SignPortals requires Protocol Level: " + requiresProtocol); Logging.severe("Your of Core Protocol Level is: " + this.core.getProtocolVersion()); Logging.severe("Grab an updated copy at: "); Logging.severe("http://dev.bukkit.org/bukkit-plugins/multiverse-core/"); getServer().getPluginManager().disablePlugin(this); return; } this.core.incrementPluginCount(); // Init our listeners this.pluginListener = new MVSPPluginListener(this); this.playerListener = new MVSPPlayerListener(this); this.blockListener = new MVSPBlockListener(this); // Init our events PluginManager pm = this.getServer().getPluginManager(); pm.registerEvents(this.pluginListener, this); pm.registerEvents(this.playerListener, this); pm.registerEvents(this.blockListener, this); pm.registerEvents(new MVSPVersionListener(this), this); this.portalDetector = new PortalDetector(this); Logging.log(true, Level.INFO, " Enabled - By %s", getAuthors()); }
diff --git a/src/org/opensolaris/opengrok/history/ClearCaseRepository.java b/src/org/opensolaris/opengrok/history/ClearCaseRepository.java index 5baaa16..616a368 100644 --- a/src/org/opensolaris/opengrok/history/ClearCaseRepository.java +++ b/src/org/opensolaris/opengrok/history/ClearCaseRepository.java @@ -1,321 +1,321 @@ /* * 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 */ package org.opensolaris.opengrok.history; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.logging.Level; import org.opensolaris.opengrok.OpenGrokLogger; /** * Access to a ClearCase repository. * */ public class ClearCaseRepository extends Repository { private boolean verbose; /** * Get the name of the ClearCase command that should be used * @return the name of the cleartool command in use */ private String getCommand() { return System.getProperty("org.opensolaris.opengrok.history.ClearCase", "cleartool"); } /** * Use verbose log messages, or just the summary * @return true if verbose log messages are used for this repository */ public boolean isVerbose() { return verbose; } /** * Specify if verbose log messages or just the summary should be used * @param verbose set to true if verbose messages should be used */ public void setVerbose(boolean verbose) { this.verbose = verbose; } Process getHistoryLogProcess(File file) throws IOException { String abs = file.getAbsolutePath(); String filename = ""; String directoryName = getDirectoryName(); if (abs.length() > directoryName.length()) { filename = abs.substring(directoryName.length() + 1); } ArrayList<String> argv = new ArrayList<String>(); argv.add(getCommand()); argv.add("lshistory"); if (file.isDirectory()) { argv.add("-dir"); } argv.add("-fmt"); argv.add("%e\n%Nd\n%Fu (%u)\n%Vn\n%Nc\n.\n"); argv.add(filename); ProcessBuilder pb = new ProcessBuilder(argv); File directory = new File(getDirectoryName()); pb.directory(directory); return pb.start(); } public InputStream getHistoryGet(String parent, String basename, String rev) { InputStream ret = null; String directoryName = getDirectoryName(); File directory = new File(directoryName); String filename = (new File(parent, basename)).getAbsolutePath().substring(directoryName.length() + 1); Process process = null; try { final File tmp = File.createTempFile("opengrok", "tmp"); String tmpName = tmp.getAbsolutePath(); // cleartool can't get to a previously existing file if (tmp.exists() && !tmp.delete()) { OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to remove temporary file used by history cache"); } String decorated = filename + "@@" + rev; String argv[] = {getCommand(), "get", "-to", tmpName, decorated}; process = Runtime.getRuntime().exec(argv, null, directory); drainStream(process.getInputStream()); if(waitFor(process) != 0) { return null; } - ret = new BufferedInputStream(new FileInputStream(tmp) { + ret = new BufferedInputStream(new FileInputStream(tmp)) { public void close() throws IOException { super.close(); // delete the temporary file on close if (!tmp.delete()) { // failed, lets do the next best thing then .. // delete it on JVM exit tmp.deleteOnExit(); } } - }); + }; } catch (Exception exp) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to get history: " + exp.getClass().toString(), exp); } finally { // Clean up zombie-processes... if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException exp) { // the process is still running??? just kill it.. process.destroy(); } } } return ret; } /** * Drain all data from a stream and close it. * @param in the stream to drain * @throws IOException if an I/O error occurs */ private static void drainStream(InputStream in) throws IOException { while (true) { long skipped = in.skip(32768L); if (skipped == 0 && in.read() == -1) { // No bytes skipped, checked that we've reached EOF with read() break; } } in.close(); } public Class<? extends HistoryParser> getHistoryParser() { return ClearCaseHistoryParser.class; } public Class<? extends HistoryParser> getDirectoryHistoryParser() { return ClearCaseHistoryParser.class; } /** * Annotate the specified file/revision. * * @param file file to annotate * @param revision revision to annotate * @return file annotation */ public Annotation annotate(File file, String revision) throws IOException { ArrayList<String> argv = new ArrayList<String>(); argv.add(getCommand()); argv.add("annotate"); argv.add("-nheader"); argv.add("-out"); argv.add("-"); argv.add("-f"); argv.add("-fmt"); argv.add("%u|%Vn|"); if (revision != null) { argv.add(revision); } argv.add(file.getName()); ProcessBuilder pb = new ProcessBuilder(argv); pb.directory(file.getParentFile()); Process process = null; BufferedReader in = null; try { process = pb.start(); in = new BufferedReader(new InputStreamReader(process.getInputStream())); Annotation a = new Annotation(file.getName()); String line; int lineno = 0; while ((line = in.readLine()) != null) { ++lineno; String parts[] = line.split("\\|"); String aAuthor = parts[0]; String aRevision = parts[1]; aRevision = aRevision.replace('\\', '/'); a.addLine(aRevision, aAuthor, true); } return a; } finally { if (in != null) { try { in.close(); } catch (IOException exp) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while closing stream.", exp); } } if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException e) { process.destroy(); } } } } public boolean fileHasAnnotation(File file) { return true; } public boolean isCacheable() { return true; } private int waitFor(Process process) { do { try { return process.waitFor(); } catch (InterruptedException exp) { } } while (true); } @SuppressWarnings("PMD.EmptyWhileStmt") public void update() throws IOException { Process process = null; BufferedReader in = null; try { File directory = new File(getDirectoryName()); // Check if this is a snapshot view String[] argv = {getCommand(), "catcs"}; process = Runtime.getRuntime().exec(argv, null, directory); in = new BufferedReader(new InputStreamReader(process.getInputStream())); boolean snapshot = false; String line; while (!snapshot && (line = in.readLine()) != null) { snapshot = line.startsWith("load"); } if (waitFor(process) != 0) { return; } in.close(); in = null; // To avoid double close in finally clause if (snapshot) { // It is a snapshot view, we need to update it manually argv = new String[]{getCommand(), "update", "-overwrite", "-f"}; process = Runtime.getRuntime().exec(argv, null, directory); in = new BufferedReader(new InputStreamReader(process.getInputStream())); // consume output while ((line = in.readLine()) != null) { // do nothing } if (waitFor(process) != 0) { return; } } } finally { if (in != null) { try { in.close(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while closing stream.", e); } } if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException e) { process.destroy(); } } } } public boolean fileHasHistory(File file) { // Todo: is there a cheap test for whether ClearCase has history // available for a file? // Otherwise, this is harmless, since ClearCase's commands will just // print nothing if there is no history. return true; } @Override boolean isRepositoryFor( File file) { // if the parent contains a file named "view.dat" or // the parent is named "vobs" File f = new File(file, "view.dat"); if (f.exists() && f.isDirectory()) { return true; } else { return file.isDirectory() && file.getName().equalsIgnoreCase("vobs"); } } }
false
true
public InputStream getHistoryGet(String parent, String basename, String rev) { InputStream ret = null; String directoryName = getDirectoryName(); File directory = new File(directoryName); String filename = (new File(parent, basename)).getAbsolutePath().substring(directoryName.length() + 1); Process process = null; try { final File tmp = File.createTempFile("opengrok", "tmp"); String tmpName = tmp.getAbsolutePath(); // cleartool can't get to a previously existing file if (tmp.exists() && !tmp.delete()) { OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to remove temporary file used by history cache"); } String decorated = filename + "@@" + rev; String argv[] = {getCommand(), "get", "-to", tmpName, decorated}; process = Runtime.getRuntime().exec(argv, null, directory); drainStream(process.getInputStream()); if(waitFor(process) != 0) { return null; } ret = new BufferedInputStream(new FileInputStream(tmp) { public void close() throws IOException { super.close(); // delete the temporary file on close if (!tmp.delete()) { // failed, lets do the next best thing then .. // delete it on JVM exit tmp.deleteOnExit(); } } }); } catch (Exception exp) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to get history: " + exp.getClass().toString(), exp); } finally { // Clean up zombie-processes... if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException exp) { // the process is still running??? just kill it.. process.destroy(); } } } return ret; }
public InputStream getHistoryGet(String parent, String basename, String rev) { InputStream ret = null; String directoryName = getDirectoryName(); File directory = new File(directoryName); String filename = (new File(parent, basename)).getAbsolutePath().substring(directoryName.length() + 1); Process process = null; try { final File tmp = File.createTempFile("opengrok", "tmp"); String tmpName = tmp.getAbsolutePath(); // cleartool can't get to a previously existing file if (tmp.exists() && !tmp.delete()) { OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to remove temporary file used by history cache"); } String decorated = filename + "@@" + rev; String argv[] = {getCommand(), "get", "-to", tmpName, decorated}; process = Runtime.getRuntime().exec(argv, null, directory); drainStream(process.getInputStream()); if(waitFor(process) != 0) { return null; } ret = new BufferedInputStream(new FileInputStream(tmp)) { public void close() throws IOException { super.close(); // delete the temporary file on close if (!tmp.delete()) { // failed, lets do the next best thing then .. // delete it on JVM exit tmp.deleteOnExit(); } } }; } catch (Exception exp) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to get history: " + exp.getClass().toString(), exp); } finally { // Clean up zombie-processes... if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException exp) { // the process is still running??? just kill it.. process.destroy(); } } } return ret; }
diff --git a/src/java/com/android/internal/telephony/UiccCardApplication.java b/src/java/com/android/internal/telephony/UiccCardApplication.java index 9ec16fc..2718af6 100644 --- a/src/java/com/android/internal/telephony/UiccCardApplication.java +++ b/src/java/com/android/internal/telephony/UiccCardApplication.java @@ -1,699 +1,699 @@ /* * Copyright (C) 2006, 2012 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.internal.telephony; import android.content.Context; import android.os.AsyncResult; import android.os.Handler; import android.os.Message; import android.os.Registrant; import android.os.RegistrantList; import android.util.Log; import com.android.internal.telephony.IccCardApplicationStatus.AppState; import com.android.internal.telephony.IccCardApplicationStatus.AppType; import com.android.internal.telephony.IccCardApplicationStatus.PersoSubState; import com.android.internal.telephony.IccCardStatus.PinState; import com.android.internal.telephony.cdma.RuimFileHandler; import com.android.internal.telephony.cdma.RuimRecords; import com.android.internal.telephony.gsm.SIMFileHandler; import com.android.internal.telephony.gsm.SIMRecords; import com.android.internal.telephony.ims.IsimFileHandler; import com.android.internal.telephony.ims.IsimUiccRecords; /** * {@hide} */ public class UiccCardApplication { private static final String LOG_TAG = "RIL_UiccCardApplication"; private static final boolean DBG = true; private static final int EVENT_QUERY_FACILITY_FDN_DONE = 1; private static final int EVENT_CHANGE_FACILITY_FDN_DONE = 2; private static final int EVENT_QUERY_FACILITY_LOCK_DONE = 3; private static final int EVENT_CHANGE_FACILITY_LOCK_DONE = 4; private final Object mLock = new Object(); private UiccCard mUiccCard; //parent private AppState mAppState; private AppType mAppType; private PersoSubState mPersoSubState; private String mAid; private String mAppLabel; private boolean mPin1Replaced; private PinState mPin1State; private PinState mPin2State; private boolean mIccFdnEnabled; private boolean mDesiredFdnEnabled; private boolean mIccLockEnabled; private boolean mDesiredPinLocked; private CommandsInterface mCi; private Context mContext; private IccRecords mIccRecords; private IccFileHandler mIccFh; private boolean mDestroyed;//set to true once this App is commanded to be disposed of. private RegistrantList mReadyRegistrants = new RegistrantList(); private RegistrantList mPinLockedRegistrants = new RegistrantList(); private RegistrantList mNetworkLockedRegistrants = new RegistrantList(); UiccCardApplication(UiccCard uiccCard, IccCardApplicationStatus as, Context c, CommandsInterface ci) { if (DBG) log("Creating UiccApp: " + as); mUiccCard = uiccCard; mAppState = as.app_state; mAppType = as.app_type; mPersoSubState = as.perso_substate; mAid = as.aid; mAppLabel = as.app_label; mPin1Replaced = (as.pin1_replaced != 0); mPin1State = as.pin1; mPin2State = as.pin2; mContext = c; mCi = ci; mIccFh = createIccFileHandler(as.app_type); mIccRecords = createIccRecords(as.app_type, mContext, mCi); if (mAppState == AppState.APPSTATE_READY) { queryFdn(); queryPin1State(); } } void update (IccCardApplicationStatus as, Context c, CommandsInterface ci) { synchronized (mLock) { if (mDestroyed) { loge("Application updated after destroyed! Fix me!"); return; } if (DBG) log(mAppType + " update. New " + as); mContext = c; mCi = ci; AppType oldAppType = mAppType; AppState oldAppState = mAppState; PersoSubState oldPersoSubState = mPersoSubState; mAppType = as.app_type; mAppState = as.app_state; mPersoSubState = as.perso_substate; mAid = as.aid; mAppLabel = as.app_label; mPin1Replaced = (as.pin1_replaced != 0); mPin1State = as.pin1; mPin2State = as.pin2; if (mAppType != oldAppType) { - mIccFh.dispose(); - mIccRecords.dispose(); + if (mIccFh != null) { mIccFh.dispose();} + if (mIccRecords != null) { mIccRecords.dispose();} mIccFh = createIccFileHandler(as.app_type); mIccRecords = createIccRecords(as.app_type, c, ci); } if (mPersoSubState != oldPersoSubState && mPersoSubState == PersoSubState.PERSOSUBSTATE_SIM_NETWORK) { notifyNetworkLockedRegistrantsIfNeeded(null); } if (mAppState != oldAppState) { if (DBG) log(oldAppType + " changed state: " + oldAppState + " -> " + mAppState); // If the app state turns to APPSTATE_READY, then query FDN status, //as it might have failed in earlier attempt. if (mAppState == AppState.APPSTATE_READY) { queryFdn(); queryPin1State(); } notifyPinLockedRegistrantsIfNeeded(null); notifyReadyRegistrantsIfNeeded(null); } } } void dispose() { synchronized (mLock) { if (DBG) log(mAppType + " being Disposed"); mDestroyed = true; if (mIccRecords != null) { mIccRecords.dispose();} if (mIccFh != null) { mIccFh.dispose();} mIccRecords = null; mIccFh = null; } } private IccRecords createIccRecords(AppType type, Context c, CommandsInterface ci) { if (type == AppType.APPTYPE_USIM || type == AppType.APPTYPE_SIM) { return new SIMRecords(this, c, ci); } else if (type == AppType.APPTYPE_RUIM || type == AppType.APPTYPE_CSIM){ return new RuimRecords(this, c, ci); } else if (type == AppType.APPTYPE_ISIM) { return new IsimUiccRecords(this, c, ci); } else { // Unknown app type (maybe detection is still in progress) return null; } } private IccFileHandler createIccFileHandler(AppType type) { switch (type) { case APPTYPE_SIM: return new SIMFileHandler(this, mAid, mCi); case APPTYPE_RUIM: return new RuimFileHandler(this, mAid, mCi); case APPTYPE_USIM: return new UsimFileHandler(this, mAid, mCi); case APPTYPE_CSIM: return new CsimFileHandler(this, mAid, mCi); case APPTYPE_ISIM: return new IsimFileHandler(this, mAid, mCi); default: return null; } } /** Assumes mLock is held. */ private void queryFdn() { //This shouldn't change run-time. So needs to be called only once. int serviceClassX; serviceClassX = CommandsInterface.SERVICE_CLASS_VOICE + CommandsInterface.SERVICE_CLASS_DATA + CommandsInterface.SERVICE_CLASS_FAX; mCi.queryFacilityLockForApp ( CommandsInterface.CB_FACILITY_BA_FD, "", serviceClassX, mAid, mHandler.obtainMessage(EVENT_QUERY_FACILITY_FDN_DONE)); } /** * Interpret EVENT_QUERY_FACILITY_LOCK_DONE * @param ar is asyncResult of Query_Facility_Locked */ private void onQueryFdnEnabled(AsyncResult ar) { synchronized (mLock) { if (ar.exception != null) { if (DBG) log("Error in querying facility lock:" + ar.exception); return; } int[] ints = (int[])ar.result; if(ints.length != 0) { mIccFdnEnabled = (0!=ints[0]); if (DBG) log("Query facility lock : " + mIccFdnEnabled); } else { loge("Bogus facility lock response"); } } } private void onChangeFdnDone(AsyncResult ar) { synchronized (mLock) { if (ar.exception == null) { mIccFdnEnabled = mDesiredFdnEnabled; if (DBG) log("EVENT_CHANGE_FACILITY_FDN_DONE: " + "mIccFdnEnabled=" + mIccFdnEnabled); } else { loge("Error change facility fdn with exception " + ar.exception); } Message response = (Message)ar.userObj; AsyncResult.forMessage(response).exception = ar.exception; response.sendToTarget(); } } /** REMOVE when mIccLockEnabled is not needed, assumes mLock is held */ private void queryPin1State() { int serviceClassX = CommandsInterface.SERVICE_CLASS_VOICE + CommandsInterface.SERVICE_CLASS_DATA + CommandsInterface.SERVICE_CLASS_FAX; mCi.queryFacilityLockForApp ( CommandsInterface.CB_FACILITY_BA_SIM, "", serviceClassX, mAid, mHandler.obtainMessage(EVENT_QUERY_FACILITY_LOCK_DONE)); } /** REMOVE when mIccLockEnabled is not needed*/ private void onQueryFacilityLock(AsyncResult ar) { synchronized (mLock) { if(ar.exception != null) { if (DBG) log("Error in querying facility lock:" + ar.exception); return; } int[] ints = (int[])ar.result; if(ints.length != 0) { if (DBG) log("Query facility lock : " + ints[0]); mIccLockEnabled = (ints[0] != 0); if (mIccLockEnabled) { mPinLockedRegistrants.notifyRegistrants(); } // Sanity check: we expect mPin1State to match mIccLockEnabled. // When mPin1State is DISABLED mIccLockEanbled should be false. // When mPin1State is ENABLED mIccLockEnabled should be true. // // Here we validate these assumptions to assist in identifying which ril/radio's // have not correctly implemented GET_SIM_STATUS switch (mPin1State) { case PINSTATE_DISABLED: if (mIccLockEnabled) { loge("QUERY_FACILITY_LOCK:enabled GET_SIM_STATUS.Pin1:disabled." + " Fixme"); } break; case PINSTATE_ENABLED_NOT_VERIFIED: case PINSTATE_ENABLED_VERIFIED: case PINSTATE_ENABLED_BLOCKED: case PINSTATE_ENABLED_PERM_BLOCKED: if (!mIccLockEnabled) { loge("QUERY_FACILITY_LOCK:disabled GET_SIM_STATUS.Pin1:enabled." + " Fixme"); } } } else { loge("Bogus facility lock response"); } } } /** REMOVE when mIccLockEnabled is not needed */ private void onChangeFacilityLock(AsyncResult ar) { synchronized (mLock) { if (ar.exception == null) { mIccLockEnabled = mDesiredPinLocked; if (DBG) log( "EVENT_CHANGE_FACILITY_LOCK_DONE: mIccLockEnabled= " + mIccLockEnabled); } else { loge("Error change facility lock with exception " + ar.exception); } AsyncResult.forMessage(((Message)ar.userObj)).exception = ar.exception; ((Message)ar.userObj).sendToTarget(); } } private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg){ AsyncResult ar; if (mDestroyed) { loge("Received message " + msg + "[" + msg.what + "] while being destroyed. Ignoring."); return; } switch (msg.what) { case EVENT_QUERY_FACILITY_FDN_DONE: ar = (AsyncResult)msg.obj; onQueryFdnEnabled(ar); break; case EVENT_CHANGE_FACILITY_FDN_DONE: ar = (AsyncResult)msg.obj; onChangeFdnDone(ar); break; case EVENT_QUERY_FACILITY_LOCK_DONE: ar = (AsyncResult)msg.obj; onQueryFacilityLock(ar); break; case EVENT_CHANGE_FACILITY_LOCK_DONE: ar = (AsyncResult)msg.obj; onChangeFacilityLock(ar); break; default: loge("Unknown Event " + msg.what); } } }; public void registerForReady(Handler h, int what, Object obj) { synchronized (mLock) { Registrant r = new Registrant (h, what, obj); mReadyRegistrants.add(r); notifyReadyRegistrantsIfNeeded(r); } } public void unregisterForReady(Handler h) { synchronized (mLock) { mReadyRegistrants.remove(h); } } /** * Notifies handler of any transition into State.isPinLocked() */ public void registerForLocked(Handler h, int what, Object obj) { synchronized (mLock) { Registrant r = new Registrant (h, what, obj); mPinLockedRegistrants.add(r); notifyPinLockedRegistrantsIfNeeded(r); } } public void unregisterForLocked(Handler h) { synchronized (mLock) { mPinLockedRegistrants.remove(h); } } /** * Notifies handler of any transition into State.NETWORK_LOCKED */ public void registerForNetworkLocked(Handler h, int what, Object obj) { synchronized (mLock) { Registrant r = new Registrant (h, what, obj); mNetworkLockedRegistrants.add(r); notifyNetworkLockedRegistrantsIfNeeded(r); } } public void unregisterForNetworkLocked(Handler h) { synchronized (mLock) { mNetworkLockedRegistrants.remove(h); } } /** * Notifies specified registrant, assume mLock is held. * * @param r Registrant to be notified. If null - all registrants will be notified */ private void notifyReadyRegistrantsIfNeeded(Registrant r) { if (mDestroyed) { return; } if (mAppState == AppState.APPSTATE_READY) { if (mPin1State == PinState.PINSTATE_ENABLED_NOT_VERIFIED || mPin1State == PinState.PINSTATE_ENABLED_BLOCKED || mPin1State == PinState.PINSTATE_ENABLED_PERM_BLOCKED) { loge("Sanity check failed! APPSTATE is ready while PIN1 is not verified!!!"); // Don't notify if application is in insane state return; } if (r == null) { if (DBG) log("Notifying registrants: READY"); mReadyRegistrants.notifyRegistrants(); } else { if (DBG) log("Notifying 1 registrant: READY"); r.notifyRegistrant(new AsyncResult(null, null, null)); } } } /** * Notifies specified registrant, assume mLock is held. * * @param r Registrant to be notified. If null - all registrants will be notified */ private void notifyPinLockedRegistrantsIfNeeded(Registrant r) { if (mDestroyed) { return; } if (mAppState == AppState.APPSTATE_PIN || mAppState == AppState.APPSTATE_PUK) { if (mPin1State == PinState.PINSTATE_ENABLED_VERIFIED || mPin1State == PinState.PINSTATE_DISABLED) { loge("Sanity check failed! APPSTATE is locked while PIN1 is not!!!"); //Don't notify if application is in insane state return; } if (r == null) { if (DBG) log("Notifying registrants: LOCKED"); mPinLockedRegistrants.notifyRegistrants(); } else { if (DBG) log("Notifying 1 registrant: LOCKED"); r.notifyRegistrant(new AsyncResult(null, null, null)); } } } /** * Notifies specified registrant, assume mLock is held. * * @param r Registrant to be notified. If null - all registrants will be notified */ private void notifyNetworkLockedRegistrantsIfNeeded(Registrant r) { if (mDestroyed) { return; } if (mAppState == AppState.APPSTATE_SUBSCRIPTION_PERSO && mPersoSubState == PersoSubState.PERSOSUBSTATE_SIM_NETWORK) { if (r == null) { if (DBG) log("Notifying registrants: NETWORK_LOCKED"); mNetworkLockedRegistrants.notifyRegistrants(); } else { if (DBG) log("Notifying 1 registrant: NETWORK_LOCED"); r.notifyRegistrant(new AsyncResult(null, null, null)); } } } public AppState getState() { synchronized (mLock) { return mAppState; } } public AppType getType() { synchronized (mLock) { return mAppType; } } public PersoSubState getPersoSubState() { synchronized (mLock) { return mPersoSubState; } } public String getAid() { synchronized (mLock) { return mAid; } } public PinState getPin1State() { synchronized (mLock) { if (mPin1Replaced) { return mUiccCard.getUniversalPinState(); } return mPin1State; } } public IccFileHandler getIccFileHandler() { synchronized (mLock) { return mIccFh; } } public IccRecords getIccRecords() { synchronized (mLock) { return mIccRecords; } } /** * Supply the ICC PIN to the ICC * * When the operation is complete, onComplete will be sent to its * Handler. * * onComplete.obj will be an AsyncResult * * ((AsyncResult)onComplete.obj).exception == null on success * ((AsyncResult)onComplete.obj).exception != null on fail * * If the supplied PIN is incorrect: * ((AsyncResult)onComplete.obj).exception != null * && ((AsyncResult)onComplete.obj).exception * instanceof com.android.internal.telephony.gsm.CommandException) * && ((CommandException)(((AsyncResult)onComplete.obj).exception)) * .getCommandError() == CommandException.Error.PASSWORD_INCORRECT * * */ public void supplyPin (String pin, Message onComplete) { synchronized (mLock) { mCi.supplyIccPin(pin, onComplete); } } public void supplyPuk (String puk, String newPin, Message onComplete) { synchronized (mLock) { mCi.supplyIccPuk(puk, newPin, onComplete); } } public void supplyPin2 (String pin2, Message onComplete) { synchronized (mLock) { mCi.supplyIccPin2(pin2, onComplete); } } public void supplyPuk2 (String puk2, String newPin2, Message onComplete) { synchronized (mLock) { mCi.supplyIccPuk2(puk2, newPin2, onComplete); } } public void supplyNetworkDepersonalization (String pin, Message onComplete) { synchronized (mLock) { if (DBG) log("supplyNetworkDepersonalization"); mCi.supplyNetworkDepersonalization(pin, onComplete); } } /** * Check whether ICC pin lock is enabled * This is a sync call which returns the cached pin enabled state * * @return true for ICC locked enabled * false for ICC locked disabled */ public boolean getIccLockEnabled() { return mIccLockEnabled; /* STOPSHIP: Remove line above and all code associated with setting mIccLockEanbled once all RIL correctly sends the pin1 state. // Use getPin1State to take into account pin1Replaced flag PinState pinState = getPin1State(); return pinState == PinState.PINSTATE_ENABLED_NOT_VERIFIED || pinState == PinState.PINSTATE_ENABLED_VERIFIED || pinState == PinState.PINSTATE_ENABLED_BLOCKED || pinState == PinState.PINSTATE_ENABLED_PERM_BLOCKED;*/ } /** * Check whether ICC fdn (fixed dialing number) is enabled * This is a sync call which returns the cached pin enabled state * * @return true for ICC fdn enabled * false for ICC fdn disabled */ public boolean getIccFdnEnabled() { synchronized (mLock) { return mIccFdnEnabled; } } /** * Set the ICC pin lock enabled or disabled * When the operation is complete, onComplete will be sent to its handler * * @param enabled "true" for locked "false" for unlocked. * @param password needed to change the ICC pin state, aka. Pin1 * @param onComplete * onComplete.obj will be an AsyncResult * ((AsyncResult)onComplete.obj).exception == null on success * ((AsyncResult)onComplete.obj).exception != null on fail */ public void setIccLockEnabled (boolean enabled, String password, Message onComplete) { synchronized (mLock) { int serviceClassX; serviceClassX = CommandsInterface.SERVICE_CLASS_VOICE + CommandsInterface.SERVICE_CLASS_DATA + CommandsInterface.SERVICE_CLASS_FAX; mDesiredPinLocked = enabled; mCi.setFacilityLockForApp(CommandsInterface.CB_FACILITY_BA_SIM, enabled, password, serviceClassX, mAid, mHandler.obtainMessage(EVENT_CHANGE_FACILITY_LOCK_DONE, onComplete)); } } /** * Set the ICC fdn enabled or disabled * When the operation is complete, onComplete will be sent to its handler * * @param enabled "true" for locked "false" for unlocked. * @param password needed to change the ICC fdn enable, aka Pin2 * @param onComplete * onComplete.obj will be an AsyncResult * ((AsyncResult)onComplete.obj).exception == null on success * ((AsyncResult)onComplete.obj).exception != null on fail */ public void setIccFdnEnabled (boolean enabled, String password, Message onComplete) { synchronized (mLock) { int serviceClassX; serviceClassX = CommandsInterface.SERVICE_CLASS_VOICE + CommandsInterface.SERVICE_CLASS_DATA + CommandsInterface.SERVICE_CLASS_FAX + CommandsInterface.SERVICE_CLASS_SMS; mDesiredFdnEnabled = enabled; mCi.setFacilityLockForApp(CommandsInterface.CB_FACILITY_BA_FD, enabled, password, serviceClassX, mAid, mHandler.obtainMessage(EVENT_CHANGE_FACILITY_FDN_DONE, onComplete)); } } /** * Change the ICC password used in ICC pin lock * When the operation is complete, onComplete will be sent to its handler * * @param oldPassword is the old password * @param newPassword is the new password * @param onComplete * onComplete.obj will be an AsyncResult * ((AsyncResult)onComplete.obj).exception == null on success * ((AsyncResult)onComplete.obj).exception != null on fail */ public void changeIccLockPassword(String oldPassword, String newPassword, Message onComplete) { synchronized (mLock) { if (DBG) log("changeIccLockPassword"); mCi.changeIccPinForApp(oldPassword, newPassword, mAid, onComplete); } } /** * Change the ICC password used in ICC fdn enable * When the operation is complete, onComplete will be sent to its handler * * @param oldPassword is the old password * @param newPassword is the new password * @param onComplete * onComplete.obj will be an AsyncResult * ((AsyncResult)onComplete.obj).exception == null on success * ((AsyncResult)onComplete.obj).exception != null on fail */ public void changeIccFdnPassword(String oldPassword, String newPassword, Message onComplete) { synchronized (mLock) { if (DBG) log("changeIccFdnPassword"); mCi.changeIccPin2ForApp(oldPassword, newPassword, mAid, onComplete); } } private void log(String msg) { Log.d(LOG_TAG, msg); } private void loge(String msg) { Log.e(LOG_TAG, msg); } }
true
true
void update (IccCardApplicationStatus as, Context c, CommandsInterface ci) { synchronized (mLock) { if (mDestroyed) { loge("Application updated after destroyed! Fix me!"); return; } if (DBG) log(mAppType + " update. New " + as); mContext = c; mCi = ci; AppType oldAppType = mAppType; AppState oldAppState = mAppState; PersoSubState oldPersoSubState = mPersoSubState; mAppType = as.app_type; mAppState = as.app_state; mPersoSubState = as.perso_substate; mAid = as.aid; mAppLabel = as.app_label; mPin1Replaced = (as.pin1_replaced != 0); mPin1State = as.pin1; mPin2State = as.pin2; if (mAppType != oldAppType) { mIccFh.dispose(); mIccRecords.dispose(); mIccFh = createIccFileHandler(as.app_type); mIccRecords = createIccRecords(as.app_type, c, ci); } if (mPersoSubState != oldPersoSubState && mPersoSubState == PersoSubState.PERSOSUBSTATE_SIM_NETWORK) { notifyNetworkLockedRegistrantsIfNeeded(null); } if (mAppState != oldAppState) { if (DBG) log(oldAppType + " changed state: " + oldAppState + " -> " + mAppState); // If the app state turns to APPSTATE_READY, then query FDN status, //as it might have failed in earlier attempt. if (mAppState == AppState.APPSTATE_READY) { queryFdn(); queryPin1State(); } notifyPinLockedRegistrantsIfNeeded(null); notifyReadyRegistrantsIfNeeded(null); } } }
void update (IccCardApplicationStatus as, Context c, CommandsInterface ci) { synchronized (mLock) { if (mDestroyed) { loge("Application updated after destroyed! Fix me!"); return; } if (DBG) log(mAppType + " update. New " + as); mContext = c; mCi = ci; AppType oldAppType = mAppType; AppState oldAppState = mAppState; PersoSubState oldPersoSubState = mPersoSubState; mAppType = as.app_type; mAppState = as.app_state; mPersoSubState = as.perso_substate; mAid = as.aid; mAppLabel = as.app_label; mPin1Replaced = (as.pin1_replaced != 0); mPin1State = as.pin1; mPin2State = as.pin2; if (mAppType != oldAppType) { if (mIccFh != null) { mIccFh.dispose();} if (mIccRecords != null) { mIccRecords.dispose();} mIccFh = createIccFileHandler(as.app_type); mIccRecords = createIccRecords(as.app_type, c, ci); } if (mPersoSubState != oldPersoSubState && mPersoSubState == PersoSubState.PERSOSUBSTATE_SIM_NETWORK) { notifyNetworkLockedRegistrantsIfNeeded(null); } if (mAppState != oldAppState) { if (DBG) log(oldAppType + " changed state: " + oldAppState + " -> " + mAppState); // If the app state turns to APPSTATE_READY, then query FDN status, //as it might have failed in earlier attempt. if (mAppState == AppState.APPSTATE_READY) { queryFdn(); queryPin1State(); } notifyPinLockedRegistrantsIfNeeded(null); notifyReadyRegistrantsIfNeeded(null); } } }
diff --git a/proxy/src/main/java/net/md_5/bungee/ServerConnection.java b/proxy/src/main/java/net/md_5/bungee/ServerConnection.java index 9c69902e..eaa81183 100644 --- a/proxy/src/main/java/net/md_5/bungee/ServerConnection.java +++ b/proxy/src/main/java/net/md_5/bungee/ServerConnection.java @@ -1,132 +1,137 @@ package net.md_5.bungee; import java.net.InetSocketAddress; import java.net.Socket; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import lombok.Getter; import net.md_5.bungee.api.Callback; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ServerPing; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.Server; import net.md_5.bungee.api.event.ServerConnectedEvent; import net.md_5.bungee.packet.DefinedPacket; import net.md_5.bungee.packet.Packet1Login; import net.md_5.bungee.packet.Packet2Handshake; import net.md_5.bungee.packet.PacketCDClientStatus; import net.md_5.bungee.packet.PacketFAPluginMessage; import net.md_5.bungee.packet.PacketFFKick; import net.md_5.bungee.packet.PacketStream; import net.md_5.mendax.PacketDefinitions; /** * Class representing a connection from the proxy to the server; ie upstream. */ public class ServerConnection extends GenericConnection implements Server { @Getter private final ServerInfo info; public final Packet1Login loginPacket; public Queue<DefinedPacket> packetQueue = new ConcurrentLinkedQueue<>(); public ServerConnection(Socket socket, ServerInfo info, PacketStream stream, Packet1Login loginPacket) { super( socket, stream ); this.info = info; this.loginPacket = loginPacket; } public static ServerConnection connect(UserConnection user, ServerInfo info, Packet2Handshake handshake, boolean retry) { try { Socket socket = new Socket(); socket.connect( info.getAddress(), BungeeCord.getInstance().config.getTimeout() ); BungeeCord.getInstance().setSocketOptions( socket ); PacketStream stream = new PacketStream( socket.getInputStream(), socket.getOutputStream(), user.stream.getProtocol() ); if ( user.forgeLogin != null ) { stream.write( user.forgeLogin ); } stream.write( handshake ); stream.write( PacketCDClientStatus.CLIENT_LOGIN ); stream.readPacket(); byte[] loginResponse = null; + boolean forgeIHateYou = false; loop: while ( true ) { loginResponse = stream.readPacket(); int id = Util.getId( loginResponse ); switch ( id ) { case 0x01: break loop; case 0xFA: - for ( PacketFAPluginMessage message : user.loginMessages ) + if ( !forgeIHateYou ) { - stream.write( message ); + for ( PacketFAPluginMessage message : user.loginMessages ) + { + stream.write( message ); + } + forgeIHateYou = true; } break; case 0xFF: throw new KickException( "[Kicked] " + new PacketFFKick( loginResponse ).message ); default: throw new IllegalArgumentException( "Unknown login packet " + Util.hex( id ) ); } } Packet1Login login = new Packet1Login( loginResponse ); ServerConnection server = new ServerConnection( socket, info, stream, login ); ServerConnectedEvent event = new ServerConnectedEvent( user, server ); ProxyServer.getInstance().getPluginManager().callEvent( event ); stream.write( BungeeCord.getInstance().registerChannels() ); Queue<DefinedPacket> packetQueue = ( (BungeeServerInfo) info ).getPacketQueue(); while ( !packetQueue.isEmpty() ) { stream.write( packetQueue.poll() ); } return server; } catch ( KickException ex ) { throw ex; } catch ( Exception ex ) { ServerInfo def = ProxyServer.getInstance().getServers().get( user.getPendingConnection().getListener().getDefaultServer() ); if ( retry && !info.equals( def ) ) { user.sendMessage( ChatColor.RED + "Could not connect to target server, you have been moved to the default server" ); return connect( user, def, handshake, false ); } else { throw new RuntimeException( "Could not connect to target server " + Util.exception( ex ) ); } } } @Override public void sendData(String channel, byte[] data) { packetQueue.add( new PacketFAPluginMessage( channel, data ) ); } @Override public void ping(final Callback<ServerPing> callback) { getInfo().ping( callback ); } @Override public InetSocketAddress getAddress() { return getInfo().getAddress(); } }
false
true
public static ServerConnection connect(UserConnection user, ServerInfo info, Packet2Handshake handshake, boolean retry) { try { Socket socket = new Socket(); socket.connect( info.getAddress(), BungeeCord.getInstance().config.getTimeout() ); BungeeCord.getInstance().setSocketOptions( socket ); PacketStream stream = new PacketStream( socket.getInputStream(), socket.getOutputStream(), user.stream.getProtocol() ); if ( user.forgeLogin != null ) { stream.write( user.forgeLogin ); } stream.write( handshake ); stream.write( PacketCDClientStatus.CLIENT_LOGIN ); stream.readPacket(); byte[] loginResponse = null; loop: while ( true ) { loginResponse = stream.readPacket(); int id = Util.getId( loginResponse ); switch ( id ) { case 0x01: break loop; case 0xFA: for ( PacketFAPluginMessage message : user.loginMessages ) { stream.write( message ); } break; case 0xFF: throw new KickException( "[Kicked] " + new PacketFFKick( loginResponse ).message ); default: throw new IllegalArgumentException( "Unknown login packet " + Util.hex( id ) ); } } Packet1Login login = new Packet1Login( loginResponse ); ServerConnection server = new ServerConnection( socket, info, stream, login ); ServerConnectedEvent event = new ServerConnectedEvent( user, server ); ProxyServer.getInstance().getPluginManager().callEvent( event ); stream.write( BungeeCord.getInstance().registerChannels() ); Queue<DefinedPacket> packetQueue = ( (BungeeServerInfo) info ).getPacketQueue(); while ( !packetQueue.isEmpty() ) { stream.write( packetQueue.poll() ); } return server; } catch ( KickException ex ) { throw ex; } catch ( Exception ex ) { ServerInfo def = ProxyServer.getInstance().getServers().get( user.getPendingConnection().getListener().getDefaultServer() ); if ( retry && !info.equals( def ) ) { user.sendMessage( ChatColor.RED + "Could not connect to target server, you have been moved to the default server" ); return connect( user, def, handshake, false ); } else { throw new RuntimeException( "Could not connect to target server " + Util.exception( ex ) ); } } }
public static ServerConnection connect(UserConnection user, ServerInfo info, Packet2Handshake handshake, boolean retry) { try { Socket socket = new Socket(); socket.connect( info.getAddress(), BungeeCord.getInstance().config.getTimeout() ); BungeeCord.getInstance().setSocketOptions( socket ); PacketStream stream = new PacketStream( socket.getInputStream(), socket.getOutputStream(), user.stream.getProtocol() ); if ( user.forgeLogin != null ) { stream.write( user.forgeLogin ); } stream.write( handshake ); stream.write( PacketCDClientStatus.CLIENT_LOGIN ); stream.readPacket(); byte[] loginResponse = null; boolean forgeIHateYou = false; loop: while ( true ) { loginResponse = stream.readPacket(); int id = Util.getId( loginResponse ); switch ( id ) { case 0x01: break loop; case 0xFA: if ( !forgeIHateYou ) { for ( PacketFAPluginMessage message : user.loginMessages ) { stream.write( message ); } forgeIHateYou = true; } break; case 0xFF: throw new KickException( "[Kicked] " + new PacketFFKick( loginResponse ).message ); default: throw new IllegalArgumentException( "Unknown login packet " + Util.hex( id ) ); } } Packet1Login login = new Packet1Login( loginResponse ); ServerConnection server = new ServerConnection( socket, info, stream, login ); ServerConnectedEvent event = new ServerConnectedEvent( user, server ); ProxyServer.getInstance().getPluginManager().callEvent( event ); stream.write( BungeeCord.getInstance().registerChannels() ); Queue<DefinedPacket> packetQueue = ( (BungeeServerInfo) info ).getPacketQueue(); while ( !packetQueue.isEmpty() ) { stream.write( packetQueue.poll() ); } return server; } catch ( KickException ex ) { throw ex; } catch ( Exception ex ) { ServerInfo def = ProxyServer.getInstance().getServers().get( user.getPendingConnection().getListener().getDefaultServer() ); if ( retry && !info.equals( def ) ) { user.sendMessage( ChatColor.RED + "Could not connect to target server, you have been moved to the default server" ); return connect( user, def, handshake, false ); } else { throw new RuntimeException( "Could not connect to target server " + Util.exception( ex ) ); } } }
diff --git a/src/web/api/src/main/java/org/geogit/web/api/commands/FeatureDiffWeb.java b/src/web/api/src/main/java/org/geogit/web/api/commands/FeatureDiffWeb.java index 8493c988..0e38897b 100644 --- a/src/web/api/src/main/java/org/geogit/web/api/commands/FeatureDiffWeb.java +++ b/src/web/api/src/main/java/org/geogit/web/api/commands/FeatureDiffWeb.java @@ -1,261 +1,261 @@ package org.geogit.web.api.commands; import java.util.HashMap; import java.util.Map; import org.geogit.api.GeoGIT; import org.geogit.api.NodeRef; import org.geogit.api.ObjectId; import org.geogit.api.Ref; import org.geogit.api.RevCommit; import org.geogit.api.RevFeature; import org.geogit.api.RevFeatureType; import org.geogit.api.RevObject; import org.geogit.api.RevTree; import org.geogit.api.plumbing.FindTreeChild; import org.geogit.api.plumbing.ResolveTreeish; import org.geogit.api.plumbing.RevObjectParse; import org.geogit.api.plumbing.diff.AttributeDiff; import org.geogit.api.plumbing.diff.FeatureDiff; import org.geogit.api.plumbing.diff.GenericAttributeDiffImpl; import org.geogit.api.plumbing.diff.GeometryAttributeDiff; import org.geogit.web.api.CommandContext; import org.geogit.web.api.CommandResponse; import org.geogit.web.api.CommandSpecException; import org.geogit.web.api.ResponseWriter; import org.geogit.web.api.WebAPICommand; import org.opengis.feature.type.PropertyDescriptor; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.vividsolutions.jts.geom.Geometry; /** * This is the interface for the FeatureDiff command. It is used by passing a path to a feature, an * oldCommitId and a newCommitId. It returns the differences in the attributes of a feature between * the two supplied commits. * * Web interface for {@link FeatureDiff} */ public class FeatureDiffWeb implements WebAPICommand { private String path; private String newCommitId; private String oldCommitId; private boolean all; /** * Mutator of the path variable * * @param path - the path to the feature */ public void setPath(String path) { this.path = path; } /** * Mutator for the newCommitId * * @param newCommitId - the id of the newer commit */ public void setNewCommitId(String newCommitId) { this.newCommitId = newCommitId; } /** * Mutator for the oldCommitId * * @param oldCommitId - the id of the older commit */ public void setOldCommitId(String oldCommitId) { this.oldCommitId = oldCommitId; } /** * Mutator for all attributes bool * * @param all - true to show all attributes not just changed ones */ public void setAll(boolean all) { this.all = all; } /** * Helper function to parse the given commit id's feature information * * @param id - the id to parse out * @param geogit - an instance of geogit to run commands with * @return (Optional)NodeRef - the NodeRef that contains the metadata id and id needed to get * the feature and featuretype * * @throws CommandSpecException - if the commit or treeid couldn't be resolved */ private Optional<NodeRef> parseID(ObjectId id, GeoGIT geogit) { Optional<RevObject> object = geogit.command(RevObjectParse.class).setObjectId(id).call(); RevCommit commit = null; if (object.isPresent() && object.get() instanceof RevCommit) { commit = (RevCommit) object.get(); } else { throw new CommandSpecException("Couldn't resolve id: " + id.toString() + " to a commit"); } object = geogit.command(RevObjectParse.class).setObjectId(commit.getTreeId()).call(); if (object.isPresent()) { RevTree tree = (RevTree) object.get(); return geogit.command(FindTreeChild.class).setParent(tree).setChildPath(path).call(); } else { throw new CommandSpecException("Couldn't resolve commit's treeId"); } } /** * Runs the command and builds the appropriate response * * @throws CommandSpecException */ @Override public void run(CommandContext context) { if (path == null || path.trim().isEmpty()) { throw new CommandSpecException("No path for feature name specifed"); } ObjectId newId = null; final GeoGIT geogit = context.getGeoGIT(); if (newCommitId.equals(ObjectId.NULL.toString()) || newCommitId.trim().isEmpty()) { Optional<ObjectId> oid = geogit.command(ResolveTreeish.class).setTreeish(Ref.HEAD) .call(); if (oid.isPresent()) { newId = oid.get(); } else { throw new CommandSpecException("Something went wrong, couldn't resolve HEAD"); } } else { newId = ObjectId.valueOf(newCommitId); } ObjectId oldId = ObjectId.valueOf(oldCommitId); RevFeature newFeature = null; RevFeatureType newFeatureType = null; RevFeature oldFeature = null; RevFeatureType oldFeatureType = null; final Map<PropertyDescriptor, AttributeDiff> diffs; Optional<NodeRef> ref = parseID(newId, geogit); Optional<RevObject> object; // need these to determine if the feature was added or removed so I can build the diffs // myself until the FeatureDiff supports null values boolean removed = false; boolean added = false; if (ref.isPresent()) { object = geogit.command(RevObjectParse.class).setObjectId(ref.get().getMetadataId()) .call(); if (object.isPresent() && object.get() instanceof RevFeatureType) { newFeatureType = (RevFeatureType) object.get(); } else { throw new CommandSpecException("Couldn't resolve newCommit's featureType"); } object = geogit.command(RevObjectParse.class).setObjectId(ref.get().objectId()).call(); if (object.isPresent() && object.get() instanceof RevFeature) { newFeature = (RevFeature) object.get(); } else { throw new CommandSpecException("Couldn't resolve newCommit's feature"); } } else { removed = true; } if (!oldId.equals(ObjectId.NULL)) { ref = parseID(oldId, geogit); if (ref.isPresent()) { object = geogit.command(RevObjectParse.class) .setObjectId(ref.get().getMetadataId()).call(); if (object.isPresent() && object.get() instanceof RevFeatureType) { oldFeatureType = (RevFeatureType) object.get(); } else { throw new CommandSpecException("Couldn't resolve oldCommit's featureType"); } object = geogit.command(RevObjectParse.class).setObjectId(ref.get().objectId()) .call(); if (object.isPresent() && object.get() instanceof RevFeature) { oldFeature = (RevFeature) object.get(); } else { throw new CommandSpecException("Couldn't resolve oldCommit's feature"); } } else { added = true; } } else { added = true; } if (removed) { Map<PropertyDescriptor, AttributeDiff> tempDiffs = new HashMap<PropertyDescriptor, AttributeDiff>(); ImmutableList<PropertyDescriptor> attributes = oldFeatureType.sortedDescriptors(); ImmutableList<Optional<Object>> values = oldFeature.getValues(); for (int index = 0; index < attributes.size(); index++) { Optional<Object> value = values.get(index); if (Geometry.class.isAssignableFrom(attributes.get(index).getType().getBinding())) { Optional<Geometry> temp = Optional.absent(); - if (value.isPresent()) { + if (value.isPresent() || all) { tempDiffs.put( attributes.get(index), new GeometryAttributeDiff(Optional.fromNullable((Geometry) value .orNull()), temp)); } } else { - if (value.isPresent()) { + if (value.isPresent() || all) { tempDiffs.put(attributes.get(index), new GenericAttributeDiffImpl(value, Optional.absent())); } } } diffs = tempDiffs; } else if (added) { Map<PropertyDescriptor, AttributeDiff> tempDiffs = new HashMap<PropertyDescriptor, AttributeDiff>(); ImmutableList<PropertyDescriptor> attributes = newFeatureType.sortedDescriptors(); ImmutableList<Optional<Object>> values = newFeature.getValues(); for (int index = 0; index < attributes.size(); index++) { Optional<Object> value = values.get(index); if (Geometry.class.isAssignableFrom(attributes.get(index).getType().getBinding())) { Optional<Geometry> temp = Optional.absent(); - if (value.isPresent()) { + if (value.isPresent() || all) { tempDiffs.put(attributes.get(index), new GeometryAttributeDiff(temp, Optional.fromNullable((Geometry) value.orNull()))); } } else { - if (value.isPresent()) { + if (value.isPresent() || all) { tempDiffs.put(attributes.get(index), new GenericAttributeDiffImpl(Optional.absent(), value)); } } } diffs = tempDiffs; } else { FeatureDiff diff = new FeatureDiff(path, newFeature, oldFeature, newFeatureType, oldFeatureType, all); diffs = diff.getDiffs(); } context.setResponseContent(new CommandResponse() { @Override public void write(ResponseWriter out) throws Exception { out.start(); out.writeFeatureDiffResponse(diffs); out.finish(); } }); } }
false
true
public void run(CommandContext context) { if (path == null || path.trim().isEmpty()) { throw new CommandSpecException("No path for feature name specifed"); } ObjectId newId = null; final GeoGIT geogit = context.getGeoGIT(); if (newCommitId.equals(ObjectId.NULL.toString()) || newCommitId.trim().isEmpty()) { Optional<ObjectId> oid = geogit.command(ResolveTreeish.class).setTreeish(Ref.HEAD) .call(); if (oid.isPresent()) { newId = oid.get(); } else { throw new CommandSpecException("Something went wrong, couldn't resolve HEAD"); } } else { newId = ObjectId.valueOf(newCommitId); } ObjectId oldId = ObjectId.valueOf(oldCommitId); RevFeature newFeature = null; RevFeatureType newFeatureType = null; RevFeature oldFeature = null; RevFeatureType oldFeatureType = null; final Map<PropertyDescriptor, AttributeDiff> diffs; Optional<NodeRef> ref = parseID(newId, geogit); Optional<RevObject> object; // need these to determine if the feature was added or removed so I can build the diffs // myself until the FeatureDiff supports null values boolean removed = false; boolean added = false; if (ref.isPresent()) { object = geogit.command(RevObjectParse.class).setObjectId(ref.get().getMetadataId()) .call(); if (object.isPresent() && object.get() instanceof RevFeatureType) { newFeatureType = (RevFeatureType) object.get(); } else { throw new CommandSpecException("Couldn't resolve newCommit's featureType"); } object = geogit.command(RevObjectParse.class).setObjectId(ref.get().objectId()).call(); if (object.isPresent() && object.get() instanceof RevFeature) { newFeature = (RevFeature) object.get(); } else { throw new CommandSpecException("Couldn't resolve newCommit's feature"); } } else { removed = true; } if (!oldId.equals(ObjectId.NULL)) { ref = parseID(oldId, geogit); if (ref.isPresent()) { object = geogit.command(RevObjectParse.class) .setObjectId(ref.get().getMetadataId()).call(); if (object.isPresent() && object.get() instanceof RevFeatureType) { oldFeatureType = (RevFeatureType) object.get(); } else { throw new CommandSpecException("Couldn't resolve oldCommit's featureType"); } object = geogit.command(RevObjectParse.class).setObjectId(ref.get().objectId()) .call(); if (object.isPresent() && object.get() instanceof RevFeature) { oldFeature = (RevFeature) object.get(); } else { throw new CommandSpecException("Couldn't resolve oldCommit's feature"); } } else { added = true; } } else { added = true; } if (removed) { Map<PropertyDescriptor, AttributeDiff> tempDiffs = new HashMap<PropertyDescriptor, AttributeDiff>(); ImmutableList<PropertyDescriptor> attributes = oldFeatureType.sortedDescriptors(); ImmutableList<Optional<Object>> values = oldFeature.getValues(); for (int index = 0; index < attributes.size(); index++) { Optional<Object> value = values.get(index); if (Geometry.class.isAssignableFrom(attributes.get(index).getType().getBinding())) { Optional<Geometry> temp = Optional.absent(); if (value.isPresent()) { tempDiffs.put( attributes.get(index), new GeometryAttributeDiff(Optional.fromNullable((Geometry) value .orNull()), temp)); } } else { if (value.isPresent()) { tempDiffs.put(attributes.get(index), new GenericAttributeDiffImpl(value, Optional.absent())); } } } diffs = tempDiffs; } else if (added) { Map<PropertyDescriptor, AttributeDiff> tempDiffs = new HashMap<PropertyDescriptor, AttributeDiff>(); ImmutableList<PropertyDescriptor> attributes = newFeatureType.sortedDescriptors(); ImmutableList<Optional<Object>> values = newFeature.getValues(); for (int index = 0; index < attributes.size(); index++) { Optional<Object> value = values.get(index); if (Geometry.class.isAssignableFrom(attributes.get(index).getType().getBinding())) { Optional<Geometry> temp = Optional.absent(); if (value.isPresent()) { tempDiffs.put(attributes.get(index), new GeometryAttributeDiff(temp, Optional.fromNullable((Geometry) value.orNull()))); } } else { if (value.isPresent()) { tempDiffs.put(attributes.get(index), new GenericAttributeDiffImpl(Optional.absent(), value)); } } } diffs = tempDiffs; } else { FeatureDiff diff = new FeatureDiff(path, newFeature, oldFeature, newFeatureType, oldFeatureType, all); diffs = diff.getDiffs(); } context.setResponseContent(new CommandResponse() { @Override public void write(ResponseWriter out) throws Exception { out.start(); out.writeFeatureDiffResponse(diffs); out.finish(); } }); }
public void run(CommandContext context) { if (path == null || path.trim().isEmpty()) { throw new CommandSpecException("No path for feature name specifed"); } ObjectId newId = null; final GeoGIT geogit = context.getGeoGIT(); if (newCommitId.equals(ObjectId.NULL.toString()) || newCommitId.trim().isEmpty()) { Optional<ObjectId> oid = geogit.command(ResolveTreeish.class).setTreeish(Ref.HEAD) .call(); if (oid.isPresent()) { newId = oid.get(); } else { throw new CommandSpecException("Something went wrong, couldn't resolve HEAD"); } } else { newId = ObjectId.valueOf(newCommitId); } ObjectId oldId = ObjectId.valueOf(oldCommitId); RevFeature newFeature = null; RevFeatureType newFeatureType = null; RevFeature oldFeature = null; RevFeatureType oldFeatureType = null; final Map<PropertyDescriptor, AttributeDiff> diffs; Optional<NodeRef> ref = parseID(newId, geogit); Optional<RevObject> object; // need these to determine if the feature was added or removed so I can build the diffs // myself until the FeatureDiff supports null values boolean removed = false; boolean added = false; if (ref.isPresent()) { object = geogit.command(RevObjectParse.class).setObjectId(ref.get().getMetadataId()) .call(); if (object.isPresent() && object.get() instanceof RevFeatureType) { newFeatureType = (RevFeatureType) object.get(); } else { throw new CommandSpecException("Couldn't resolve newCommit's featureType"); } object = geogit.command(RevObjectParse.class).setObjectId(ref.get().objectId()).call(); if (object.isPresent() && object.get() instanceof RevFeature) { newFeature = (RevFeature) object.get(); } else { throw new CommandSpecException("Couldn't resolve newCommit's feature"); } } else { removed = true; } if (!oldId.equals(ObjectId.NULL)) { ref = parseID(oldId, geogit); if (ref.isPresent()) { object = geogit.command(RevObjectParse.class) .setObjectId(ref.get().getMetadataId()).call(); if (object.isPresent() && object.get() instanceof RevFeatureType) { oldFeatureType = (RevFeatureType) object.get(); } else { throw new CommandSpecException("Couldn't resolve oldCommit's featureType"); } object = geogit.command(RevObjectParse.class).setObjectId(ref.get().objectId()) .call(); if (object.isPresent() && object.get() instanceof RevFeature) { oldFeature = (RevFeature) object.get(); } else { throw new CommandSpecException("Couldn't resolve oldCommit's feature"); } } else { added = true; } } else { added = true; } if (removed) { Map<PropertyDescriptor, AttributeDiff> tempDiffs = new HashMap<PropertyDescriptor, AttributeDiff>(); ImmutableList<PropertyDescriptor> attributes = oldFeatureType.sortedDescriptors(); ImmutableList<Optional<Object>> values = oldFeature.getValues(); for (int index = 0; index < attributes.size(); index++) { Optional<Object> value = values.get(index); if (Geometry.class.isAssignableFrom(attributes.get(index).getType().getBinding())) { Optional<Geometry> temp = Optional.absent(); if (value.isPresent() || all) { tempDiffs.put( attributes.get(index), new GeometryAttributeDiff(Optional.fromNullable((Geometry) value .orNull()), temp)); } } else { if (value.isPresent() || all) { tempDiffs.put(attributes.get(index), new GenericAttributeDiffImpl(value, Optional.absent())); } } } diffs = tempDiffs; } else if (added) { Map<PropertyDescriptor, AttributeDiff> tempDiffs = new HashMap<PropertyDescriptor, AttributeDiff>(); ImmutableList<PropertyDescriptor> attributes = newFeatureType.sortedDescriptors(); ImmutableList<Optional<Object>> values = newFeature.getValues(); for (int index = 0; index < attributes.size(); index++) { Optional<Object> value = values.get(index); if (Geometry.class.isAssignableFrom(attributes.get(index).getType().getBinding())) { Optional<Geometry> temp = Optional.absent(); if (value.isPresent() || all) { tempDiffs.put(attributes.get(index), new GeometryAttributeDiff(temp, Optional.fromNullable((Geometry) value.orNull()))); } } else { if (value.isPresent() || all) { tempDiffs.put(attributes.get(index), new GenericAttributeDiffImpl(Optional.absent(), value)); } } } diffs = tempDiffs; } else { FeatureDiff diff = new FeatureDiff(path, newFeature, oldFeature, newFeatureType, oldFeatureType, all); diffs = diff.getDiffs(); } context.setResponseContent(new CommandResponse() { @Override public void write(ResponseWriter out) throws Exception { out.start(); out.writeFeatureDiffResponse(diffs); out.finish(); } }); }
diff --git a/src/org/mustard/android/activity/MustardBaseActivity.java b/src/org/mustard/android/activity/MustardBaseActivity.java index e32c4e6..d1a72c8 100644 --- a/src/org/mustard/android/activity/MustardBaseActivity.java +++ b/src/org/mustard/android/activity/MustardBaseActivity.java @@ -1,2313 +1,2313 @@ /* * MUSTARD: Android's Client for StatusNet * * Copyright (C) 2009-2010 macno.org, Michele Azzolari * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package org.mustard.android.activity; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.mustard.android.Controller; import org.mustard.android.MessagingListener; import org.mustard.android.MustardApplication; import org.mustard.android.MustardDbAdapter; import org.mustard.android.Preferences; import org.mustard.android.R; import org.mustard.android.provider.StatusNet; import org.mustard.android.view.GimmeMoreListView; import org.mustard.android.view.MustardStatusTextView; import org.mustard.android.view.RemoteImageView; import org.mustard.geonames.GeoName; import org.mustard.statusnet.Attachment; import org.mustard.util.DateUtils; import org.mustard.util.MustardException; import org.mustard.util.StatusNetUtils; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.app.ProgressDialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.AsyncTask.Status; import android.preference.PreferenceManager; import android.text.ClipboardManager; import android.text.Html; import android.text.util.Linkify; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.ContextMenu.ContextMenuInfo; import android.webkit.WebView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.TextView.BufferType; public abstract class MustardBaseActivity extends ListActivity implements GimmeMoreListView.OnNeedMoreListener { protected String TAG="MustardBaseActivity"; protected static final String EXTRA_USER="mustard.user"; protected static final int DIALOG_FETCHING_ID=0; protected static final int DIALOG_OPENING_ID=1; private static final int ACTIVITY_CREATE = 0; private static final int ACTIVITY_EDIT = 1; private static final int ACCOUNT_ADD = 2; private static final int ACCOUNT_DEL = 3; // private static final int ACTIVITY_MENTIONS = 4; private static final int ACCOUNT_ADD_SWITCH = 5; // private static final int ACTIVITY_FRIENDS = 6; // private static final int ACTIVITY_FAVORITES = 7; private static final int ACTIVITY_PUBLIC = 8; private static final int INSERT_ID = 0; private static final int USER_TL_ID = 1; private static final int REPLY_ID = 2; private static final int REPEAT_ID = 3; protected static final int MENTIONS_ID = 4; private static final int PUBLIC_ID = 5; private static final int REFRESH_ID = 6; private static final int LOGOUT_ID = 7; private static final int DELETE_ID = 8; private static final int SWITCH_ID = 9; private static final int SEARCH_ID = 10; private static final int ABOUT_ID = 11; private static final int BACK_ID = 12; private static final int FAVORS_ID = 13; private static final int UNFAVORS_ID = 14; protected static final int SUB_ID = 15; protected static final int UNSUB_ID = 16; protected static final int FAVORITES_ID = 17; protected static final int FRIENDS_ID = 18; private static final int ACCOUNT_SETTINGS_ID = 19; private static final int SETTINGS_ID = 20; private static final int BOOKMARKS_ID = 21; private static final int BOOKMARK_THIS_ID = 22; // private static final int ACCOUNT_MENU_ID = 23; private static final int BLOCK_ID = 24; private static final int GEOLOCATION_ID = 25; protected static final int GROUP_JOIN_ID= 26; protected static final int GROUP_LEAVE_ID= 27; protected static final int M_SUB_ID = 28; protected static final int M_UNSUB_ID = 29; private static final int SHARE_ID = 30; private static final int COPY2CLIPBOARD_ID = 31; protected MustardDbAdapter mDbHelper; private StatusesLoadMore mLoadMoreTask = null; private StatusesFetcher mFetcherTask = null; private boolean mIsRefresh=false; protected boolean mNoMoreDents=false; private String mErrorMessage=""; private long mCurrentRowid = -1; protected StatusNet mStatusNet = null; protected boolean mFromSavedState = false; protected boolean mForceOnlyBackMenu=false; private boolean mIsOnSaveInstanceState=false; protected int DB_ROW_TYPE; protected String DB_ROW_EXTRA; protected String DB_ROW_ORDER = "DESC"; protected int R_ROW_ID=R.layout.timeline_list_item; protected boolean isRefreshEnable=true; protected boolean isBookmarkEnable=true; protected boolean isConversationEnable=true; protected boolean mFromService=false; // private Cursor mNoticesCursor; NoticeListAdapter mNoticeCursorAdapter = null; protected SharedPreferences mPreferences; //private Timer mAutoRefreshTimer ; protected boolean mAutoRefresh=false; protected boolean mLayoutLegacy=false; private boolean mLayoutNewButton=false; private int mTextSizeNormal=14; private int mTextSizeSmall=12; // protected static boolean isMainTimeline = false; class NoticeListAdapter extends SimpleCursorAdapter { private boolean mLoading = true; private int mIdIdx; private int mIdAccountIdx; private int mProfileImageIdx; private int mGeolocationIdx; private int mScreenNameIdx; private int mStatusIdx; private int mStatusIdIdx; private int mDatetimeIdx; private int mSourceIdx; private int mInReplyToIdx; private int mLonIdx; private int mLatIdx; private int mAttachmentIdx; private HashMap<Long, String> hmAccounts; class ViewHolder { RemoteImageView profile_image; ImageButton noticeinfo; ImageButton geolocation; ImageButton conversation; TextView screen_name; TextView account_name; MustardStatusTextView status; TextView datetime; TextView source; MustardStatusTextView in_reply_to; ImageButton attachment; View bottomRow; } /** * @param context * @param layout * @param c * @param from * @param to */ public NoticeListAdapter(Context context, int layout, String[] from, int[] to) { super(context, layout, null, from, to); } public void setLoading(boolean loading) { mLoading = loading; } public View newView(Context context, Cursor cursor, ViewGroup parent) { View v = super.newView(context, cursor, parent); // Log.d(TAG, "newView"); ViewHolder vh = new ViewHolder(); try { vh.profile_image = (RemoteImageView)v.findViewById(R.id.profile_image); } catch (Exception e) { } vh.noticeinfo = (ImageButton)v.findViewById(R.id.noticeinfo); vh.geolocation = (ImageButton)v.findViewById(R.id.geolocation); vh.screen_name = (TextView)v.findViewById(R.id.screen_name); try { vh.account_name = (TextView)v.findViewById(R.id.account_name); } catch (Exception e) { } vh.status = (MustardStatusTextView)v.findViewById(R.id.status); Typeface tf = Typeface.createFromAsset(getAssets(),MustardApplication.MUSTARD_FONT_NAME); vh.status.setTypeface(tf); vh.datetime = (TextView)v.findViewById(R.id.datetime); vh.datetime.setTypeface(tf); vh.source = (TextView)v.findViewById(R.id.source); vh.source.setTypeface(tf); try { vh.bottomRow = (View)v.findViewById(R.id.bottom_row); }catch (Exception e) { } try { vh.conversation = (ImageButton)v.findViewById(R.id.conversation); }catch (Exception e) { } try { vh.in_reply_to = (MustardStatusTextView)v.findViewById(R.id.in_reply_to); vh.in_reply_to.setTypeface(tf); } catch (Exception e) { } vh.attachment = (ImageButton)v.findViewById(R.id.attachment); v.setTag(vh); return v; } public void bindView(final View view, final Context context, Cursor cursor) { ViewHolder vh = (ViewHolder) view.getTag(); if (hmAccounts==null) { hmAccounts = new HashMap<Long,String>(); if (MustardApplication.DEBUG) Log.i(TAG, "############################## CREATO hmAccounts ##########"); } final long id = cursor.getLong(mIdIdx); final long statusId = cursor.getLong(mStatusIdIdx); view.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // openContextMenu(v); onShowNoticeMenu(v,id); } }); view.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { openContextMenu(v); return true; } }); if (MustardApplication.DEBUG) Log.v(TAG, "Binding id=" + id + " " + statusId + " cursor=" + cursor); long accountId = cursor.getLong(mIdAccountIdx); if (vh.screen_name != null) { vh.screen_name.setText(cursor.getString(mScreenNameIdx)); vh.screen_name.setTextSize(mTextSizeSmall); } if ( mMergedTimeline && vh.account_name != null) { if(!hmAccounts.containsKey(accountId)) { Cursor c = mDbHelper.fetchAccount(accountId); String account = ""; if (c.moveToNext()) { account=c.getString(c.getColumnIndex(MustardDbAdapter.KEY_USER)); String instance = c.getString(c.getColumnIndex(MustardDbAdapter.KEY_INSTANCE)); try { URL url = new URL(instance); account += "@" + url.getHost() + url.getPath(); // Log.i(TAG, "AccountID " + accountId + " => " + account + " " + host + " (" +instance +")"); } catch (Exception e) { e.printStackTrace(); } } else { Log.e(TAG,"NO ACCOUNT WITH ID: " + accountId); } c.close(); hmAccounts.put(accountId, account); } vh.account_name.setText(hmAccounts.get(accountId)); vh.account_name.setVisibility(View.VISIBLE); vh.account_name.setTextSize(mTextSizeSmall); } String source = cursor.getString(mSourceIdx) ; if (source != null && !"".equals(source)) { - source = Html.fromHtml("&nbsp;from " + source.replace("&lt;", "<").replace("&gt;", ">"))+" "; - if (source.length()>15) - source = source.substring(0, 15) +".."; + source = Html.fromHtml("&nbsp;from&nbsp;" + source.replace("&lt;", "<").replace("&gt;", ">"))+" "; + if (source.trim().length()>15) + source = source.trim().substring(0, 15) +".."; else source=source.trim(); } vh.source.setText(source, BufferType.SPANNABLE); vh.source.setTextSize(mTextSizeSmall); long inreplyto = cursor.getLong(mInReplyToIdx); TextView vr = vh.in_reply_to; if (vr != null) { if (inreplyto > 0) { vr.setText(Html.fromHtml("&nbsp;<a href='statusnet://conversation/"+id+"' >in context</a>") , BufferType.SPANNABLE); vr.setVisibility(View.VISIBLE); vr.setTextSize(mTextSizeSmall); } else { vr.setVisibility(View.GONE); } } if (vh.profile_image != null) { String profileUrl = cursor.getString(mProfileImageIdx); if (profileUrl != null && !"".equals(profileUrl)) { vh.profile_image.setRemoteURI(profileUrl); vh.profile_image.loadImage(); } if(mLayoutNewButton) { vh.profile_image.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { openContextMenu(v); } }); } vh.profile_image.setFocusable(mLayoutNewButton); } Date d = new Date(); d.setTime(cursor.getLong(mDatetimeIdx)); vh.datetime.setText(DateUtils.getRelativeDate( d )); vh.datetime.setTextSize(mTextSizeSmall); if(mPreferences.getBoolean(Preferences.COMPACT_VIEW, false) ) { if (vh.bottomRow!=null) vh.bottomRow.setVisibility(View.GONE); } else { if(vh.conversation != null) { if (inreplyto > 0) { vh.conversation.setImageResource(R.drawable.conversation); vh.conversation.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // doOpenConversation(statusId); doOpenConversation(id); } }); } else { vh.conversation.setImageResource(R.drawable.conversation_disabled); } vh.conversation.setFocusable(mLayoutNewButton); } int geo = cursor.getInt(mGeolocationIdx); if (geo == 1) { final String lon = cursor.getString(mLonIdx); final String lat = cursor.getString(mLatIdx); vh.geolocation.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { doShowLocation(lon, lat); } }); vh.geolocation.setImageResource(R.drawable.pin_button); } else { vh.geolocation.setImageResource(R.drawable.pin_disabled); } vh.geolocation.setFocusable(mLayoutNewButton); int attachment = cursor.getInt(mAttachmentIdx); if (attachment == 1) { vh.attachment.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { onShowAttachemntList(id); } }); vh.attachment.setImageResource(R.drawable.attachment); } else { vh.attachment.setImageResource(R.drawable.attachment_disabled); } vh.attachment.setFocusable(mLayoutNewButton); } String status = cursor.getString(mStatusIdx); if (status.indexOf("<")>=0) status=status.replaceAll("<", "&lt;"); if(status.indexOf(">")>=0) status=status.replaceAll(">","&gt;"); TextView v = vh.status; v.setText(Html.fromHtml(status).toString(), BufferType.SPANNABLE); Linkify.addLinks(v, Linkify.WEB_URLS); StatusNetUtils.linkifyUsers(v); if(mStatusNet.isTwitterInstance()) { StatusNetUtils.linkifyGroupsForTwitter(v); StatusNetUtils.linkifyTagsForTwitter(v); } else { StatusNetUtils.linkifyGroups(v); StatusNetUtils.linkifyTags(v); } v.setTextSize(mTextSizeNormal); if (vh.noticeinfo !=null) { if(mLayoutNewButton) { vh.noticeinfo.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { onShowNoticeAction(id); } }); } else { vh.noticeinfo.setVisibility(View.GONE); } vh.noticeinfo.setFocusable(mLayoutNewButton); } } public void changeCursor(Cursor cursor) { super.changeCursor(cursor); // Log.v(TAG, "Setting cursor to: " + cursor + " from: " + TimelineNoticeList.this.mCursor); if (cursor != null) { mIdIdx = cursor.getColumnIndex(MustardDbAdapter.KEY_ROWID); mIdAccountIdx = cursor.getColumnIndex(MustardDbAdapter.KEY_ACCOUNT_ID); mGeolocationIdx = cursor.getColumnIndex(MustardDbAdapter.KEY_GEO); mScreenNameIdx = cursor.getColumnIndex(MustardDbAdapter.KEY_SCREEN_NAME); mStatusIdx = cursor.getColumnIndex(MustardDbAdapter.KEY_STATUS); mStatusIdIdx = cursor.getColumnIndex(MustardDbAdapter.KEY_STATUS_ID); mDatetimeIdx = cursor.getColumnIndex(MustardDbAdapter.KEY_INSERT_AT); mSourceIdx = cursor.getColumnIndex(MustardDbAdapter.KEY_SOURCE); mInReplyToIdx = cursor.getColumnIndex(MustardDbAdapter.KEY_IN_REPLY_TO); mProfileImageIdx = cursor.getColumnIndex(MustardDbAdapter.KEY_USER_IMAGE); mLonIdx = cursor.getColumnIndex(MustardDbAdapter.KEY_LON); mLatIdx = cursor.getColumnIndex(MustardDbAdapter.KEY_LAT); mAttachmentIdx = cursor.getColumnIndex(MustardDbAdapter.KEY_ATTACHMENT); } else { Log.v(TAG, "Cursor is null "); } } public boolean isEmpty() { if (mLoading) { // We don't want the empty state to show when loading. return false; } else { return super.isEmpty(); } } } private void onShowNoticeMenu(View v,final long id) { Cursor c = mDbHelper.fetchStatus(id); BitmapDrawable _icon = new BitmapDrawable( MustardApplication.sImageManager.get( c.getString( c.getColumnIndexOrThrow(MustardDbAdapter.KEY_USER_IMAGE) ) ) ); String userName = c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_SCREEN_NAME)); boolean favorited = c.getInt(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_FAVORITE)) == 1 ? true : false; long in_reply_to = c.getLong(c.getColumnIndex(MustardDbAdapter.KEY_IN_REPLY_TO)); int geo = c.getInt(c.getColumnIndex(MustardDbAdapter.KEY_GEO)); int attachment = c.getInt(c.getColumnIndex(MustardDbAdapter.KEY_ATTACHMENT)); try { c.close(); } catch (Exception e) { } // Log.v(TAG, "Username id: " + usernameId + " vs " + mStatusNet.getUsernameId()); ArrayList<CharSequence> aitems = new ArrayList<CharSequence>(); aitems.add(getString(R.string.menu_reply)); aitems.add(getString(R.string.menu_forward)); aitems.add(getString(favorited ? R.string.menu_unfav : R.string.menu_fav)); if (in_reply_to > 0 && isConversationEnable) { aitems.add(getString(R.string.menu_conversation)); } final int conversationIdx = in_reply_to > 0 && isConversationEnable ? aitems.size()-1 : -1; // Log.i(TAG,"conversationIdx = " + conversationIdx); if (attachment>0) { aitems.add(getString(R.string.menu_view_attachment)); } final int attachmentIdx = attachment > 0 ? aitems.size()-1 : -1; // Log.i(TAG,"attachmentIdx = " + attachmentIdx); if (geo == 1) { aitems.add(getString(R.string.menu_view_geo)); } final int geoIdx = geo == 1 ? aitems.size()-1 : -1; // Log.i(TAG,"geoIdx = " + geoIdx); final CharSequence[] items = new CharSequence[aitems.size()]; for(int i=0;i<aitems.size();i++) { items[i]=aitems.get(i); } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(userName); builder.setIcon(_icon); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { // Funky hack.. if you have a better idea.. you're welcome! // Log.i(TAG,"Clicked = " + item); if (item > 2) { if (item == conversationIdx) item = 3; else if (item == attachmentIdx) item = 4; else if (item == geoIdx) item = 5; } onNoticeMenuItemClick(id, item); dialog.dismiss(); } }); builder.create().show(); } private void onNoticeMenuItemClick(long rowid, int action) { // Log.i(TAG,"onNoticeMenuItemClick Action " + action); Cursor c = mDbHelper.fetchStatus(rowid); switch (action) { case 0: // Reply: MustardUpdate.actionReply(this,mHandler, rowid); break; case 1: // Forward boolean newRepeat = mPreferences.getBoolean(Preferences.NEW_REPEAT_ENABLES_KEY, false); if(newRepeat) { String ss = c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_STATUS_ID)); repeat(ss); } else { MustardUpdate.actionForward(this,mHandler, rowid); } break; case 2: // Fav/Unfav boolean favorited = c.getInt(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_FAVORITE)) == 1 ? true : false; if (favorited) new StatusDisfavor().execute(c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_STATUS_ID))); else new StatusFavor().execute(c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_STATUS_ID))); break; case 3: // Conversation // doOpenConversation(c.getLong(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_STATUS_ID))); doOpenConversation(rowid); break; case 4: // Attachment onShowAttachemntList(rowid); break; case 5: // Geo doShowLocation(c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_LON)), c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_LAT))); break; } try { c.close(); } catch (Exception e) {} } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); if(savedInstanceState != null) { mFromSavedState=true; } mPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); String sFontSize=mPreferences.getString(Preferences.FONT_SIZE, "1"); Log.i(TAG,"Font Size: " + sFontSize); int fontSize=1; try { fontSize=Integer.parseInt(sFontSize); } catch (NumberFormatException e) { // Not sure but got a cast exception.. if(sFontSize.equals(getString(R.string.small))) { fontSize=0; } else if (sFontSize.equals(getString(R.string.medium))) { fontSize=1; } else { fontSize=2; } } switch (fontSize) { case 0: mTextSizeNormal=12; mTextSizeSmall=10; break; case 1: mTextSizeNormal=14; mTextSizeSmall=12; break; case 2: mTextSizeNormal=16; mTextSizeSmall=14; break; } mLayoutLegacy=mPreferences.getBoolean(Preferences.LAYOUT_LEGACY, false); mLayoutNewButton=mPreferences.getBoolean(Preferences.LAYOUT_NEW_BUTTON, false); if (MustardApplication.DEBUG) Log.i(TAG,"onCreate"); if (mDbHelper!=null) { try { mDbHelper.close(); } catch (Exception e) { } } mDbHelper = new MustardDbAdapter(this); mDbHelper.open(); if(mLayoutLegacy) { R_ROW_ID=R.layout.legacy_timeline_list_item; } else { R_ROW_ID=R.layout.timeline_list_item; } onSetListView(); ListView view = null; try { view = (GimmeMoreListView)getListView(); ((GimmeMoreListView)view).setOnNeedMoreListener(this); } catch(ClassCastException e){ Log.e(TAG," change view type!!"); view = getListView(); } mNoticeCursorAdapter = new NoticeListAdapter(this, R_ROW_ID, new String[] {}, new int[] {}); setListAdapter(mNoticeCursorAdapter); registerForContextMenu(view); onSetupTimeline(); getStatusNet(); if (mStatusNet == null) { if (MustardApplication.DEBUG) Log.i(TAG, "No account found. Starting Login activity"); showLogin(); } else { if (MustardApplication.DEBUG) Log.i(TAG, "calling onBeforeFetch()"); onBeforeFetch(); changeTitle(); // onStartScheduler(); } } protected abstract void onSetListView() ; private void onShowNoticeAction(final long id) { AlertDialog.Builder builder = new AlertDialog.Builder(this); Cursor c = mDbHelper.fetchStatus(id); String text = c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_STATUS)); boolean fav = c.getInt(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_FAVORITE)) == 1 ? true : false; View view = LayoutInflater.from(this).inflate(R.layout.notice_action, null); TextView tv = (TextView)view.findViewById(R.id.text_status); tv.setText(text); final Context context = this; final long statusId = c.getLong(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_STATUS_ID)); Button ibr = (Button)view.findViewById(R.id.button_reply); ibr.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { MustardUpdate.actionReply(context,mHandler, id); closeNoticeDialog(); } }); Button ibf = (Button)view.findViewById(R.id.button_repeat); ibf.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { boolean newRepeat = mPreferences.getBoolean(Preferences.NEW_REPEAT_ENABLES_KEY, false); if(newRepeat) { repeat(Long.toString(statusId)); } else { MustardUpdate.actionForward(context,mHandler, id); } closeNoticeDialog(); } }); Button ib = (Button)view.findViewById(R.id.button_fav); if(!fav) { ib.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.favorited); ib.setText(R.string.menu_fav); ib.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { new StatusFavor().execute(Long.toString(statusId)); closeNoticeDialog(); } }); } else { ib.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.unfavorited); ib.setText(R.string.menu_unfav); ib.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { new StatusDisfavor().execute(Long.toString(statusId)); closeNoticeDialog(); } }); } BitmapDrawable _icon = new BitmapDrawable( MustardApplication.sImageManager.get( c.getString( c.getColumnIndexOrThrow(MustardDbAdapter.KEY_USER_IMAGE) ) ) ); String userName = c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_SCREEN_NAME)); try { c.close(); } catch (Exception e) { } builder.setIcon(_icon); builder.setView(view); builder.setCancelable(true); builder.setTitle(userName); builder.setPositiveButton(R.string.close, null); noticeDialog = builder.create(); noticeDialog.show(); } private AlertDialog noticeDialog; private void closeNoticeDialog() { noticeDialog.dismiss(); } private void onShowAttachemntList(long statusId) { Cursor c = mDbHelper.fetchAttachment(statusId); final CharSequence[] items = new CharSequence[c.getCount()]; final ArrayList<Attachment> attachments = new ArrayList<Attachment>(); int cc=0; while(c.moveToNext()) { Attachment a = new Attachment(); String mimeType = c.getString(c.getColumnIndex(MustardDbAdapter.KEY_MIMETYPE)); a.setMimeType(mimeType); a.setUrl(c.getString(c.getColumnIndex(MustardDbAdapter.KEY_URL))); attachments.add(a); if (mimeType.startsWith("image")) { items[cc]="Image"; } else if (mimeType.startsWith("text/html")) { items[cc]="Html"; } else { items[cc]="Unknown"; } cc++; } c.close(); if (attachments.size() > 1) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("View attachment"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface xdialog, int item) { Attachment a = attachments.get(item); if (a.getMimeType().startsWith("image")) { showAttachmentImage(a.getUrl(),true); } else if (a.getMimeType().startsWith("text/html")){ showAttachmentText(a.getUrl()); } } }); builder.create(); builder.setPositiveButton(R.string.close, null); builder.show(); } else { Attachment a = attachments.get(0); if (a.getMimeType().startsWith("image")) { showAttachmentImage(a.getUrl(),true); } else if (a.getMimeType().startsWith("text/html")){ showAttachmentText(a.getUrl()); } } } void showAttachmentImage(String url, boolean extraLink) { View view = LayoutInflater.from(this).inflate(R.layout.html, null); WebView html = (WebView)view.findViewById(R.id.html); String summary = "<html><body>" + "<center>" + "<img width=\"100%\" src=\""+url+"\"/>"; if (extraLink) summary += "<br/><a href=\""+url+"\">Open with Browser</a></center>"; summary += "</body></html>"; html.loadDataWithBaseURL("fake://this/is/not/real",summary, "text/html", "utf-8",""); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.attachment); builder.setView(view); builder.setCancelable(true); builder.setTitle("View Image"); builder.setPositiveButton(R.string.close, null); builder.create().show(); } void showAttachmentText(String url) { View view = LayoutInflater.from(this).inflate(R.layout.html, null); WebView html = (WebView)view.findViewById(R.id.html); html.loadUrl(url); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(view); builder.setIcon(R.drawable.attachment); builder.setCancelable(true); builder.setTitle("View Text"); builder.setPositiveButton(R.string.close, null); builder.create().show(); } @Override protected void onResume() { super.onResume(); if (MustardApplication.DEBUG) Log.i(TAG, "onResume()"); mIsOnSaveInstanceState=false; } @Override protected void onRestart() { super.onRestart(); if (MustardApplication.DEBUG) Log.i(TAG, "onRestart()"); mIsOnSaveInstanceState=false; } @Override protected void onRestoreInstanceState(Bundle state) { super.onRestoreInstanceState(state); if (MustardApplication.DEBUG) Log.i(TAG, "onRestoreInstanceState()"); mIsOnSaveInstanceState=false; } @Override protected void onPause() { super.onPause(); if (MustardApplication.DEBUG) Log.i(TAG, "onPause()"); } @Override protected void onStart() { super.onStart(); if (MustardApplication.DEBUG) Log.i(TAG, "onStart()"); mIsOnSaveInstanceState=false; } @Override protected void onStop() { super.onStop(); if (MustardApplication.DEBUG) Log.i(TAG, "onStop()"); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (MustardApplication.DEBUG) Log.i(TAG, "onConfigurationChanged()"); } @Override public void onSaveInstanceState(Bundle savedInstanceState) { mIsOnSaveInstanceState=true; super.onSaveInstanceState(savedInstanceState); } @Override public void onDestroy() { super.onDestroy(); if (MustardApplication.DEBUG) Log.i(TAG,"onDestroy()"); if(mDbHelper != null) { try { if(!mIsOnSaveInstanceState) { if (MustardApplication.DEBUG) Log.i(TAG,"deleting dents"); mDbHelper.deleteStatuses(DB_ROW_TYPE,DB_ROW_EXTRA); } } catch (Exception e) { if (MustardApplication.DEBUG) e.printStackTrace(); } finally { mDbHelper.close(); } } } protected void onPreCreateOptionsMenu(Menu menu) { } protected void onPostCreateOptionsMenu(Menu menu) { } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); onPreCreateOptionsMenu(menu); if(mForceOnlyBackMenu) { menu.add(0, BACK_ID, 0, R.string.menu_back) .setIcon(android.R.drawable.ic_menu_revert); return true; } if(isTaskRoot()) { menu.add(0, INSERT_ID, 0, R.string.menu_insert) .setIcon(android.R.drawable.ic_menu_add); } if(isRefreshEnable) menu.add(0, REFRESH_ID, 0, R.string.menu_refresh) .setIcon(android.R.drawable.ic_menu_rotate); if(isTaskRoot()) { menu.add(0, MENTIONS_ID, 0, R.string.menu_mentions) .setIcon(android.R.drawable.ic_menu_mylocation); menu.add(0, SEARCH_ID, 0, R.string.menu_search) .setIcon(android.R.drawable.ic_menu_search); menu.add(0, BOOKMARKS_ID, 0, R.string.menu_bookmarks) .setIcon(android.R.drawable.ic_menu_compass); menu.add(0, PUBLIC_ID, 0, R.string.menu_public) .setIcon(android.R.drawable.ic_menu_myplaces); menu.add(0, FAVORITES_ID, 0, R.string.menu_favorites) .setIcon(android.R.drawable.ic_menu_recent_history); menu.add(0, SWITCH_ID, 0, R.string.menu_switch) .setIcon(android.R.drawable.ic_menu_directions); menu.add(0, ACCOUNT_SETTINGS_ID, 0, R.string.menu_account_settings) .setIcon(android.R.drawable.ic_menu_gallery); menu.add(0, SETTINGS_ID, 0, R.string.menu_settings) .setIcon(android.R.drawable.ic_menu_preferences); // menu.add(0, OAUTHSETTING_ID, 0, R.string.menu_oauth_settings) // .setIcon(android.R.drawable.ic_menu_preferences); menu.add(0, LOGOUT_ID, 0, R.string.menu_logout) .setIcon(android.R.drawable.ic_menu_delete); menu.add(0, ABOUT_ID, 0, R.string.menu_about) .setIcon(android.R.drawable.ic_menu_info_details); } else { if(isBookmarkEnable) { menu.add(0, BOOKMARK_THIS_ID, 0, R.string.menu_bookmark_this_page) .setIcon(android.R.drawable.btn_star); } menu.add(0, BACK_ID, 0, R.string.menu_back) .setIcon(android.R.drawable.ic_menu_revert); } onPostCreateOptionsMenu(menu); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case INSERT_ID: doCompose(); return true; case REFRESH_ID: doRefresh(); return true; case MENTIONS_ID: getMentions(); return true; case PUBLIC_ID: getPublic(); return true; case LOGOUT_ID: logout(); return true; case SWITCH_ID: switchUser(); return true; // case OAUTHSETTING_ID: // oauthSettings(); // return true; case SEARCH_ID: doSearch(); return true; case BOOKMARKS_ID: doBookmark(); return true; case ABOUT_ID: AboutDialog.show(this); return true; case BACK_ID: setResult(RESULT_OK); finish(); return true; case BOOKMARK_THIS_ID: bookmarkThis(); return true; case FAVORITES_ID: getFavorites(); return true; case FRIENDS_ID: getFriends(); return true; case ACCOUNT_SETTINGS_ID: AccountSettings.actionAccountSettings(this); return true; case SETTINGS_ID: settings(); return true; case GROUP_LEAVE_ID: doLeaveGroup(); return true; case GROUP_JOIN_ID: doJoinGroup(); return true; case SUB_ID: doSubscribe(); return true; case UNSUB_ID: doUnsubscribe(); return true; } return super.onMenuItemSelected(featureId, item); } protected abstract void onBeforeFetch() ; protected void onSetupTimeline() { } public void needMore() { if(MustardApplication.DEBUG) Log.d(TAG,"Asked for more!"); doLoadMore(); } protected void doRefresh() { mIsRefresh=true; getStatuses(); } private void switchUser() { Cursor c = mDbHelper.fetchAllNonDefaultAccounts(); final CharSequence[] items = new CharSequence[c.getCount()+1]; final long[] rowIds = new long[c.getCount()]; int cc=0; while(c.moveToNext()) { items[cc]=c.getString(c.getColumnIndex(MustardDbAdapter.KEY_INSTANCE)) + "/" + c.getString(c.getColumnIndex(MustardDbAdapter.KEY_USER)); rowIds[cc]=c.getLong(c.getColumnIndex(MustardDbAdapter.KEY_ROWID)); cc++; } items[cc]=getString(R.string.menu_add_new); c.close(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.menu_choose_account)); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface xdialog, int item) { mDbHelper.resetDefaultAccounts(); mDbHelper.deleteStatuses(MustardDbAdapter.ROWTYPE_ALL, ""); mDbHelper.deleteStatuses(DB_ROW_TYPE,DB_ROW_EXTRA); if(mFetcherTask!=null) { mFetcherTask.cancel(true); } mFetcherTask = null; if (items[item].equals(getString(R.string.menu_add_new))) { if (mNoticeCursorAdapter!=null) { mNoticeCursorAdapter.notifyDataSetInvalidated(); // mNoticeCursorAdapter.getCursor().requery(); // mNoticeCursorAdapter = null; } showLogin(); } else { mDbHelper.setDefaultAccount(rowIds[item]); startMainTimeline(); // if (mNoticeCursorAdapter!=null) { // mNoticeCursorAdapter.notifyDataSetInvalidated(); //// mNoticeCursorAdapter.getCursor().requery(); //// mNoticeCursorAdapter = null; // } // getStatusNet(); // onBeforeFetch(); // changeTitle(); // getStatuses(); } } }); builder.create(); builder.show(); } private void startMainTimeline() { MustardMain.actionHandleTimeline(this); finish(); } private void changeTitle() { if (mStatusNet != null) { setTitle(getString(R.string.app_name) + " - " + mStatusNet.getMUsername() + "@" + mStatusNet.getURL().getHost()); } } private void showLogin() { // Intent i = new Intent(this, Login.class); // startActivityForResult(i, ACCOUNT_ADD_SWITCH); Login.actionHandleLogin(this); finish(); } private void logout() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.msg_logout)) .setCancelable(false) .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface xdialog, int id) { mDbHelper.deleteAccount(mStatusNet.getUserId()); mDbHelper.deleteBookmarks(mStatusNet.getUserId()); mDbHelper.deleteStatuses(MustardDbAdapter.ROWTYPE_ALL, ""); finish(); } }) .setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface xdialog, int id) { xdialog.cancel(); } }); builder.create(); builder.show(); } private void repeat(final String ss) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.msg_confirm_repeat)) .setCancelable(false) .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface xdialog, int id) { new StatusRepeat().execute(ss); } }) .setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface xdialog, int id) { xdialog.cancel(); } }); builder.create(); builder.show(); } private void getFriends() { MustardFriend.actionHandleTimeline(this, DB_ROW_EXTRA); // Intent i = new Intent("android.intent.action.VIEW",Uri.parse("statusnet://friends/"+DB_ROW_EXTRA)); // startActivityForResult(i, ACTIVITY_FRIENDS); } protected void getMentions() { MustardMention.actionHandleTimeline(this, mStatusNet.getUsernameId()); // Intent i = new Intent("android.intent.action.VIEW",Uri.parse("statusnet://mentions/"+mStatusNet.getUsernameId())); // startActivityForResult(i, ACTIVITY_MENTIONS); } private void getFavorites() { MustardFavorite.actionHandleTimeline(this,DB_ROW_EXTRA); } private void getPublic() { Intent i = new Intent("android.intent.action.VIEW",Uri.parse("statusnet://public/")); startActivityForResult(i, ACTIVITY_PUBLIC); } protected void doCompose() { MustardUpdate.actionCompose(this,mHandler); } private void doSearch() { Intent i = new Intent(this, Search.class); startActivity(i); } private void doBookmark() { Intent i = new Intent(this, Bookmark.class); startActivity(i); } private void bookmarkThis() { try { mDbHelper.createBookmark(mStatusNet.getUserId(), DB_ROW_TYPE, DB_ROW_EXTRA); } catch (MustardException e) { if(MustardApplication.DEBUG) Log.e(TAG, e.getMessage()); } } // private void avatar() { // Intent i = new Intent(this, Avatar.class); // startActivity(i); // } // private void oauthSettings() { // Intent i = new Intent(this, OAuthSettings.class); // startActivity(i); // } private void settings() { Intent i = new Intent(this, Settings.class); startActivity(i); } protected void showToastMessage(CharSequence message) { showToastMessage(message,false); } protected void showToastMessage(CharSequence message,boolean longView) { int popTime = longView ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT; Toast.makeText(this, message, popTime).show(); } protected void showAlertMessage(String errorTitle,String errorMessage) { new AlertDialog.Builder(this) .setTitle(errorTitle) .setMessage(errorMessage) .setNeutralButton(getString(R.string.close), null).show(); } protected void showAlertMessageAndFinish(String errorTitle,String errorMessage) { new AlertDialog.Builder(this) .setTitle(errorTitle) .setMessage(errorMessage) .setNeutralButton(getString(R.string.close), new DialogInterface.OnClickListener() { public void onClick(DialogInterface xdialog, int id) { finish(); } }).show(); } @Override protected Dialog onCreateDialog(int id) { ProgressDialog dialog; switch(id) { case DIALOG_FETCHING_ID: // do the work to define the pause Dialog dialog = new ProgressDialog(this); dialog.setIndeterminate(true); dialog.setCancelable(true); dialog.setMessage(getString(R.string.please_wait_fetching_dents)); break; case DIALOG_OPENING_ID: dialog = new ProgressDialog(this); dialog.setIndeterminate(true); dialog.setCancelable(true); dialog.setMessage(getString(R.string.please_wait_opening)); break; default: if(MustardApplication.DEBUG) Log.d(TAG,"onCreateDialog null...."); dialog = null; } return dialog; } protected long mStatusNetAccountId = -1; private void getStatusNet() { MustardApplication _ma = (MustardApplication) getApplication(); if (mStatusNetAccountId>=0) { mStatusNet = _ma.checkAccount(mDbHelper,mStatusNetAccountId); } else { mStatusNet = _ma.checkAccount(mDbHelper); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (MustardApplication.DEBUG) Log.i(TAG,"onActivityResult"); super.onActivityResult(requestCode, resultCode, intent); if (requestCode == ACCOUNT_ADD || requestCode == ACCOUNT_ADD_SWITCH) { if (resultCode == RESULT_OK) { // ... have to recheck mStatusNet = null; if (MustardApplication.DEBUG) Log.d(TAG,"Back OK from ActivityResult " + requestCode); getStatusNet(); onBeforeFetch(); changeTitle(); getStatuses(); } else { // Log.i(TAG, "Finshed..." ); finish(); } } else if (requestCode == ACCOUNT_DEL) { if (!isTaskRoot()) { setResult(ACCOUNT_DEL); } finish(); } else if (requestCode == ACTIVITY_EDIT || requestCode == ACTIVITY_CREATE) { if(mPreferences.getBoolean(Preferences.REFRESH_ON_POST_ENABLES_KEY, false) && resultCode == RESULT_OK) { if(MustardApplication.DEBUG) Log.d(TAG, "Refresh"); doRefresh(); } } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; mCurrentRowid=info.id; // Log.d(TAG,"Set mCurrentRowid " + mCurrentRowid); Cursor c = mDbHelper.fetchStatus(info.id); BitmapDrawable _icon = new BitmapDrawable( MustardApplication.sImageManager.get( c.getString( c.getColumnIndexOrThrow(MustardDbAdapter.KEY_USER_IMAGE) ) ) ); String userName = c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_SCREEN_NAME)); long usernameId = c.getLong(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_USER_ID)); // Log.v(TAG, "Username id: " + usernameId + " vs " + mStatusNet.getUsernameId()); menu.setHeaderTitle(userName); menu.setHeaderIcon(_icon); if(!mLayoutNewButton) { menu.add(0, SHARE_ID, 0, R.string.menu_share); menu.add(0, COPY2CLIPBOARD_ID, 0, R.string.menu_copy2clipboard); menu.add(0, USER_TL_ID, 0, R.string.menu_timeline); if (usernameId != mStatusNet.getUsernameId()) { boolean following = c.getInt(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_FOLLOWING)) == 1 ? true : false; if (following) menu.add(0, M_UNSUB_ID,0, R.string.menu_unsub); else menu.add(0, M_SUB_ID,0, R.string.menu_sub); menu.add(0,BLOCK_ID,0,R.string.menu_block); } } else { menu.add(0, USER_TL_ID, 0, R.string.menu_timeline); if (usernameId != mStatusNet.getUsernameId()) { boolean following = c.getInt(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_FOLLOWING)) == 1 ? true : false; if (following) menu.add(0, M_UNSUB_ID,0, R.string.menu_unsub); else menu.add(0, M_SUB_ID,0, R.string.menu_sub); menu.add(0,BLOCK_ID,0,R.string.menu_block); } String geo = c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_GEO)); if ("1".equals(geo)) { menu.add(0,GEOLOCATION_ID, 0,R.string.menu_view_geo); } } if (usernameId == mStatusNet.getUsernameId()) { menu.add(0, DELETE_ID, 0, R.string.menu_delete).setIcon(android.R.drawable.ic_delete); } try { c.close(); } catch(Exception e) { } } private void doOpenConversation(long statusId) { MustardConversation.actionHandleTimeline(this,statusId); } private void doShowLocation(final String lon,final String lat) { new Thread() { public void run() { Controller.getInstance(getApplication()) .loadGeoNames(getApplication(), lon, lat, mListener); } }.start(); } private void doShowGeolocation(GeoName gn) { Builder b = StatusNetUtils.getGeoInfo(this, gn); b.show(); } private void doShare(String text) { Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_TEXT, text); startActivity(i); } @Override public void onContextMenuClosed(Menu menu) { super.onContextMenuClosed(menu); // Log.d(TAG,"Remove mCurrentRowid"); mCurrentRowid = -1; } @Override public boolean onContextItemSelected(MenuItem item) { long rowid = mCurrentRowid; // Intent i = null; Cursor c = null; int x = item.getItemId(); switch (x) { case REPLY_ID: MustardUpdate.actionReply(this,mHandler, rowid); return true; case REPEAT_ID: boolean newRepeat = mPreferences.getBoolean(Preferences.NEW_REPEAT_ENABLES_KEY, false); if(newRepeat) { c = mDbHelper.fetchStatus(rowid); String ss = c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_STATUS_ID)); repeat(ss); try { c.close(); } catch (Exception e) {} } else { MustardUpdate.actionForward(this,mHandler, rowid); } return true; case SHARE_ID: c = mDbHelper.fetchStatus(rowid); String text = c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_STATUS)); doShare(text); try { c.close(); } catch (Exception e) {} return true; case COPY2CLIPBOARD_ID: c = mDbHelper.fetchStatus(rowid); String id = c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_STATUS_ID)); try { c.close(); } catch (Exception e) {} ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); String url = mStatusNet.getURL().toExternalForm(); if (url.endsWith("/api")) url = url.substring(0, -4); clipboard.setText(url+"/notice/"+id); Toast.makeText(this, getString(R.string.copied_to_clipboard), Toast.LENGTH_LONG).show(); return true; case USER_TL_ID: c = mDbHelper.fetchStatus(rowid); String userid = ""; if(mStatusNet.isTwitterInstance()) userid=c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_SCREEN_NAME)); else userid=c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_USER_ID)); if (MustardApplication.DEBUG) Log.d(TAG,"Called user timeline userid " + userid); // i = new Intent("android.intent.action.VIEW",Uri.parse("statusnet://users/"+userid)); // startActivityForResult(i,0); MustardUser.actionHandleTimeline(this, userid); try { c.close(); } catch (Exception e) {} return true; case DELETE_ID: c = mDbHelper.fetchStatus(rowid); if(mStatusNet.delete(c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_STATUS_ID)))) { mDbHelper.deleteStatus(rowid); Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show(); fillData(); } else { Toast.makeText(this, "Can't Delete", Toast.LENGTH_SHORT).show(); } try { c.close(); } catch (Exception e) {} return true; case FAVORS_ID: c = mDbHelper.fetchStatus(rowid); new StatusFavor().execute(c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_STATUS_ID))); try { c.close(); } catch (Exception e) {} return true; case UNFAVORS_ID: c = mDbHelper.fetchStatus(rowid); new StatusDisfavor().execute(c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_STATUS_ID))); try { c.close(); } catch (Exception e) {} return true; case M_SUB_ID: c = mDbHelper.fetchStatus(rowid); new StatusSubscribe().execute(c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_USER_ID))); try { c.close(); } catch (Exception e) {} return true; case M_UNSUB_ID: c = mDbHelper.fetchStatus(rowid); new StatusUnsubscribe().execute(c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_USER_ID))); try { c.close(); } catch (Exception e) {} return true; case BLOCK_ID: c = mDbHelper.fetchStatus(rowid); new StatusBlock().execute(c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_USER_ID))); try { c.close(); } catch (Exception e) {} return true; case GEOLOCATION_ID: c = mDbHelper.fetchStatus(rowid); String lon = c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_LON)); String lat = c.getString(c.getColumnIndexOrThrow(MustardDbAdapter.KEY_LAT)); doShowLocation(lon, lat); try { c.close(); } catch (Exception e) {} return true; } return super.onContextItemSelected(item); } private void doJoinGroup() { new StatusGroupJoin().execute(DB_ROW_EXTRA); } protected void doSubscribe() { } protected void doUnsubscribe() { } private void doLeaveGroup() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.warning_leave_group,DB_ROW_EXTRA)) .setCancelable(false) .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface xdialog, int id) { new StatusGroupLeave().execute(DB_ROW_EXTRA); } }) .setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface xdialog, int id) { xdialog.cancel(); } }); builder.create(); builder.show(); } private void showIntederminateProgressBar(boolean show) { setProgressBarIndeterminateVisibility(show); } protected abstract void onAfterFetch() ; protected void doLoadMore() { if (MustardApplication.DEBUG) Log.d(TAG, "Attempting load more."); if (mLoadMoreTask != null && mLoadMoreTask.getStatus() == Status.RUNNING ) { if(MustardApplication.DEBUG) Log.w(TAG, "Already loading more."); } else { if (mNoMoreDents) { if(MustardApplication.DEBUG) Log.w(TAG, "Reached NoMoreDent!"); } else { if (mMergedTimeline) mLoadMoreTask = new MergedStatusesLoadMore(); else mLoadMoreTask = new StatusesLoadMore(); mLoadMoreTask.execute(); } } } protected void doSilentRefresh() { if(MustardApplication.DEBUG) Log.d(TAG, "Silent Refresh."); if(mFetcherTask != null && mFetcherTask.getStatus()==Status.RUNNING) { if(MustardApplication.DEBUG) if(MustardApplication.DEBUG) Log.w(TAG, "Already fetching statuses"); } else { if(MustardApplication.DEBUG) Log.i(TAG, "Fetching statuses silently"); if (mMergedTimeline) mFetcherTask = new MultiStatusesFetcher(); else mFetcherTask = new StatusesFetcher(); mFetcherTask.setSilent(true); mFetcherTask.execute(); } } protected boolean mMergedTimeline=false; protected void getStatuses() { getStatuses(mMergedTimeline); } protected void getStatuses(boolean multiple) { if(mFromSavedState) { mFromSavedState=false; fillData(); return; } if (MustardApplication.DEBUG) Log.d(TAG,"Attempting fetching statuses"); if(mFetcherTask != null && mFetcherTask.getStatus()==Status.RUNNING) { if(MustardApplication.DEBUG) if(MustardApplication.DEBUG) Log.w(TAG, "Already fetching statuses"); } else { if(MustardApplication.DEBUG) Log.i(TAG, "Fetching statuses"); if(multiple) { mMergedTimeline=true; // Log.i(TAG, "MULTIPLE STATUS FETCHER!!!"); mFetcherTask = new MultiStatusesFetcher(); mFetcherTask.execute(); } else { mFetcherTask = new StatusesFetcher(); mFetcherTask.execute(); } } } protected void fillData() { Cursor mNoticesCursor = mDbHelper.fetchAllStatuses(DB_ROW_TYPE, DB_ROW_EXTRA,DB_ROW_ORDER); if (mNoticesCursor == null) { Log.e(TAG, "Cursor is null.. "); return; } startManagingCursor(mNoticesCursor); if(MustardApplication.DEBUG) Log.d(TAG,"Found: " + mNoticesCursor.getCount() + " rows"); mNoticeCursorAdapter.changeCursor(mNoticesCursor); } public class StatusesFetcher extends AsyncTask<Void, Integer, Integer> { private final String TAG = "StatusesFetcher"; protected boolean mGetdents=false; protected boolean mSilent = false; public void setSilent(boolean silent) { mSilent=silent; } @Override protected Integer doInBackground(Void... v) { if (MustardApplication.DEBUG) Log.i(TAG, "background task - start"); ArrayList<org.mustard.statusnet.Status> al = null; try { if (mStatusNet==null) { Log.e(TAG, "Statusnet is null!"); return 0; } long maxId = mDbHelper.fetchMaxStatusesId(mStatusNet.getUserId(),DB_ROW_TYPE,DB_ROW_EXTRA); al=mStatusNet.get(DB_ROW_TYPE,DB_ROW_EXTRA,maxId,true); if(al==null || al.size()< 1) { return 0; } else { mGetdents=mDbHelper.createStatuses(mStatusNet.getUserId(),DB_ROW_TYPE,DB_ROW_EXTRA,al); } } catch(Exception e) { if (MustardApplication.DEBUG) e.printStackTrace(); mErrorMessage=e.toString(); if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); return -1; } finally { if (MustardApplication.DEBUG) Log.i(TAG, "background task - end " + mGetdents); } return 1; } @Override protected void onPreExecute() { super.onPreExecute(); if (MustardApplication.DEBUG) Log.i(TAG, "onPreExecute"); try { if(mSilent) showIntederminateProgressBar(true); else showDialog(MustardBaseActivity.DIALOG_FETCHING_ID); } catch(Exception e) { e.printStackTrace(); } } protected void onPostExecute(Integer result) { if(mSilent) showIntederminateProgressBar(false); else { try { dismissDialog(MustardBaseActivity.DIALOG_FETCHING_ID); } catch (IllegalArgumentException e) {} } try { if (result==-1) { showToastMessage(getText(R.string.error_fetch_dents)+"\n"+mErrorMessage); } else if (result == -10) { showToastMessage("Merged timeline active but no account selected!"); } else { if(mGetdents) { onAfterFetch(); } fillData(); } } catch(IllegalArgumentException e) { if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); } finally { if(mIsRefresh) mIsRefresh=false; } } } public class MultiStatusesFetcher extends StatusesFetcher { private final String TAG = "MultiStatusesFetcher"; @Override protected Integer doInBackground(Void... v) { if (MustardApplication.DEBUG) Log.i(TAG, "background task - start"); try { if (mStatusNet==null) { Log.e(TAG, "Statusnet is null!"); return 0; } MustardApplication _ma = (MustardApplication) getApplication(); StatusNet _sn = null; boolean haveAtLeastOneAccount=false; boolean haveAtLeastOneStatus=false; Cursor c = mDbHelper.fetchAllAccountsToMerge(); while(c.moveToNext()) { ArrayList<org.mustard.statusnet.Status> al = null; haveAtLeastOneAccount=true; long _aid = c.getLong(c.getColumnIndex(MustardDbAdapter.KEY_ROWID)); _sn = _ma.checkAccount(mDbHelper,false,_aid); // Log.i(TAG, "Fetching " + _sn.getMUsername() + "@" + _sn.getURL().getHost()); long maxId = mDbHelper.fetchMaxStatusesId(_aid, DB_ROW_TYPE,DB_ROW_EXTRA); try { al=_sn.get(DB_ROW_TYPE,Long.toString(_sn.getUsernameId()),maxId,true); } catch (MustardException e) { Log.e(TAG,e.toString()); } if(al==null || al.size()< 1) { continue; } else { haveAtLeastOneStatus=true; mGetdents=mDbHelper.createStatuses(_aid,DB_ROW_TYPE,DB_ROW_EXTRA,al); } } c.close(); if(!haveAtLeastOneAccount) { return -10; } if(!haveAtLeastOneStatus) { return 0; } } catch(Exception e) { if (MustardApplication.DEBUG) e.printStackTrace(); mErrorMessage=e.toString(); if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); return -1; } finally { if (MustardApplication.DEBUG) Log.i(TAG, "background task - end " + mGetdents); } return 1; } } public class StatusRepeat extends AsyncTask<String, Integer, Integer> { private final String TAG = "StatusRepeat"; @Override protected Integer doInBackground(String... s) { if (MustardApplication.DEBUG) Log.i(TAG, "background task - start"); try { mStatusNet.doRepeat(s[0]); } catch(Exception e) { mErrorMessage=e.toString(); if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); return 0; } finally { if (MustardApplication.DEBUG) Log.i(TAG, "background task - end "); } return 1; } protected void onPostExecute(Integer result) { try { if (result>0) { showToastMessage(getText(R.string.confirm_repeat)); } else { showToastMessage(getText(R.string.error_repeat)+"\n"+mErrorMessage,true); mPreferences.edit().putBoolean(Preferences.NEW_REPEAT_ENABLES_KEY, false).commit(); } } catch(IllegalArgumentException e) { if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); } finally { } } } public class StatusFavor extends AsyncTask<String, Integer, Integer> { private final String TAG = "StatusFavor"; @Override protected Integer doInBackground(String... s) { if (MustardApplication.DEBUG) Log.i(TAG, "background task - start"); try { mStatusNet.doFavour(s[0]); mDbHelper.updateStatusFavor(s[0], true); } catch(Exception e) { e.printStackTrace(); mErrorMessage=e.toString(); if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); return 0; } finally { if (MustardApplication.DEBUG) Log.i(TAG, "background task - end "); } return 1; } protected void onPostExecute(Integer result) { try { if (result>0) { showToastMessage(getText(R.string.confirm_fav)); } else { showToastMessage(getText(R.string.error_fav)+"\n"+mErrorMessage,true); } } catch(IllegalArgumentException e) { if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); } finally { } } } public class StatusDisfavor extends AsyncTask<String, Integer, Integer> { private final String TAG = "StatusDisfavor"; @Override protected Integer doInBackground(String... s) { if (MustardApplication.DEBUG) Log.i(TAG, "background task - start"); try { mStatusNet.doDisfavour(s[0]); mDbHelper.updateStatusFavor(s[0], false); } catch(Exception e) { e.printStackTrace(); mErrorMessage=e.toString(); if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); return 0; } finally { if (MustardApplication.DEBUG) Log.i(TAG, "background task - end "); } return 1; } protected void onPostExecute(Integer result) { try { if (result>0) { showToastMessage(getText(R.string.confirm_unfav)); } else { showToastMessage(getText(R.string.error_unfav)+"\n"+mErrorMessage); } } catch(IllegalArgumentException e) { if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); } finally { } } } public class StatusBlock extends AsyncTask<String, Integer, Integer> { private final String TAG = getClass().getCanonicalName(); @Override protected Integer doInBackground(String... s) { if (MustardApplication.DEBUG) Log.i(TAG, "background task - start"); try { mStatusNet.doBlock(s[0]); } catch(Exception e) { mErrorMessage=e.toString(); if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); return 0; } finally { if (MustardApplication.DEBUG) Log.i(TAG, "background task - end "); } return 1; } protected void onPostExecute(Integer result) { try { if (result>0) { showToastMessage(getText(R.string.confirm_block)); } else { showToastMessage(getText(R.string.error_block)+"\n"+mErrorMessage); } } catch(IllegalArgumentException e) { if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); } finally { } } } public class StatusGroupJoin extends AsyncTask<String, Integer, Integer> { private final String TAG = getClass().getCanonicalName(); @Override protected Integer doInBackground(String... s) { if (MustardApplication.DEBUG) Log.i(TAG, "background task - start"); try { String group = s[0]; mStatusNet.doJoinGroup(group); } catch(Exception e) { mErrorMessage=e.toString(); if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); return 0; } finally { if (MustardApplication.DEBUG) Log.i(TAG, "background task - end "); } return 1; } protected void onPostExecute(Integer result) { try { if (result>0) { showToastMessage(getText(R.string.confirm_join)); } else { showToastMessage(getText(R.string.error_join)+"\n"+mErrorMessage); } } catch(IllegalArgumentException e) { if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); } finally { } } } public class StatusGroupLeave extends AsyncTask<String, Integer, Integer> { private final String TAG = getClass().getCanonicalName(); @Override protected Integer doInBackground(String... s) { if (MustardApplication.DEBUG) Log.i(TAG, "background task - start"); try { String group = s[0]; mStatusNet.doLeaveGroup(group); } catch(Exception e) { mErrorMessage=e.toString(); if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); return 0; } finally { if (MustardApplication.DEBUG) Log.i(TAG, "background task - end "); } return 1; } protected void onPostExecute(Integer result) { try { if (result>0) { showToastMessage(getText(R.string.confirm_leave)); } else { showToastMessage(getText(R.string.error_leave)+"\n"+mErrorMessage); } } catch(IllegalArgumentException e) { if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); } finally { } } } public class StatusSubscribe extends AsyncTask<String, Integer, Integer> { private final String TAG = getClass().getCanonicalName(); @Override protected Integer doInBackground(String... s) { if (MustardApplication.DEBUG) Log.i(TAG, "background task - start"); try { if(mStatusNet.doSubscribe(s[0])) { mDbHelper.updateStatusFollowing(s[0], true); } else { mErrorMessage=getString(R.string.error_sub); return 0; } } catch(MustardException e) { mErrorMessage=e.getMessage(); if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); return 0; } finally { if (MustardApplication.DEBUG) Log.i(TAG, "background task - end "); } return 1; } protected void onPostExecute(Integer result) { try { if (result>0) { showToastMessage(getText(R.string.confirm_sub)); } else { showToastMessage(getText(R.string.error_sub)+"\n"+mErrorMessage); } } catch(IllegalArgumentException e) { if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); } finally { } } } public class StatusUnsubscribe extends AsyncTask<String, Integer, Integer> { private final String TAG = getClass().getCanonicalName(); @Override protected Integer doInBackground(String... s) { if (MustardApplication.DEBUG) Log.i(TAG, "background task - start"); try { if(mStatusNet.doUnsubscribe(s[0])) { mDbHelper.updateStatusFollowing(s[0], false); } else { return 0; } } catch(MustardException e) { mErrorMessage=e.getMessage(); if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); return 0; } finally { if (MustardApplication.DEBUG) Log.i(TAG, "background task - end "); } return 1; } protected void onPostExecute(Integer result) { try { if (result>0) { showToastMessage(getText(R.string.confirm_unsub)); } else { showToastMessage(getText(R.string.error_unsub)+"\n"+mErrorMessage); } } catch(IllegalArgumentException e) { if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); } finally { } } } public class StatusesLoadMore extends AsyncTask<Void, Integer, Integer> { private final String TAG = "StatusesLoadMore"; protected boolean mGetdents=false; @Override protected Integer doInBackground(Void... v) { if (MustardApplication.DEBUG) Log.i(TAG, "background task - start"); long maxId = mDbHelper.fetchMinStatusesId(mStatusNet.getUserId(),DB_ROW_TYPE,DB_ROW_EXTRA); Log.v(TAG,"Search " + (maxId-1)); if (maxId-1 < 1) { return -1; } ArrayList<org.mustard.statusnet.Status> al = null; try { al=mStatusNet.get(DB_ROW_TYPE,DB_ROW_EXTRA,maxId-1,false); if(al==null) { return -1; } else if (al.size()< 1) { return -1; } else { Log.v(TAG,"Found " + al.size()); mGetdents=mDbHelper.createStatuses(mStatusNet.getUserId(),DB_ROW_TYPE,DB_ROW_EXTRA,al); } } catch(Exception e) { mNoMoreDents=true; // if (MustardApplication.DEBUG) e.printStackTrace(); mErrorMessage=e.toString(); if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); return -1; } finally { if (MustardApplication.DEBUG) Log.i(TAG, "background task - end " + mGetdents); } return 1; } @Override protected void onPreExecute() { super.onPreExecute(); setProgressBarIndeterminateVisibility(true); } protected void onPostExecute(Integer result) { setProgressBarIndeterminateVisibility(false); if (result<0) { mNoMoreDents=true; } else { if(mGetdents) { fillData(); } else { mNoMoreDents=true; showToastMessage(getText(R.string.error_fetch_more_dents)+"\n"+mErrorMessage); } } } } public class MergedStatusesLoadMore extends StatusesLoadMore { private final String TAG = "MergedStatusesLoadMore"; @Override protected Integer doInBackground(Void... v) { if (MustardApplication.DEBUG) Log.i(TAG, "background task - start"); MustardApplication _ma = (MustardApplication) getApplication(); StatusNet _sn = null; boolean haveAtLeastOneStatus=false; Cursor c = mDbHelper.fetchAllAccountsToMerge(); while(c.moveToNext()) { long _aid = c.getLong(c.getColumnIndex(MustardDbAdapter.KEY_ROWID)); _sn = _ma.checkAccount(mDbHelper,false,_aid); Log.i(TAG, "Fetching " + _sn.getMUsername() + "@" + _sn.getURL().getHost()); long maxId = mDbHelper.fetchMinStatusesId(_aid,DB_ROW_TYPE,DB_ROW_EXTRA); Log.v(TAG,"Search " + (maxId-1)); if (maxId-1 < 1) { return -1; } ArrayList<org.mustard.statusnet.Status> al = null; try { al=_sn.get(DB_ROW_TYPE,Long.toString(_sn.getUsernameId()),maxId-1,false); if(al==null || al.size()< 1) { continue; } else { Log.v(TAG,"Found " + al.size()); mGetdents=mDbHelper.createStatuses(_aid,DB_ROW_TYPE,DB_ROW_EXTRA,al); haveAtLeastOneStatus=true; } } catch(Exception e) { mNoMoreDents=true; // if (MustardApplication.DEBUG) e.printStackTrace(); mErrorMessage=e.toString(); if (MustardApplication.DEBUG) Log.e(TAG,e.toString()); return -1; } finally { if (MustardApplication.DEBUG) Log.i(TAG, "background task - end " + mGetdents); } } c.close(); return haveAtLeastOneStatus ? 1 : 0; } } protected TimelineHandler mHandler = new TimelineHandler(); class TimelineHandler extends Handler { private static final int MSG_PROGRESS = 2; private static final int MSG_GEOLOCATION_OK = 3; private static final int MSG_GEOLOCATION_KO = 4; private static final int MSG_REFRESH = 5; public void handleMessage(Message msg) { switch (msg.what) { case MSG_PROGRESS: setProgressBarIndeterminateVisibility(msg.arg1 != 0); break; case MSG_GEOLOCATION_OK: GeoName gn = (GeoName)msg.obj; doShowGeolocation(gn); break; case MSG_GEOLOCATION_KO: showErrorMessage((String)msg.obj); break; case MSG_REFRESH: doSilentRefresh(); break; } } public void progress(boolean progress) { Message msg = new Message(); msg.what = MSG_PROGRESS; msg.arg1 = progress ? 1 : 0; sendMessage(msg); } public void showGeolocation(GeoName geoname) { Message msg = new Message(); msg.what = MSG_GEOLOCATION_OK; msg.obj = geoname; sendMessage(msg); } public void errorGeolocation(String error) { Message msg = new Message(); msg.what = MSG_GEOLOCATION_KO; msg.obj = error; sendMessage(msg); } } private void showErrorMessage(String reason) { Toast.makeText(this, getString(R.string.error_generic_detail,reason), Toast.LENGTH_LONG).show(); } private MessagingListener mListener = new MessagingListener() { public void loadGeonameStarted(Context context) { mHandler.progress(true); } public void loadGeonameFinished(Context context, GeoName geoname ) { mHandler.progress(false); mHandler.showGeolocation(geoname); } public void loadGeonameFailed(Context context, String reason) { mHandler.progress(false); mHandler.errorGeolocation(reason); } }; }
true
true
public void bindView(final View view, final Context context, Cursor cursor) { ViewHolder vh = (ViewHolder) view.getTag(); if (hmAccounts==null) { hmAccounts = new HashMap<Long,String>(); if (MustardApplication.DEBUG) Log.i(TAG, "############################## CREATO hmAccounts ##########"); } final long id = cursor.getLong(mIdIdx); final long statusId = cursor.getLong(mStatusIdIdx); view.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // openContextMenu(v); onShowNoticeMenu(v,id); } }); view.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { openContextMenu(v); return true; } }); if (MustardApplication.DEBUG) Log.v(TAG, "Binding id=" + id + " " + statusId + " cursor=" + cursor); long accountId = cursor.getLong(mIdAccountIdx); if (vh.screen_name != null) { vh.screen_name.setText(cursor.getString(mScreenNameIdx)); vh.screen_name.setTextSize(mTextSizeSmall); } if ( mMergedTimeline && vh.account_name != null) { if(!hmAccounts.containsKey(accountId)) { Cursor c = mDbHelper.fetchAccount(accountId); String account = ""; if (c.moveToNext()) { account=c.getString(c.getColumnIndex(MustardDbAdapter.KEY_USER)); String instance = c.getString(c.getColumnIndex(MustardDbAdapter.KEY_INSTANCE)); try { URL url = new URL(instance); account += "@" + url.getHost() + url.getPath(); // Log.i(TAG, "AccountID " + accountId + " => " + account + " " + host + " (" +instance +")"); } catch (Exception e) { e.printStackTrace(); } } else { Log.e(TAG,"NO ACCOUNT WITH ID: " + accountId); } c.close(); hmAccounts.put(accountId, account); } vh.account_name.setText(hmAccounts.get(accountId)); vh.account_name.setVisibility(View.VISIBLE); vh.account_name.setTextSize(mTextSizeSmall); } String source = cursor.getString(mSourceIdx) ; if (source != null && !"".equals(source)) { source = Html.fromHtml("&nbsp;from " + source.replace("&lt;", "<").replace("&gt;", ">"))+" "; if (source.length()>15) source = source.substring(0, 15) +".."; else source=source.trim(); } vh.source.setText(source, BufferType.SPANNABLE); vh.source.setTextSize(mTextSizeSmall); long inreplyto = cursor.getLong(mInReplyToIdx); TextView vr = vh.in_reply_to; if (vr != null) { if (inreplyto > 0) { vr.setText(Html.fromHtml("&nbsp;<a href='statusnet://conversation/"+id+"' >in context</a>") , BufferType.SPANNABLE); vr.setVisibility(View.VISIBLE); vr.setTextSize(mTextSizeSmall); } else { vr.setVisibility(View.GONE); } } if (vh.profile_image != null) { String profileUrl = cursor.getString(mProfileImageIdx); if (profileUrl != null && !"".equals(profileUrl)) { vh.profile_image.setRemoteURI(profileUrl); vh.profile_image.loadImage(); } if(mLayoutNewButton) { vh.profile_image.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { openContextMenu(v); } }); } vh.profile_image.setFocusable(mLayoutNewButton); } Date d = new Date(); d.setTime(cursor.getLong(mDatetimeIdx)); vh.datetime.setText(DateUtils.getRelativeDate( d )); vh.datetime.setTextSize(mTextSizeSmall); if(mPreferences.getBoolean(Preferences.COMPACT_VIEW, false) ) { if (vh.bottomRow!=null) vh.bottomRow.setVisibility(View.GONE); } else { if(vh.conversation != null) { if (inreplyto > 0) { vh.conversation.setImageResource(R.drawable.conversation); vh.conversation.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // doOpenConversation(statusId); doOpenConversation(id); } }); } else { vh.conversation.setImageResource(R.drawable.conversation_disabled); } vh.conversation.setFocusable(mLayoutNewButton); } int geo = cursor.getInt(mGeolocationIdx); if (geo == 1) { final String lon = cursor.getString(mLonIdx); final String lat = cursor.getString(mLatIdx); vh.geolocation.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { doShowLocation(lon, lat); } }); vh.geolocation.setImageResource(R.drawable.pin_button); } else { vh.geolocation.setImageResource(R.drawable.pin_disabled); } vh.geolocation.setFocusable(mLayoutNewButton); int attachment = cursor.getInt(mAttachmentIdx); if (attachment == 1) { vh.attachment.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { onShowAttachemntList(id); } }); vh.attachment.setImageResource(R.drawable.attachment); } else { vh.attachment.setImageResource(R.drawable.attachment_disabled); } vh.attachment.setFocusable(mLayoutNewButton); } String status = cursor.getString(mStatusIdx); if (status.indexOf("<")>=0) status=status.replaceAll("<", "&lt;"); if(status.indexOf(">")>=0) status=status.replaceAll(">","&gt;"); TextView v = vh.status; v.setText(Html.fromHtml(status).toString(), BufferType.SPANNABLE); Linkify.addLinks(v, Linkify.WEB_URLS); StatusNetUtils.linkifyUsers(v); if(mStatusNet.isTwitterInstance()) { StatusNetUtils.linkifyGroupsForTwitter(v); StatusNetUtils.linkifyTagsForTwitter(v); } else { StatusNetUtils.linkifyGroups(v); StatusNetUtils.linkifyTags(v); } v.setTextSize(mTextSizeNormal); if (vh.noticeinfo !=null) { if(mLayoutNewButton) { vh.noticeinfo.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { onShowNoticeAction(id); } }); } else { vh.noticeinfo.setVisibility(View.GONE); } vh.noticeinfo.setFocusable(mLayoutNewButton); } }
public void bindView(final View view, final Context context, Cursor cursor) { ViewHolder vh = (ViewHolder) view.getTag(); if (hmAccounts==null) { hmAccounts = new HashMap<Long,String>(); if (MustardApplication.DEBUG) Log.i(TAG, "############################## CREATO hmAccounts ##########"); } final long id = cursor.getLong(mIdIdx); final long statusId = cursor.getLong(mStatusIdIdx); view.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // openContextMenu(v); onShowNoticeMenu(v,id); } }); view.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { openContextMenu(v); return true; } }); if (MustardApplication.DEBUG) Log.v(TAG, "Binding id=" + id + " " + statusId + " cursor=" + cursor); long accountId = cursor.getLong(mIdAccountIdx); if (vh.screen_name != null) { vh.screen_name.setText(cursor.getString(mScreenNameIdx)); vh.screen_name.setTextSize(mTextSizeSmall); } if ( mMergedTimeline && vh.account_name != null) { if(!hmAccounts.containsKey(accountId)) { Cursor c = mDbHelper.fetchAccount(accountId); String account = ""; if (c.moveToNext()) { account=c.getString(c.getColumnIndex(MustardDbAdapter.KEY_USER)); String instance = c.getString(c.getColumnIndex(MustardDbAdapter.KEY_INSTANCE)); try { URL url = new URL(instance); account += "@" + url.getHost() + url.getPath(); // Log.i(TAG, "AccountID " + accountId + " => " + account + " " + host + " (" +instance +")"); } catch (Exception e) { e.printStackTrace(); } } else { Log.e(TAG,"NO ACCOUNT WITH ID: " + accountId); } c.close(); hmAccounts.put(accountId, account); } vh.account_name.setText(hmAccounts.get(accountId)); vh.account_name.setVisibility(View.VISIBLE); vh.account_name.setTextSize(mTextSizeSmall); } String source = cursor.getString(mSourceIdx) ; if (source != null && !"".equals(source)) { source = Html.fromHtml("&nbsp;from&nbsp;" + source.replace("&lt;", "<").replace("&gt;", ">"))+" "; if (source.trim().length()>15) source = source.trim().substring(0, 15) +".."; else source=source.trim(); } vh.source.setText(source, BufferType.SPANNABLE); vh.source.setTextSize(mTextSizeSmall); long inreplyto = cursor.getLong(mInReplyToIdx); TextView vr = vh.in_reply_to; if (vr != null) { if (inreplyto > 0) { vr.setText(Html.fromHtml("&nbsp;<a href='statusnet://conversation/"+id+"' >in context</a>") , BufferType.SPANNABLE); vr.setVisibility(View.VISIBLE); vr.setTextSize(mTextSizeSmall); } else { vr.setVisibility(View.GONE); } } if (vh.profile_image != null) { String profileUrl = cursor.getString(mProfileImageIdx); if (profileUrl != null && !"".equals(profileUrl)) { vh.profile_image.setRemoteURI(profileUrl); vh.profile_image.loadImage(); } if(mLayoutNewButton) { vh.profile_image.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { openContextMenu(v); } }); } vh.profile_image.setFocusable(mLayoutNewButton); } Date d = new Date(); d.setTime(cursor.getLong(mDatetimeIdx)); vh.datetime.setText(DateUtils.getRelativeDate( d )); vh.datetime.setTextSize(mTextSizeSmall); if(mPreferences.getBoolean(Preferences.COMPACT_VIEW, false) ) { if (vh.bottomRow!=null) vh.bottomRow.setVisibility(View.GONE); } else { if(vh.conversation != null) { if (inreplyto > 0) { vh.conversation.setImageResource(R.drawable.conversation); vh.conversation.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // doOpenConversation(statusId); doOpenConversation(id); } }); } else { vh.conversation.setImageResource(R.drawable.conversation_disabled); } vh.conversation.setFocusable(mLayoutNewButton); } int geo = cursor.getInt(mGeolocationIdx); if (geo == 1) { final String lon = cursor.getString(mLonIdx); final String lat = cursor.getString(mLatIdx); vh.geolocation.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { doShowLocation(lon, lat); } }); vh.geolocation.setImageResource(R.drawable.pin_button); } else { vh.geolocation.setImageResource(R.drawable.pin_disabled); } vh.geolocation.setFocusable(mLayoutNewButton); int attachment = cursor.getInt(mAttachmentIdx); if (attachment == 1) { vh.attachment.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { onShowAttachemntList(id); } }); vh.attachment.setImageResource(R.drawable.attachment); } else { vh.attachment.setImageResource(R.drawable.attachment_disabled); } vh.attachment.setFocusable(mLayoutNewButton); } String status = cursor.getString(mStatusIdx); if (status.indexOf("<")>=0) status=status.replaceAll("<", "&lt;"); if(status.indexOf(">")>=0) status=status.replaceAll(">","&gt;"); TextView v = vh.status; v.setText(Html.fromHtml(status).toString(), BufferType.SPANNABLE); Linkify.addLinks(v, Linkify.WEB_URLS); StatusNetUtils.linkifyUsers(v); if(mStatusNet.isTwitterInstance()) { StatusNetUtils.linkifyGroupsForTwitter(v); StatusNetUtils.linkifyTagsForTwitter(v); } else { StatusNetUtils.linkifyGroups(v); StatusNetUtils.linkifyTags(v); } v.setTextSize(mTextSizeNormal); if (vh.noticeinfo !=null) { if(mLayoutNewButton) { vh.noticeinfo.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { onShowNoticeAction(id); } }); } else { vh.noticeinfo.setVisibility(View.GONE); } vh.noticeinfo.setFocusable(mLayoutNewButton); } }
diff --git a/src/com/vitaltech/bioink/DataSimulatorPlus.java b/src/com/vitaltech/bioink/DataSimulatorPlus.java index 939c0a3..1115503 100644 --- a/src/com/vitaltech/bioink/DataSimulatorPlus.java +++ b/src/com/vitaltech/bioink/DataSimulatorPlus.java @@ -1,268 +1,273 @@ package com.vitaltech.bioink; import android.util.Log; public class DataSimulatorPlus { private static final String TAG = DataSimulatorPlus.class.getSimpleName(); private static final Boolean DEBUG = MainActivity.DEBUG; private DataProcess dataProcessor; private String u1 = "user1"; private String u2 = "user2"; private String u3 = "user3"; private String u4 = "user4"; private long wait = 2500; public DataSimulatorPlus(DataProcess dp){ this.dataProcessor = dp; } public void run(){ if(DEBUG) Log.d(TAG, "Starting simulator"); int loop = 0; + Boolean run = true; try { - while(true){ + while(run){ if(DEBUG) Log.d(TAG, "simulator loop " + loop++); fourCorners(); // no Z plane fourCornersZ(); // in Z plane Thread.sleep(2 * wait); walkabout(); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "four sides"); dataProcessor.push(u1, BiometricType.HEARTRATE, 0.5f * dataProcessor.maxHR); dataProcessor.push(u1, BiometricType.RESPIRATION, 0.2f * dataProcessor.maxResp); dataProcessor.push(u2, BiometricType.HEARTRATE, 0.5f * dataProcessor.maxHR); dataProcessor.push(u2, BiometricType.RESPIRATION, 0.8f * dataProcessor.maxResp); dataProcessor.push(u3, BiometricType.HEARTRATE, 0.2f * dataProcessor.maxHR); dataProcessor.push(u3, BiometricType.RESPIRATION, 0.5f * dataProcessor.maxResp); dataProcessor.push(u4, BiometricType.HEARTRATE, 0.8f * dataProcessor.maxHR); dataProcessor.push(u4, BiometricType.RESPIRATION, 0.5f * dataProcessor.maxResp); Thread.sleep(4 * wait); if(DEBUG) Log.d(TAG, "two pairs"); threeTypes(u1, 0.3f); threeTypes(u2, 0.3f); threeTypes(u3, 0.7f); threeTypes(u4, 0.7f); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "one pair"); threeTypes(u1, 0.5f); threeTypes(u2, 0.5f); threeTypes(u3, 0.5f); threeTypes(u4, 0.5f); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "3 to 1 split"); threeTypes(u1, 0.3f); threeTypes(u2, 0.3f); threeTypes(u3, 0.3f); threeTypes(u4, 0.7f); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "transition to 2 pairs"); threeTypes(u3, 0.7f); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "all 90% heart rate"); syncUsers(BiometricType.HEARTRATE, 0.9f * dataProcessor.maxHR); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "all 10% respiration rate"); syncUsers(BiometricType.RESPIRATION, 0.1f * dataProcessor.maxResp); Thread.sleep(2 * wait); // FIXME disabled 3rd axis // if(DEBUG) Log.d(TAG, "all 10% HRV"); // syncUsers(BiometricType.RR, 0.1f * dataProcessor.maxResp); // Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "all 10% heart rate"); syncUsers(BiometricType.HEARTRATE, 0.1f * dataProcessor.maxHR); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "center all"); syncUsers(BiometricType.HEARTRATE, 0.5f * dataProcessor.maxHR); syncUsers(BiometricType.RESPIRATION, 0.5f * dataProcessor.maxResp); // FIXME disabled 3rd axis syncUsers(BiometricType.RR, 0.5f * dataProcessor.maxRR); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "u1 gets 100% heart rate"); dataProcessor.push(u1, BiometricType.HEARTRATE, 1f * dataProcessor.maxHR); Thread.sleep(wait); if(DEBUG) Log.d(TAG, "u2 gets 100% respirations"); dataProcessor.push(u2, BiometricType.RESPIRATION, 1f * dataProcessor.maxResp); Thread.sleep(wait); if(DEBUG) Log.d(TAG, "u3 gets 0% respirations"); dataProcessor.push(u3, BiometricType.RESPIRATION, 0f); Thread.sleep(wait); if(DEBUG) Log.d(TAG, "u4 gets 0% heart rate"); dataProcessor.push(u4, BiometricType.HEARTRATE, 0f); Thread.sleep(2 * wait); // FIXME disabled 3rd axis // if(DEBUG) Log.d(TAG, "u1 gets 100% RR"); // dataProcessor.push(u1, BiometricType.RR, 1f); // Thread.sleep(wait); // if(DEBUG) Log.d(TAG, "u2 gets 100% RR"); // dataProcessor.push(u2, BiometricType.RR, 1f); // Thread.sleep(wait); // if(DEBUG) Log.d(TAG, "u3 gets 0% RR"); // dataProcessor.push(u3, BiometricType.RR, 0f); // Thread.sleep(wait); // if(DEBUG) Log.d(TAG, "u4 gets 0% RR"); // dataProcessor.push(u4, BiometricType.RR, 0f); // Thread.sleep(2 * wait); } } catch (InterruptedException e) { - Log.e(TAG, e.toString()); + run = false; + Log.e(TAG, "caught interrupt exception : " + e.toString()); + } finally { + run = false; + Log.d(TAG, "finally after " + loop); } - Log.e(TAG, "exiting simulator after " + loop); + Log.d(TAG, "exiting after " + loop); } // single user gets one value across three types private void threeTypes(String user, float value){ dataProcessor.push(user, BiometricType.HEARTRATE, value * dataProcessor.maxHR); dataProcessor.push(user, BiometricType.RESPIRATION, value * dataProcessor.maxResp); // FIXME: disabled 3rd axis dataProcessor.push(user, BiometricType.RR, value * 1.0f); } // all users get one value across one type private void syncUsers(BiometricType type, float value){ dataProcessor.push(u1, type, value); dataProcessor.push(u2, type, value); dataProcessor.push(u3, type, value); dataProcessor.push(u4, type, value); } private void fourCorners(){ dataProcessor.push("staticA", BiometricType.HEARTRATE, 0f); // 0,0 dataProcessor.push("staticA", BiometricType.RESPIRATION, 0f); dataProcessor.push("staticA", BiometricType.HRV, 0f); dataProcessor.push("staticB", BiometricType.HEARTRATE, 0f); // 0,1 dataProcessor.push("staticB", BiometricType.RESPIRATION, 1f * dataProcessor.maxResp); dataProcessor.push("staticB", BiometricType.HRV, 0f); dataProcessor.push("staticC", BiometricType.HEARTRATE, 1f * dataProcessor.maxHR); // 1,0 dataProcessor.push("staticC", BiometricType.RESPIRATION, 0f); dataProcessor.push("staticC", BiometricType.HRV, 0f); dataProcessor.push("staticD", BiometricType.HEARTRATE, 1f * dataProcessor.maxHR); // 1,1 dataProcessor.push("staticD", BiometricType.RESPIRATION, 1f * dataProcessor.maxResp); dataProcessor.push("staticD", BiometricType.HRV, 0f); dataProcessor.push("center", BiometricType.HEARTRATE, 0.5f * dataProcessor.maxHR); dataProcessor.push("center", BiometricType.RESPIRATION, 0.5f * dataProcessor.maxResp); dataProcessor.push("center", BiometricType.HRV, 0.5f * dataProcessor.maxHRV); } private void fourCornersZ(){ dataProcessor.push("staticAz", BiometricType.HEARTRATE, 0f); // 0,0 dataProcessor.push("staticAz", BiometricType.RESPIRATION, 0f); dataProcessor.push("staticAz", BiometricType.HRV, 1f * dataProcessor.maxHRV); dataProcessor.push("staticBz", BiometricType.HEARTRATE, 0f); // 0,1 dataProcessor.push("staticBz", BiometricType.RESPIRATION, 1f * dataProcessor.maxResp); dataProcessor.push("staticBz", BiometricType.HRV, 1f * dataProcessor.maxHRV); dataProcessor.push("staticCz", BiometricType.HEARTRATE, 1f * dataProcessor.maxHR); // 1,0 dataProcessor.push("staticCz", BiometricType.RESPIRATION, 0f); dataProcessor.push("staticCz", BiometricType.HRV, 1f * dataProcessor.maxHRV); dataProcessor.push("staticDz", BiometricType.HEARTRATE, 1 * dataProcessor.maxHR); // 1,1 dataProcessor.push("staticDz", BiometricType.RESPIRATION, 1 * dataProcessor.maxResp); dataProcessor.push("staticDz", BiometricType.HRV, 1f * dataProcessor.maxHRV); } private void walkabout(){ Log.d(TAG, "walkabout started"); try { dataProcessor.push(u1, BiometricType.HEARTRATE, 0 * dataProcessor.maxHR); // 0,0 dataProcessor.push(u1, BiometricType.RESPIRATION, 0 * dataProcessor.maxResp); Thread.sleep(2 * wait); // dataProcessor.push(u1, BiometricType.HEARTRATE, 0 * dataProcessor.maxHR); // 0,1 dataProcessor.push(u1, BiometricType.RESPIRATION, 1 * dataProcessor.maxResp); Thread.sleep(2 * wait); dataProcessor.push(u1, BiometricType.HEARTRATE, 1 * dataProcessor.maxHR); // 1,0 dataProcessor.push(u1, BiometricType.RESPIRATION, 0 * dataProcessor.maxResp); Thread.sleep(2 * wait); // dataProcessor.push(u1, BiometricType.HEARTRATE, 1 * dataProcessor.maxHR); // 1,1 dataProcessor.push(u1, BiometricType.RESPIRATION, 1 * dataProcessor.maxResp); Thread.sleep(2 * wait); Log.d(TAG, "intervals"); dataProcessor.push(u1, BiometricType.HEARTRATE, 0.9f * dataProcessor.maxHR); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HEARTRATE, 0.8f * dataProcessor.maxHR); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HEARTRATE, 0.7f * dataProcessor.maxHR); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HEARTRATE, 0.6f * dataProcessor.maxHR); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HEARTRATE, 0.5f * dataProcessor.maxHR); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HEARTRATE, 0.4f * dataProcessor.maxHR); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HEARTRATE, 0.3f * dataProcessor.maxHR); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HEARTRATE, 0.2f * dataProcessor.maxHR); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HEARTRATE, 0.1f * dataProcessor.maxHR); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HEARTRATE, 0f); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.RESPIRATION, 0.9f * dataProcessor.maxResp); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.RESPIRATION, 0.8f * dataProcessor.maxResp); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.RESPIRATION, 0.7f * dataProcessor.maxResp); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.RESPIRATION, 0.6f * dataProcessor.maxResp); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.RESPIRATION, 0.5f * dataProcessor.maxResp); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.RESPIRATION, 0.4f * dataProcessor.maxResp); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.RESPIRATION, 0.3f * dataProcessor.maxResp); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.RESPIRATION, 0.2f * dataProcessor.maxResp); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.RESPIRATION, 0.1f * dataProcessor.maxResp); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.RESPIRATION, 0f); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HRV, 0.9f * dataProcessor.maxHRV); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HRV, 0.8f * dataProcessor.maxHRV); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HRV, 0.7f * dataProcessor.maxHRV); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HRV, 0.6f * dataProcessor.maxHRV); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HRV, 0.5f * dataProcessor.maxHRV); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HRV, 0.4f * dataProcessor.maxHRV); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HRV, 0.3f * dataProcessor.maxHRV); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HRV, 0.2f * dataProcessor.maxHRV); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HRV, 0.1f * dataProcessor.maxHRV); Thread.sleep(1 * wait); dataProcessor.push(u1, BiometricType.HRV, 0f); Log.d(TAG, "walkabout complete"); Thread.sleep(2 * wait); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
false
true
public void run(){ if(DEBUG) Log.d(TAG, "Starting simulator"); int loop = 0; try { while(true){ if(DEBUG) Log.d(TAG, "simulator loop " + loop++); fourCorners(); // no Z plane fourCornersZ(); // in Z plane Thread.sleep(2 * wait); walkabout(); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "four sides"); dataProcessor.push(u1, BiometricType.HEARTRATE, 0.5f * dataProcessor.maxHR); dataProcessor.push(u1, BiometricType.RESPIRATION, 0.2f * dataProcessor.maxResp); dataProcessor.push(u2, BiometricType.HEARTRATE, 0.5f * dataProcessor.maxHR); dataProcessor.push(u2, BiometricType.RESPIRATION, 0.8f * dataProcessor.maxResp); dataProcessor.push(u3, BiometricType.HEARTRATE, 0.2f * dataProcessor.maxHR); dataProcessor.push(u3, BiometricType.RESPIRATION, 0.5f * dataProcessor.maxResp); dataProcessor.push(u4, BiometricType.HEARTRATE, 0.8f * dataProcessor.maxHR); dataProcessor.push(u4, BiometricType.RESPIRATION, 0.5f * dataProcessor.maxResp); Thread.sleep(4 * wait); if(DEBUG) Log.d(TAG, "two pairs"); threeTypes(u1, 0.3f); threeTypes(u2, 0.3f); threeTypes(u3, 0.7f); threeTypes(u4, 0.7f); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "one pair"); threeTypes(u1, 0.5f); threeTypes(u2, 0.5f); threeTypes(u3, 0.5f); threeTypes(u4, 0.5f); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "3 to 1 split"); threeTypes(u1, 0.3f); threeTypes(u2, 0.3f); threeTypes(u3, 0.3f); threeTypes(u4, 0.7f); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "transition to 2 pairs"); threeTypes(u3, 0.7f); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "all 90% heart rate"); syncUsers(BiometricType.HEARTRATE, 0.9f * dataProcessor.maxHR); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "all 10% respiration rate"); syncUsers(BiometricType.RESPIRATION, 0.1f * dataProcessor.maxResp); Thread.sleep(2 * wait); // FIXME disabled 3rd axis // if(DEBUG) Log.d(TAG, "all 10% HRV"); // syncUsers(BiometricType.RR, 0.1f * dataProcessor.maxResp); // Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "all 10% heart rate"); syncUsers(BiometricType.HEARTRATE, 0.1f * dataProcessor.maxHR); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "center all"); syncUsers(BiometricType.HEARTRATE, 0.5f * dataProcessor.maxHR); syncUsers(BiometricType.RESPIRATION, 0.5f * dataProcessor.maxResp); // FIXME disabled 3rd axis syncUsers(BiometricType.RR, 0.5f * dataProcessor.maxRR); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "u1 gets 100% heart rate"); dataProcessor.push(u1, BiometricType.HEARTRATE, 1f * dataProcessor.maxHR); Thread.sleep(wait); if(DEBUG) Log.d(TAG, "u2 gets 100% respirations"); dataProcessor.push(u2, BiometricType.RESPIRATION, 1f * dataProcessor.maxResp); Thread.sleep(wait); if(DEBUG) Log.d(TAG, "u3 gets 0% respirations"); dataProcessor.push(u3, BiometricType.RESPIRATION, 0f); Thread.sleep(wait); if(DEBUG) Log.d(TAG, "u4 gets 0% heart rate"); dataProcessor.push(u4, BiometricType.HEARTRATE, 0f); Thread.sleep(2 * wait); // FIXME disabled 3rd axis // if(DEBUG) Log.d(TAG, "u1 gets 100% RR"); // dataProcessor.push(u1, BiometricType.RR, 1f); // Thread.sleep(wait); // if(DEBUG) Log.d(TAG, "u2 gets 100% RR"); // dataProcessor.push(u2, BiometricType.RR, 1f); // Thread.sleep(wait); // if(DEBUG) Log.d(TAG, "u3 gets 0% RR"); // dataProcessor.push(u3, BiometricType.RR, 0f); // Thread.sleep(wait); // if(DEBUG) Log.d(TAG, "u4 gets 0% RR"); // dataProcessor.push(u4, BiometricType.RR, 0f); // Thread.sleep(2 * wait); } } catch (InterruptedException e) { Log.e(TAG, e.toString()); } Log.e(TAG, "exiting simulator after " + loop); }
public void run(){ if(DEBUG) Log.d(TAG, "Starting simulator"); int loop = 0; Boolean run = true; try { while(run){ if(DEBUG) Log.d(TAG, "simulator loop " + loop++); fourCorners(); // no Z plane fourCornersZ(); // in Z plane Thread.sleep(2 * wait); walkabout(); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "four sides"); dataProcessor.push(u1, BiometricType.HEARTRATE, 0.5f * dataProcessor.maxHR); dataProcessor.push(u1, BiometricType.RESPIRATION, 0.2f * dataProcessor.maxResp); dataProcessor.push(u2, BiometricType.HEARTRATE, 0.5f * dataProcessor.maxHR); dataProcessor.push(u2, BiometricType.RESPIRATION, 0.8f * dataProcessor.maxResp); dataProcessor.push(u3, BiometricType.HEARTRATE, 0.2f * dataProcessor.maxHR); dataProcessor.push(u3, BiometricType.RESPIRATION, 0.5f * dataProcessor.maxResp); dataProcessor.push(u4, BiometricType.HEARTRATE, 0.8f * dataProcessor.maxHR); dataProcessor.push(u4, BiometricType.RESPIRATION, 0.5f * dataProcessor.maxResp); Thread.sleep(4 * wait); if(DEBUG) Log.d(TAG, "two pairs"); threeTypes(u1, 0.3f); threeTypes(u2, 0.3f); threeTypes(u3, 0.7f); threeTypes(u4, 0.7f); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "one pair"); threeTypes(u1, 0.5f); threeTypes(u2, 0.5f); threeTypes(u3, 0.5f); threeTypes(u4, 0.5f); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "3 to 1 split"); threeTypes(u1, 0.3f); threeTypes(u2, 0.3f); threeTypes(u3, 0.3f); threeTypes(u4, 0.7f); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "transition to 2 pairs"); threeTypes(u3, 0.7f); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "all 90% heart rate"); syncUsers(BiometricType.HEARTRATE, 0.9f * dataProcessor.maxHR); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "all 10% respiration rate"); syncUsers(BiometricType.RESPIRATION, 0.1f * dataProcessor.maxResp); Thread.sleep(2 * wait); // FIXME disabled 3rd axis // if(DEBUG) Log.d(TAG, "all 10% HRV"); // syncUsers(BiometricType.RR, 0.1f * dataProcessor.maxResp); // Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "all 10% heart rate"); syncUsers(BiometricType.HEARTRATE, 0.1f * dataProcessor.maxHR); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "center all"); syncUsers(BiometricType.HEARTRATE, 0.5f * dataProcessor.maxHR); syncUsers(BiometricType.RESPIRATION, 0.5f * dataProcessor.maxResp); // FIXME disabled 3rd axis syncUsers(BiometricType.RR, 0.5f * dataProcessor.maxRR); Thread.sleep(2 * wait); if(DEBUG) Log.d(TAG, "u1 gets 100% heart rate"); dataProcessor.push(u1, BiometricType.HEARTRATE, 1f * dataProcessor.maxHR); Thread.sleep(wait); if(DEBUG) Log.d(TAG, "u2 gets 100% respirations"); dataProcessor.push(u2, BiometricType.RESPIRATION, 1f * dataProcessor.maxResp); Thread.sleep(wait); if(DEBUG) Log.d(TAG, "u3 gets 0% respirations"); dataProcessor.push(u3, BiometricType.RESPIRATION, 0f); Thread.sleep(wait); if(DEBUG) Log.d(TAG, "u4 gets 0% heart rate"); dataProcessor.push(u4, BiometricType.HEARTRATE, 0f); Thread.sleep(2 * wait); // FIXME disabled 3rd axis // if(DEBUG) Log.d(TAG, "u1 gets 100% RR"); // dataProcessor.push(u1, BiometricType.RR, 1f); // Thread.sleep(wait); // if(DEBUG) Log.d(TAG, "u2 gets 100% RR"); // dataProcessor.push(u2, BiometricType.RR, 1f); // Thread.sleep(wait); // if(DEBUG) Log.d(TAG, "u3 gets 0% RR"); // dataProcessor.push(u3, BiometricType.RR, 0f); // Thread.sleep(wait); // if(DEBUG) Log.d(TAG, "u4 gets 0% RR"); // dataProcessor.push(u4, BiometricType.RR, 0f); // Thread.sleep(2 * wait); } } catch (InterruptedException e) { run = false; Log.e(TAG, "caught interrupt exception : " + e.toString()); } finally { run = false; Log.d(TAG, "finally after " + loop); } Log.d(TAG, "exiting after " + loop); }
diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/BusinessRuleTaskActivityBehavior.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/BusinessRuleTaskActivityBehavior.java index d5a578dd..9b97c443 100644 --- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/BusinessRuleTaskActivityBehavior.java +++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/BusinessRuleTaskActivityBehavior.java @@ -1,101 +1,101 @@ /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.engine.impl.bpmn.behavior; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.activiti.engine.delegate.Expression; import org.activiti.engine.impl.pvm.PvmProcessDefinition; import org.activiti.engine.impl.pvm.delegate.ActivityExecution; import org.activiti.engine.impl.rules.RulesAgendaFilter; import org.activiti.engine.impl.rules.RulesHelper; import org.drools.KnowledgeBase; import org.drools.runtime.StatefulKnowledgeSession; /** * activity implementation of the BPMN 2.0 business rule task. * * @author Tijs Rademakers */ public class BusinessRuleTaskActivityBehavior extends TaskActivityBehavior { protected Set<Expression> variablesInputExpressions = new HashSet<Expression>(); protected Set<Expression> rulesExpressions = new HashSet<Expression>(); protected boolean exclude = false; protected String resultVariable; public BusinessRuleTaskActivityBehavior() {} public void execute(ActivityExecution execution) throws Exception { PvmProcessDefinition processDefinition = execution.getActivity().getProcessDefinition(); String deploymentId = processDefinition.getDeploymentId(); KnowledgeBase knowledgeBase = RulesHelper.findKnowledgeBaseByDeploymentId(deploymentId); StatefulKnowledgeSession ksession = knowledgeBase.newStatefulKnowledgeSession(); if (variablesInputExpressions != null) { Iterator<Expression> itVariable = variablesInputExpressions.iterator(); while (itVariable.hasNext()) { Expression variable = itVariable.next(); ksession.insert(variable.getValue(execution)); } } if (rulesExpressions.size() > 0) { RulesAgendaFilter filter = new RulesAgendaFilter(); Iterator<Expression> itRuleNames = rulesExpressions.iterator(); while (itRuleNames.hasNext()) { Expression ruleName = itRuleNames.next(); filter.addSuffic(ruleName.getValue(execution).toString()); } - filter.setAccept(exclude); + filter.setAccept(!exclude); ksession.fireAllRules(filter); } else { ksession.fireAllRules(); } Collection<Object> ruleOutputObjects = ksession.getObjects(); if (ruleOutputObjects != null && ruleOutputObjects.size() > 0) { Collection<Object> outputVariables = new ArrayList<Object>(); for (Object object : ruleOutputObjects) { outputVariables.add(object); } execution.setVariable(resultVariable, outputVariables); } ksession.dispose(); leave(execution); } public void addRuleVariableInputIdExpression(Expression inputId) { this.variablesInputExpressions.add(inputId); } public void addRuleIdExpression(Expression inputId) { this.rulesExpressions.add(inputId); } public void setExclude(boolean exclude) { this.exclude = exclude; } public void setResultVariable(String resultVariableName) { this.resultVariable = resultVariableName; } }
true
true
public void execute(ActivityExecution execution) throws Exception { PvmProcessDefinition processDefinition = execution.getActivity().getProcessDefinition(); String deploymentId = processDefinition.getDeploymentId(); KnowledgeBase knowledgeBase = RulesHelper.findKnowledgeBaseByDeploymentId(deploymentId); StatefulKnowledgeSession ksession = knowledgeBase.newStatefulKnowledgeSession(); if (variablesInputExpressions != null) { Iterator<Expression> itVariable = variablesInputExpressions.iterator(); while (itVariable.hasNext()) { Expression variable = itVariable.next(); ksession.insert(variable.getValue(execution)); } } if (rulesExpressions.size() > 0) { RulesAgendaFilter filter = new RulesAgendaFilter(); Iterator<Expression> itRuleNames = rulesExpressions.iterator(); while (itRuleNames.hasNext()) { Expression ruleName = itRuleNames.next(); filter.addSuffic(ruleName.getValue(execution).toString()); } filter.setAccept(exclude); ksession.fireAllRules(filter); } else { ksession.fireAllRules(); } Collection<Object> ruleOutputObjects = ksession.getObjects(); if (ruleOutputObjects != null && ruleOutputObjects.size() > 0) { Collection<Object> outputVariables = new ArrayList<Object>(); for (Object object : ruleOutputObjects) { outputVariables.add(object); } execution.setVariable(resultVariable, outputVariables); } ksession.dispose(); leave(execution); }
public void execute(ActivityExecution execution) throws Exception { PvmProcessDefinition processDefinition = execution.getActivity().getProcessDefinition(); String deploymentId = processDefinition.getDeploymentId(); KnowledgeBase knowledgeBase = RulesHelper.findKnowledgeBaseByDeploymentId(deploymentId); StatefulKnowledgeSession ksession = knowledgeBase.newStatefulKnowledgeSession(); if (variablesInputExpressions != null) { Iterator<Expression> itVariable = variablesInputExpressions.iterator(); while (itVariable.hasNext()) { Expression variable = itVariable.next(); ksession.insert(variable.getValue(execution)); } } if (rulesExpressions.size() > 0) { RulesAgendaFilter filter = new RulesAgendaFilter(); Iterator<Expression> itRuleNames = rulesExpressions.iterator(); while (itRuleNames.hasNext()) { Expression ruleName = itRuleNames.next(); filter.addSuffic(ruleName.getValue(execution).toString()); } filter.setAccept(!exclude); ksession.fireAllRules(filter); } else { ksession.fireAllRules(); } Collection<Object> ruleOutputObjects = ksession.getObjects(); if (ruleOutputObjects != null && ruleOutputObjects.size() > 0) { Collection<Object> outputVariables = new ArrayList<Object>(); for (Object object : ruleOutputObjects) { outputVariables.add(object); } execution.setVariable(resultVariable, outputVariables); } ksession.dispose(); leave(execution); }
diff --git a/svnkit/src/org/tmatesoft/svn/core/internal/io/dav/DAVRepository.java b/svnkit/src/org/tmatesoft/svn/core/internal/io/dav/DAVRepository.java index d2e172ec0..4c98a14e1 100644 --- a/svnkit/src/org/tmatesoft/svn/core/internal/io/dav/DAVRepository.java +++ b/svnkit/src/org/tmatesoft/svn/core/internal/io/dav/DAVRepository.java @@ -1,1330 +1,1332 @@ /* * ==================================================================== * Copyright (c) 2004-2009 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.io.dav; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.tmatesoft.svn.core.ISVNDirEntryHandler; import org.tmatesoft.svn.core.ISVNLogEntryHandler; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNDirEntry; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLock; import org.tmatesoft.svn.core.SVNLogEntry; import org.tmatesoft.svn.core.SVNMergeInfo; import org.tmatesoft.svn.core.SVNMergeInfoInheritance; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNRevisionProperty; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.internal.io.dav.handlers.DAVDateRevisionHandler; import org.tmatesoft.svn.core.internal.io.dav.handlers.DAVDeletedRevisionHandler; import org.tmatesoft.svn.core.internal.io.dav.handlers.DAVEditorHandler; import org.tmatesoft.svn.core.internal.io.dav.handlers.DAVFileRevisionHandler; import org.tmatesoft.svn.core.internal.io.dav.handlers.DAVLocationSegmentsHandler; import org.tmatesoft.svn.core.internal.io.dav.handlers.DAVLocationsHandler; import org.tmatesoft.svn.core.internal.io.dav.handlers.DAVLogHandler; import org.tmatesoft.svn.core.internal.io.dav.handlers.DAVMergeInfoHandler; import org.tmatesoft.svn.core.internal.io.dav.handlers.DAVProppatchHandler; import org.tmatesoft.svn.core.internal.io.dav.handlers.DAVReplayHandler; import org.tmatesoft.svn.core.internal.io.dav.http.HTTPStatus; import org.tmatesoft.svn.core.internal.io.dav.http.IHTTPConnectionFactory; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNHashSet; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.SVNDepthFilterEditor; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.io.ISVNEditor; import org.tmatesoft.svn.core.io.ISVNFileRevisionHandler; import org.tmatesoft.svn.core.io.ISVNLocationEntryHandler; import org.tmatesoft.svn.core.io.ISVNLocationSegmentHandler; import org.tmatesoft.svn.core.io.ISVNLockHandler; import org.tmatesoft.svn.core.io.ISVNReplayHandler; import org.tmatesoft.svn.core.io.ISVNReporterBaton; import org.tmatesoft.svn.core.io.ISVNSession; import org.tmatesoft.svn.core.io.ISVNWorkspaceMediator; import org.tmatesoft.svn.core.io.SVNCapability; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.util.SVNLogType; /** * @version 1.3 * @author TMate Software Ltd. */ public class DAVRepository extends SVNRepository { private DAVConnection myConnection; private IHTTPConnectionFactory myConnectionFactory; private boolean myIsSpoolResponse; private static boolean ourIsKeepCredentials = Boolean.valueOf(System.getProperty("svnkit.http.keepCredentials", Boolean.TRUE.toString())).booleanValue(); public static void setKeepCredentials(boolean keepCredentials) { ourIsKeepCredentials = keepCredentials; } protected DAVRepository(IHTTPConnectionFactory connectionFactory, SVNURL location, ISVNSession options) { super(location, options); myConnectionFactory = connectionFactory; } public void testConnection() throws SVNException { try { openConnection(); myRepositoryRoot = null; myRepositoryUUID = null; DAVConnection connection = getConnection(); connection.fetchRepositoryUUID(this); connection.fetchRepositoryRoot(this); } finally { closeConnection(); } } public boolean hasRepositoryUUID() { return myRepositoryUUID != null; } public void setRepositoryUUID(String uuid) { myRepositoryUUID = uuid; } public boolean hasRepositoryRoot() { return myRepositoryRoot != null; } public void setRepositoryRoot(SVNURL root) { myRepositoryRoot = root; } public SVNURL getRepositoryRoot(boolean forceConnection) throws SVNException { if (myRepositoryRoot != null && !forceConnection) { return myRepositoryRoot; } if (myRepositoryRoot == null) { try { openConnection(); DAVConnection connection = getConnection(); connection.fetchRepositoryRoot(this); } finally { closeConnection(); } } return myRepositoryRoot; } public String getRepositoryUUID(boolean forceConnection) throws SVNException { if (myRepositoryUUID != null && !forceConnection) { return myRepositoryUUID; } if (myRepositoryUUID == null) { try { openConnection(); DAVConnection connection = getConnection(); connection.fetchRepositoryUUID(this); } finally { closeConnection(); } } return myRepositoryUUID; } public void setSpoolResponse(boolean spool) { myIsSpoolResponse = spool; DAVConnection connection = getConnection(); if (connection != null) { connection.setReportResponseSpooled(spool); } } public boolean isSpoolResponse() { return myIsSpoolResponse; } public void setAuthenticationManager(ISVNAuthenticationManager authManager) { DAVConnection connection = getConnection(); if (authManager != getAuthenticationManager() && connection != null) { connection.clearAuthenticationCache(); } super.setAuthenticationManager(authManager); } public long getLatestRevision() throws SVNException { try { openConnection(); String path = getLocation().getPath(); path = SVNEncodingUtil.uriEncode(path); DAVConnection connection = getConnection(); DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, path, -1, false, true, null); return info.revision; } finally { closeConnection(); } } public long getDatedRevision(Date date) throws SVNException { date = date == null ? new Date(System.currentTimeMillis()) : date; DAVDateRevisionHandler handler = new DAVDateRevisionHandler(); StringBuffer request = DAVDateRevisionHandler.generateDateRevisionRequest(null, date); try { openConnection(); String path = getLocation().getURIEncodedPath(); DAVConnection connection = getConnection(); path = DAVUtil.getVCCPath(connection, this, path); HTTPStatus status = connection.doReport(path, request, handler); if (status.getError() != null) { if (status.getError().getErrorCode() == SVNErrorCode.UNSUPPORTED_FEATURE) { SVNErrorMessage err2 = SVNErrorMessage.create(status.getError().getErrorCode(), "Server does not support date-based operations"); SVNErrorManager.error(err2, status.getError(), SVNLogType.NETWORK); } SVNErrorManager.error(status.getError(), SVNLogType.NETWORK); } } finally { closeConnection(); } return handler.getRevisionNumber(); } public SVNNodeKind checkPath(String path, long revision) throws SVNException { DAVBaselineInfo info = null; SVNNodeKind kind = SVNNodeKind.NONE; try { openConnection(); path = doGetFullPath(path); path = SVNEncodingUtil.uriEncode(path); DAVConnection connection = getConnection(); info = DAVUtil.getBaselineInfo(connection, this, path, revision, true, false, info); kind = info.isDirectory ? SVNNodeKind.DIR : SVNNodeKind.FILE; } catch (SVNException e) { SVNErrorMessage error = e.getErrorMessage(); while (error != null) { if (error.getErrorCode() == SVNErrorCode.FS_NOT_FOUND) { return kind; } error = error.getChildErrorMessage(); } throw e; } finally { closeConnection(); } return kind; } public SVNProperties getRevisionProperties(long revision, SVNProperties properties) throws SVNException { properties = properties == null ? new SVNProperties() : properties; try { openConnection(); String path = getLocation().getPath(); path = SVNEncodingUtil.uriEncode(path); DAVConnection connection = getConnection(); DAVProperties source = DAVUtil.getBaselineProperties(connection, this, path, revision, null); properties = DAVUtil.filterProperties(source, properties); if (revision >= 0) { String commitMessage = properties.getStringValue(SVNRevisionProperty.LOG); getOptions().saveCommitMessage(DAVRepository.this, revision, commitMessage); } } finally { closeConnection(); } return properties; } public SVNPropertyValue getRevisionPropertyValue(long revision, String propertyName) throws SVNException { SVNProperties properties = getRevisionProperties(revision, null); return properties.getSVNPropertyValue(propertyName); } public long getFile(String path, long revision, final SVNProperties properties, OutputStream contents) throws SVNException { long fileRevision = revision; try { openConnection(); path = doGetFullPath(path); path = SVNEncodingUtil.uriEncode(path); DAVConnection connection = getConnection(); if (revision != -2) { DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, path, revision, false, true, null); path = SVNPathUtil.append(info.baselineBase, info.baselinePath); fileRevision = info.revision; } if (properties != null) { DAVProperties props = DAVUtil.getResourceProperties(connection, path, null, null); DAVUtil.filterProperties(props, properties); for (Iterator names = props.getProperties().keySet().iterator(); names.hasNext();) { DAVElement property = (DAVElement) names.next(); DAVUtil.setSpecialWCProperties(properties, property, props.getPropertyValue(property)); } if (fileRevision >= 0) { properties.put(SVNProperty.REVISION, Long.toString(fileRevision)); } } if (contents != null) { connection.doGet(path, contents); } } finally { closeConnection(); } return fileRevision; } public long getDir(String path, long revision, final SVNProperties properties, final ISVNDirEntryHandler handler) throws SVNException { return getDir(path, revision, properties, SVNDirEntry.DIRENT_ALL, handler); } public long getDir(String path, long revision, SVNProperties properties, int entryFields, ISVNDirEntryHandler handler) throws SVNException { long dirRevision = revision; try { openConnection(); path = doGetFullPath(path); path = SVNEncodingUtil.uriEncode(path); final String fullPath = path; DAVConnection connection = getConnection(); if (revision != -2) { DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, path, revision, false, true, null); path = SVNPathUtil.append(info.baselineBase, info.baselinePath); dirRevision = info.revision; } DAVProperties deadProp = DAVUtil.getResourceProperties(connection, path, null, new DAVElement[] {DAVElement.DEADPROP_COUNT}); boolean supportsDeadPropCount = deadProp != null && deadProp.getPropertyValue(DAVElement.DEADPROP_COUNT) != null ; if (handler != null) { DAVElement[] whichProps = null; if ((entryFields & SVNDirEntry.DIRENT_HAS_PROPERTIES) == 0 || supportsDeadPropCount) { List individualProps = new LinkedList(); if ((entryFields & SVNDirEntry.DIRENT_KIND) != 0) { individualProps.add(DAVElement.RESOURCE_TYPE); } if ((entryFields & SVNDirEntry.DIRENT_SIZE) != 0) { individualProps.add(DAVElement.GET_CONTENT_LENGTH); } if ((entryFields & SVNDirEntry.DIRENT_HAS_PROPERTIES) != 0) { individualProps.add(DAVElement.DEADPROP_COUNT); } if ((entryFields & SVNDirEntry.DIRENT_CREATED_REVISION) != 0) { individualProps.add(DAVElement.VERSION_NAME); } if ((entryFields & SVNDirEntry.DIRENT_TIME) != 0) { individualProps.add(DAVElement.CREATION_DATE); } if ((entryFields & SVNDirEntry.DIRENT_LAST_AUTHOR) != 0) { individualProps.add(DAVElement.CREATOR_DISPLAY_NAME); } whichProps = (DAVElement[]) individualProps.toArray(new DAVElement[individualProps.size()]); } final int parentPathSegments = SVNPathUtil.getSegmentsCount(path); Map dirEntsMap = new SVNHashMap(); HTTPStatus status = DAVUtil.getProperties(connection, path, DAVUtil.DEPTH_ONE, null, whichProps, dirEntsMap); if (status.getError() != null) { SVNErrorManager.error(status.getError(), SVNLogType.NETWORK); } if (!hasRepositoryRoot()) { connection.fetchRepositoryRoot(this); } SVNURL repositryRoot = getRepositoryRoot(false); for(Iterator dirEnts = dirEntsMap.keySet().iterator(); dirEnts.hasNext();) { String url = (String) dirEnts.next(); DAVProperties child = (DAVProperties) dirEntsMap.get(url); String href = child.getURL(); if (parentPathSegments == SVNPathUtil.getSegmentsCount(href)) { continue; } String name = SVNEncodingUtil.uriDecode(SVNPathUtil.tail(href)); SVNNodeKind kind = SVNNodeKind.UNKNOWN; if ((entryFields & SVNDirEntry.DIRENT_KIND) != 0) { kind = child.isCollection() ? SVNNodeKind.DIR : SVNNodeKind.FILE; } long size = 0; if ((entryFields & SVNDirEntry.DIRENT_SIZE) != 0) { SVNPropertyValue sizeValue = child.getPropertyValue(DAVElement.GET_CONTENT_LENGTH); if (sizeValue != null) { try { size = Long.parseLong(sizeValue.getString()); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA, nfe), SVNLogType.NETWORK); } } } boolean hasProperties = false; if ((entryFields & SVNDirEntry.DIRENT_HAS_PROPERTIES) != 0) { if (supportsDeadPropCount) { SVNPropertyValue propVal = child.getPropertyValue(DAVElement.DEADPROP_COUNT); if (propVal == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.INCOMPLETE_DATA, "Server response missing the expected deadprop-count property"); SVNErrorManager.error(err, SVNLogType.NETWORK); } else { long propCount = -1; try { propCount = Long.parseLong(propVal.getString()); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA, nfe), SVNLogType.NETWORK); } hasProperties = propCount > 0; } } else { for(Iterator props = child.getProperties().keySet().iterator(); props.hasNext();) { DAVElement property = (DAVElement) props.next(); if (DAVElement.SVN_CUSTOM_PROPERTY_NAMESPACE.equals(property.getNamespace()) || DAVElement.SVN_SVN_PROPERTY_NAMESPACE.equals(property.getNamespace())) { hasProperties = true; break; } } } } long lastRevision = INVALID_REVISION; if ((entryFields & SVNDirEntry.DIRENT_CREATED_REVISION) != 0) { Object revisionStr = child.getPropertyValue(DAVElement.VERSION_NAME); - try { - lastRevision = Long.parseLong(revisionStr.toString()); - } catch (NumberFormatException nfe) { - SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA); - SVNErrorManager.error(err, SVNLogType.NETWORK); + if (revisionStr != null) { + try { + lastRevision = Long.parseLong(revisionStr.toString()); + } catch (NumberFormatException nfe) { + SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA); + SVNErrorManager.error(err, SVNLogType.NETWORK); + } } } Date date = null; if ((entryFields & SVNDirEntry.DIRENT_TIME) != 0) { SVNPropertyValue dateValue = child.getPropertyValue(DAVElement.CREATION_DATE); if (dateValue != null) { date = SVNDate.parseDate(dateValue.getString()); } } String author = null; if ((entryFields & SVNDirEntry.DIRENT_LAST_AUTHOR) != 0) { SVNPropertyValue authorValue = child.getPropertyValue(DAVElement.CREATOR_DISPLAY_NAME); author = authorValue == null ? null : authorValue.getString(); } SVNURL childURL = getLocation().setPath(fullPath, true); childURL = childURL.appendPath(name, false); SVNDirEntry dirEntry = new SVNDirEntry(childURL, repositryRoot, name, kind, size, hasProperties, lastRevision, date, author); handler.handleDirEntry(dirEntry); } } if (properties != null) { DAVProperties dirProps = DAVUtil.getResourceProperties(connection, path, null, null); DAVUtil.filterProperties(dirProps, properties); for(Iterator props = dirProps.getProperties().keySet().iterator(); props.hasNext();) { DAVElement property = (DAVElement) props.next(); DAVUtil.setSpecialWCProperties(properties, property, dirProps.getPropertyValue(property)); } } } finally { closeConnection(); } return dirRevision; } public SVNDirEntry getDir(String path, long revision, boolean includeComments, final Collection entries) throws SVNException { final SVNDirEntry[] parent = new SVNDirEntry[1]; final String[] parentVCC = new String[1]; try { openConnection(); path = doGetFullPath(path); path = SVNEncodingUtil.uriEncode(path); final String fullPath = path; DAVConnection connection = getConnection(); if (revision >= 0) { DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, path, revision, false, true, null); path = SVNPathUtil.append(info.baselineBase, info.baselinePath); } final int parentPathSegments = SVNPathUtil.getSegmentsCount(path); final List vccs = new ArrayList(); DAVElement[] dirProperties = new DAVElement[] {DAVElement.VERSION_CONTROLLED_CONFIGURATION, DAVElement.VERSION_NAME, DAVElement.GET_CONTENT_LENGTH, DAVElement.RESOURCE_TYPE, DAVElement.CREATOR_DISPLAY_NAME, DAVElement.CREATION_DATE}; Map dirEntsMap = new SVNHashMap(); HTTPStatus status = DAVUtil.getProperties(connection, path, DAVUtil.DEPTH_ONE, null, dirProperties, dirEntsMap); if (status.getError() != null) { SVNErrorManager.error(status.getError(), SVNLogType.NETWORK); } for(Iterator dirEnts = dirEntsMap.keySet().iterator(); dirEnts.hasNext();) { String url = (String) dirEnts.next(); DAVProperties child = (DAVProperties) dirEntsMap.get(url); String href = child.getURL(); String name = ""; if (parentPathSegments != SVNPathUtil.getSegmentsCount(href)) { name = SVNEncodingUtil.uriDecode(SVNPathUtil.tail(href)); } SVNNodeKind kind = SVNNodeKind.FILE; Object revisionStr = child.getPropertyValue(DAVElement.VERSION_NAME); long lastRevision = -1; try { lastRevision = Long.parseLong(revisionStr.toString()); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA, nfe), SVNLogType.NETWORK); } SVNPropertyValue sizeValue = child.getPropertyValue(DAVElement.GET_CONTENT_LENGTH); long size = 0; if (sizeValue != null) { try { size = Long.parseLong(sizeValue.getString()); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA, nfe), SVNLogType.NETWORK); } } if (child.isCollection()) { kind = SVNNodeKind.DIR; } SVNPropertyValue authorValue = child.getPropertyValue(DAVElement.CREATOR_DISPLAY_NAME); String author = authorValue == null ? null : authorValue.getString(); SVNPropertyValue dateValue = child.getPropertyValue(DAVElement.CREATION_DATE); Date date = dateValue != null ? SVNDate.parseDate(dateValue.getString()) : null; connection.fetchRepositoryRoot(this); SVNURL repositoryRoot = getRepositoryRoot(false); SVNURL childURL = getLocation().setPath(fullPath, true); if ("".equals(name)) { parent[0] = new SVNDirEntry(childURL, repositoryRoot, name, kind, size, false, lastRevision, date, author); SVNPropertyValue vcc = child.getPropertyValue(DAVElement.VERSION_CONTROLLED_CONFIGURATION); parentVCC[0] = vcc == null ? null : vcc.getString(); } else { childURL = childURL.appendPath(name, false); if (entries != null) { entries.add(new SVNDirEntry(childURL, repositoryRoot, name, kind, size, false, lastRevision, date, author)); } vccs.add(child.getPropertyValue(DAVElement.VERSION_CONTROLLED_CONFIGURATION)); } } if (includeComments) { DAVElement logProperty = DAVElement.getElement(DAVElement.SVN_SVN_PROPERTY_NAMESPACE, "log"); Iterator ents = entries != null ? entries.iterator() : null; SVNDirEntry entry = parent[0]; String vcc = parentVCC[0]; int index = 0; while(true) { String label = Long.toString(entry.getRevision()); if (entry.getDate() != null && getOptions().hasCommitMessage(this, entry.getRevision())) { String message = getOptions().getCommitMessage(this, entry.getRevision()); entry.setCommitMessage(message); } else if (entry.getDate() != null) { final SVNDirEntry currentEntry = entry; String commitMessage = null; try { commitMessage = DAVUtil.getPropertyValue(connection, vcc, label, logProperty); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() != SVNErrorCode.RA_DAV_PROPS_NOT_FOUND) { throw e; } } getOptions().saveCommitMessage(DAVRepository.this, currentEntry.getRevision(), commitMessage); currentEntry.setCommitMessage(commitMessage); } if (ents != null && ents.hasNext()) { entry = (SVNDirEntry) ents.next(); SVNPropertyValue vccValue = (SVNPropertyValue) vccs.get(index); vcc = vccValue != null ? vccValue.getString() : null; index++; } else { break; } } } } finally { closeConnection(); } return parent[0]; } public void replay(long lowRevision, long highRevision, boolean sendDeltas, ISVNEditor editor) throws SVNException { try { openConnection(); StringBuffer request = DAVReplayHandler.generateReplayRequest(highRevision, lowRevision, sendDeltas); DAVReplayHandler handler = new DAVReplayHandler(editor, true); String bcPath = SVNEncodingUtil.uriEncode(getLocation().getPath()); DAVConnection connection = getConnection(); HTTPStatus status = connection.doReport(bcPath, request, handler); if (status.getCode() == 501) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_IMPLEMENTED, "'replay' REPORT not implemented"); SVNErrorManager.error(err, status.getError(), SVNLogType.NETWORK); } else if (status.getError() != null) { SVNErrorManager.error(status.getError(), SVNLogType.NETWORK); } } finally { closeConnection(); } } public void setRevisionPropertyValue(long revision, String propertyName, SVNPropertyValue propertyValue) throws SVNException { assertValidRevision(revision); StringBuffer request = DAVProppatchHandler.generatePropertyRequest(null, propertyName, propertyValue); try { openConnection(); // get baseline url and proppatch. DAVConnection connection = getConnection(); DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, SVNEncodingUtil.uriEncode(getLocation().getPath()), revision, false, false, null); String path = SVNPathUtil.append(info.baselineBase, info.baselinePath); path = info.baseline; DAVProppatchHandler handler = new DAVProppatchHandler(); SVNErrorMessage requestError = null; try { connection.doProppatch(null, path, request, handler, null); } catch (SVNException e) { requestError = e.getErrorMessage(); } if (requestError != null || handler.getError() != null){ if (requestError != null){ requestError.setChildErrorMessage(handler.getError()); } else { requestError = handler.getError(); } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "DAV request failed; it's possible that the repository's " + "pre-revprop-change hook either failed or is non-existent"); SVNErrorManager.error(err, requestError, SVNLogType.NETWORK); } } finally { closeConnection(); } } public ISVNEditor getCommitEditor(String logMessage, Map locks, boolean keepLocks, ISVNWorkspaceMediator mediator) throws SVNException { return getCommitEditor(logMessage, locks, keepLocks, null, mediator); } public SVNLock getLock(String path) throws SVNException { try { openConnection(); path = doGetFullPath(path); path = SVNEncodingUtil.uriEncode(path); DAVConnection connection = getConnection(); return connection.doGetLock(path, this); } finally { closeConnection(); } } public SVNLock[] getLocks(String path) throws SVNException { try { openConnection(); path = doGetFullPath(path); path = SVNEncodingUtil.uriEncode(path); DAVConnection connection = getConnection(); return connection.doGetLocks(path); } finally { closeConnection(); } } public void lock(Map pathsToRevisions, String comment, boolean force, ISVNLockHandler handler) throws SVNException { try { openConnection(); DAVConnection connection = getConnection(); for(Iterator paths = pathsToRevisions.keySet().iterator(); paths.hasNext();) { String path = (String) paths.next(); Long revision = (Long) pathsToRevisions.get(path); String repositoryPath = doGetRepositoryPath(path); path = doGetFullPath(path); path = SVNEncodingUtil.uriEncode(path); SVNLock lock = null; SVNErrorMessage error = null; long revisionNumber = revision != null ? revision.longValue() : -1; try { lock = connection.doLock(path, this, comment, force, revisionNumber); } catch (SVNException e) { error = null; if (e.getErrorMessage() != null) { SVNErrorCode code = e.getErrorMessage().getErrorCode(); if (code == SVNErrorCode.FS_PATH_ALREADY_LOCKED || code == SVNErrorCode.FS_OUT_OF_DATE) { error = e.getErrorMessage(); } } if (error == null) { throw e; } } if (handler != null) { handler.handleLock(repositoryPath, lock, error); } } } finally { closeConnection(); } } public void unlock(Map pathToTokens, boolean force, ISVNLockHandler handler) throws SVNException { try { openConnection(); DAVConnection connection = getConnection(); for (Iterator paths = pathToTokens.keySet().iterator(); paths.hasNext();) { String path = (String) paths.next(); String shortPath = path; String id = (String) pathToTokens.get(path); String repositoryPath = doGetRepositoryPath(path); path = doGetFullPath(path); path = SVNEncodingUtil.uriEncode(path); SVNErrorMessage error = null; try { connection.doUnlock(path, this, id, force); error = null; } catch (SVNException e) { if (e.getErrorMessage() != null && e.getErrorMessage().getErrorCode() == SVNErrorCode.RA_NOT_LOCKED) { error = e.getErrorMessage(); error = SVNErrorMessage.create(error.getErrorCode(), error.getMessageTemplate(), shortPath); } else { throw e; } } if (handler != null) { handler.handleUnlock(repositoryPath, new SVNLock(path, id, null, null, null, null), error); } } } finally { closeConnection(); } } public SVNDirEntry info(String path, long revision) throws SVNException { try { openConnection(); path = doGetFullPath(path); path = SVNEncodingUtil.uriEncode(path); final String fullPath = path; DAVConnection connection = getConnection(); if (revision >= 0) { try { DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, path, revision, false, true, null); path = SVNPathUtil.append(info.baselineBase, info.baselinePath); } catch (SVNException e) { if (e.getErrorMessage() != null && e.getErrorMessage().getErrorCode() == SVNErrorCode.FS_NOT_FOUND) { return null; } throw e; } } DAVElement[] elements = null; Map propsMap = new SVNHashMap(); HTTPStatus status = DAVUtil.getProperties(connection, path, 0, null, elements, propsMap); if (status.getError() != null) { if (status.getError().getErrorCode() == SVNErrorCode.FS_NOT_FOUND) { return null; } SVNErrorManager.error(status.getError(), SVNLogType.NETWORK); } if (!propsMap.isEmpty()) { DAVProperties props = (DAVProperties) propsMap.values().iterator().next(); return createDirEntry(fullPath, props); } } finally { closeConnection(); } return null; } public void closeSession() { lock(true); try { if (myConnection != null) { myConnection.close(); myConnection = null; } } finally { unlock(); } } public String doGetFullPath(String relativeOrRepositoryPath) throws SVNException { if (relativeOrRepositoryPath == null) { return doGetFullPath("/"); } String fullPath; if (relativeOrRepositoryPath.length() > 0 && relativeOrRepositoryPath.charAt(0) == '/') { DAVConnection connection = getConnection(); connection.fetchRepositoryRoot(this); fullPath = SVNPathUtil.append(myRepositoryRoot.getPath(), relativeOrRepositoryPath); } else { fullPath = SVNPathUtil.append(getLocation().getPath(), relativeOrRepositoryPath); } if (!fullPath.startsWith("/")) { fullPath = "/" + fullPath; } return fullPath; } public void diff(SVNURL url, long targetRevision, long revision, String target, boolean ignoreAncestry, SVNDepth depth, boolean getContents, ISVNReporterBaton reporter, ISVNEditor editor) throws SVNException { if (url == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_ILLEGAL_URL, "URL could not be NULL"); SVNErrorManager.error(err, SVNLogType.NETWORK); } if (revision < 0) { revision = targetRevision; } boolean sendAll = myConnectionFactory.useSendAllForDiff(this); runReport(getLocation(), targetRevision, target, url.toString(), depth, ignoreAncestry, false, getContents, false, sendAll, false, true, reporter, editor); } public void status(long revision, String target, SVNDepth depth, ISVNReporterBaton reporter, ISVNEditor editor) throws SVNException { runReport(getLocation(), revision, target, null, depth, false, false, false, false, true, false, false, reporter, editor); } public void update(SVNURL url, long revision, String target, SVNDepth depth, ISVNReporterBaton reporter, ISVNEditor editor) throws SVNException { if (url == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_ILLEGAL_URL, "URL could not be NULL"); SVNErrorManager.error(err, SVNLogType.NETWORK); } runReport(getLocation(), revision, target, url.toString(), depth, true, false, true, false, true, true, false, reporter, editor); } public void update(long revision, String target, SVNDepth depth, boolean sendCopyFromArgs, ISVNReporterBaton reporter, ISVNEditor editor) throws SVNException { runReport(getLocation(), revision, target, null, depth, false, false, true, sendCopyFromArgs, true, false, false, reporter, editor); } public boolean hasCapability(SVNCapability capability) throws SVNException { if (capability == SVNCapability.COMMIT_REVPROPS) { return true; } try { openConnection(); DAVConnection connection = getConnection(); String result = connection.getCapabilityResponse(capability); if (DAVConnection.DAV_CAPABILITY_SERVER_YES.equals(result)) { if (capability == SVNCapability.MERGE_INFO) { SVNException error = null; try { doGetMergeInfo(new String[]{""}, -1, SVNMergeInfoInheritance.EXPLICIT, false); } catch (SVNException svne) { error = svne; } if (error != null){ if (error.getErrorMessage().getErrorCode() == SVNErrorCode.UNSUPPORTED_FEATURE) { result = DAVConnection.DAV_CAPABILITY_NO; } else if (error.getErrorMessage().getErrorCode() == SVNErrorCode.FS_NOT_FOUND) { result = DAVConnection.DAV_CAPABILITY_YES; } else { throw error; } } else { result = DAVConnection.DAV_CAPABILITY_YES; } connection.setCapability(SVNCapability.MERGE_INFO, result); } else { SVNErrorMessage error = SVNErrorMessage.create(SVNErrorCode.UNKNOWN_CAPABILITY, "Don''t know how to handle ''{0}'' for capability ''{1}''", new Object[]{DAVConnection.DAV_CAPABILITY_SERVER_YES, SVNCapability.MERGE_INFO}); SVNErrorManager.error(error, SVNLogType.NETWORK); } } if (DAVConnection.DAV_CAPABILITY_YES.equals(result)) { return true; } else if (DAVConnection.DAV_CAPABILITY_NO.equals(result)) { return false; } else if (result == null) { SVNErrorMessage error = SVNErrorMessage.create(SVNErrorCode.UNKNOWN_CAPABILITY, "Don''t know anything about capability ''{0}''", new Object[]{capability}); SVNErrorManager.error(error, SVNLogType.NETWORK); } else { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_OPTIONS_REQ_FAILED, "Attempt to fetch capability ''{0}'' resulted in ''{1}''", new Object[]{capability, result}), SVNLogType.NETWORK); } } finally { closeConnection(); } return false; } protected int getFileRevisionsImpl(String path, long startRevision, long endRevision, boolean includeMergedRevisions, ISVNFileRevisionHandler handler) throws SVNException { String bcPath = getLocation().getPath(); bcPath = SVNEncodingUtil.uriEncode(bcPath); try { openConnection(); DAVConnection connection = getConnection(); path = "".equals(path) ? "" : doGetRepositoryPath(path); DAVFileRevisionHandler davHandler = new DAVFileRevisionHandler(handler); StringBuffer request = DAVFileRevisionHandler.generateFileRevisionsRequest(null, startRevision, endRevision, path, includeMergedRevisions); long revision = -1; if (isValidRevision(startRevision) && isValidRevision(endRevision)) { revision = Math.max(startRevision, endRevision); } DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, bcPath, revision, false, false, null); bcPath = SVNPathUtil.append(info.baselineBase, info.baselinePath); HTTPStatus status = connection.doReport(bcPath, request, davHandler); if (status.getCode() == 501) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_IMPLEMENTED, "'get-file-revs' REPORT not implemented"); SVNErrorManager.error(err, status.getError(), SVNLogType.NETWORK); } else if (status.getError() != null) { SVNErrorManager.error(status.getError(), SVNLogType.NETWORK); } if (davHandler.getEntriesCount() <= 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "The file-revs report didn't contain any revisions"); SVNErrorManager.error(err, SVNLogType.NETWORK); } return davHandler.getEntriesCount(); } finally { closeConnection(); } } //TODO: FIXME protected long logImpl(String[] targetPaths, long startRevision, long endRevision, boolean changedPath, boolean strictNode, long limit, boolean includeMergedRevisions, String[] revPropNames, final ISVNLogEntryHandler handler) throws SVNException { if (targetPaths == null || targetPaths.length == 0) { targetPaths = new String[]{""}; } DAVLogHandler davHandler = null; ISVNLogEntryHandler cachingHandler = new ISVNLogEntryHandler() { public void handleLogEntry(SVNLogEntry logEntry) throws SVNException { if (logEntry.getDate() != null) { getOptions().saveCommitMessage(DAVRepository.this, logEntry.getRevision(), logEntry.getMessage()); } if (handler != null) { handler.handleLogEntry(logEntry); } } }; long latestRev = -1; if (isInvalidRevision(startRevision)) { startRevision = latestRev = getLatestRevision(); } if (isInvalidRevision(endRevision)) { endRevision = latestRev != -1 ? latestRev : getLatestRevision(); } try { openConnection(); DAVConnection connection = getConnection(); String[] fullPaths = new String[targetPaths.length]; for (int i = 0; i < targetPaths.length; i++) { fullPaths[i] = doGetFullPath(targetPaths[i]); } Collection relativePaths = new SVNHashSet(); String path = SVNPathUtil.condencePaths(fullPaths, relativePaths, false); if (relativePaths.isEmpty()) { relativePaths.add(""); } fullPaths = (String[]) relativePaths.toArray(new String[relativePaths.size()]); StringBuffer request = DAVLogHandler.generateLogRequest(null, startRevision, endRevision, changedPath, strictNode, includeMergedRevisions, revPropNames, limit, fullPaths); davHandler = new DAVLogHandler(cachingHandler, limit, revPropNames); if (davHandler.isWantCustomRevprops()) { String capability = connection.getCapabilityResponse(SVNCapability.LOG_REVPROPS); if (!DAVConnection.DAV_CAPABILITY_SERVER_YES.equals(capability) && !DAVConnection.DAV_CAPABILITY_YES.equals(capability)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_IMPLEMENTED, "Server does not support custom revprops via log"); SVNErrorManager.error(err, SVNLogType.NETWORK); } } long revision = Math.max(startRevision, endRevision); path = SVNEncodingUtil.uriEncode(path); DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, path, revision, false, false, null); path = SVNPathUtil.append(info.baselineBase, info.baselinePath); try { HTTPStatus status = connection.doReport(path, request, davHandler); if (status.getError() != null) { SVNErrorManager.error(status.getError(), SVNLogType.NETWORK); } } catch (SVNException e) { if (e.getErrorMessage() != null && e.getErrorMessage().getErrorCode() == SVNErrorCode.UNKNOWN && davHandler.isCompatibleMode()) { cachingHandler.handleLogEntry(SVNLogEntry.EMPTY_ENTRY); } else { throw e; } } } finally { closeConnection(); } return davHandler.getEntriesCount(); } protected void openConnection() throws SVNException { lock(); fireConnectionOpened(); if (myConnection == null) { myConnection = createDAVConnection(myConnectionFactory, this); myConnection.setReportResponseSpooled(isSpoolResponse()); myConnection.open(this); } } protected DAVConnection createDAVConnection(IHTTPConnectionFactory connectionFactory, DAVRepository repo) { return new DAVConnection(connectionFactory, repo); } protected void closeConnection() { DAVConnection connection = getConnection(); if (connection != null && !ourIsKeepCredentials) { connection.clearAuthenticationCache(); } if (!getOptions().keepConnection(this)) { closeSession(); } unlock(); fireConnectionClosed(); } protected int getLocationsImpl(String path, long pegRevision, long[] revisions, ISVNLocationEntryHandler handler) throws SVNException { try { openConnection(); DAVConnection connection = getConnection(); if (path.startsWith("/")) { // (root + path), relative to location connection.fetchRepositoryRoot(this); path = SVNPathUtil.append(myRepositoryRoot.getPath(), path); if (path.equals(getLocation().getPath())) { path = ""; } else { path = path.substring(getLocation().getPath().length() + 1); } } StringBuffer request = DAVLocationsHandler.generateLocationsRequest(null, path, pegRevision, revisions); DAVLocationsHandler davHandler = new DAVLocationsHandler(handler); String root = getLocation().getPath(); root = SVNEncodingUtil.uriEncode(root); DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, root, pegRevision, false, false, null); path = SVNPathUtil.append(info.baselineBase, info.baselinePath); HTTPStatus status = connection.doReport(path, request, davHandler); if (status.getCode() == 501) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_IMPLEMENTED, "'get-locations' REPORT not implemented"); SVNErrorManager.error(err, status.getError(), SVNLogType.NETWORK); } else if (status.getError() != null) { SVNErrorManager.error(status.getError(), SVNLogType.NETWORK); } return davHandler.getEntriesCount(); } finally { closeConnection(); } } protected long getLocationSegmentsImpl(String path, long pegRevision, long startRevision, long endRevision, ISVNLocationSegmentHandler handler) throws SVNException { try { openConnection(); DAVConnection connection = getConnection(); boolean absolutePath = path.startsWith("/"); if (absolutePath) { // (root + path), relative to location connection.fetchRepositoryRoot(this); path = SVNPathUtil.append(myRepositoryRoot.getPath(), path); if (path.equals(getLocation().getPath())) { path = ""; } else { path = path.substring(myRepositoryRoot.getPath().length() + 1); } } StringBuffer request = DAVLocationSegmentsHandler.generateGetLocationSegmentsRequest(null, path, pegRevision, startRevision, endRevision); DAVLocationSegmentsHandler davHandler = new DAVLocationSegmentsHandler(handler); String root = absolutePath ? myRepositoryRoot.getPath() : getLocation().getPath(); root = SVNEncodingUtil.uriEncode(root); DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, root, pegRevision, false, false, null); path = SVNPathUtil.append(info.baselineBase, info.baselinePath); HTTPStatus status = connection.doReport(path, request, davHandler); if (status.getCode() == 501) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_IMPLEMENTED, "'get-location-segments' REPORT not implemented"); SVNErrorManager.error(err, status.getError(), SVNLogType.NETWORK); } else if (status.getError() != null) { SVNErrorManager.error(status.getError(), SVNLogType.NETWORK); } return davHandler.getTotalRevisions(); } finally { closeConnection(); } } protected String doGetRepositoryPath(String relativePath) throws SVNException { if (relativePath == null) { return "/"; } if (relativePath.length() > 0 && relativePath.charAt(0) == '/') { return relativePath; } String fullPath = SVNPathUtil.append(getLocation().getPath(), relativePath); DAVConnection connection = getConnection(); connection.fetchRepositoryRoot(this); String repositoryPath = fullPath.substring(myRepositoryRoot.getPath().length()); if ("".equals(repositoryPath)) { return "/"; } return repositoryPath; } protected Map getMergeInfoImpl(String[] paths, long revision, SVNMergeInfoInheritance inherit, boolean includeDescendants) throws SVNException { try { openConnection(); return doGetMergeInfo(paths, revision, inherit, includeDescendants); } finally { closeConnection(); } } protected void replayRangeImpl(long startRevision, long endRevision, long lowRevision, boolean sendDeltas, ISVNReplayHandler handler) throws SVNException { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_IMPLEMENTED); SVNErrorManager.error(err, SVNLogType.NETWORK); } protected ISVNEditor getCommitEditorInternal(Map locks, boolean keepLocks, SVNProperties revProps, ISVNWorkspaceMediator mediator) throws SVNException { try { openConnection(); DAVConnection connection = getConnection(); Map translatedLocks = null; if (locks != null && !locks.isEmpty()) { translatedLocks = new SVNHashMap(); connection.fetchRepositoryRoot(this); String root = myRepositoryRoot.getPath(); root = SVNEncodingUtil.uriEncode(root); for (Iterator paths = locks.keySet().iterator(); paths.hasNext();) { String path = (String) paths.next(); String lock = (String) locks.get(path); if (path.startsWith("/")) { path = SVNPathUtil.append(root, SVNEncodingUtil.uriEncode(path)); } else { path = doGetFullPath(path); path = SVNEncodingUtil.uriEncode(path); } translatedLocks.put(path, lock); } } connection.setLocks(translatedLocks, keepLocks); return new DAVCommitEditor(this, connection, revProps, mediator, new Runnable() { public void run() { closeConnection(); } }); } catch (Throwable th) { closeConnection(); if (th instanceof SVNException) { throw (SVNException) th; } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNKNOWN, "can not get commit editor: ''{0}''", th.getLocalizedMessage()); SVNErrorManager.error(err, th, SVNLogType.NETWORK); return null; } } protected long getDeletedRevisionImpl(String path, long pegRevision, long endRevision) throws SVNException { try { openConnection(); DAVConnection connection = getConnection(); String thisSessionPath = doGetFullPath(""); thisSessionPath = SVNEncodingUtil.uriEncode(thisSessionPath); DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, thisSessionPath, pegRevision, false, false, null); String finalBCPath = SVNPathUtil.append(info.baselineBase, info.baselinePath); StringBuffer requestBody = DAVDeletedRevisionHandler.generateGetDeletedRevisionRequest(null, path, pegRevision, endRevision); DAVDeletedRevisionHandler handler = new DAVDeletedRevisionHandler(); HTTPStatus status = connection.doReport(finalBCPath, requestBody, handler); if (status.getCode() == 501) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_IMPLEMENTED, "'get-deleted-rev' REPORT not implemented"); SVNErrorManager.error(err, status.getError(), SVNLogType.NETWORK); } return handler.getRevision(); } finally { closeConnection(); } } protected DAVConnection getConnection() { return myConnection; } protected IHTTPConnectionFactory getConnectionFactory() { return myConnectionFactory; } private Map doGetMergeInfo(String[] paths, long revision, SVNMergeInfoInheritance inherit, boolean includeDescendants) throws SVNException { String path = doGetFullPath(""); path = SVNEncodingUtil.uriEncode(path); DAVConnection connection = getConnection(); DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, path, revision, false, true, null); path = SVNPathUtil.append(info.baselineBase, info.baselinePath); if (paths == null || paths.length == 0) { paths = new String[]{""}; } String[] repositoryPaths = new String[paths.length]; for (int i = 0; i < paths.length; i++) { repositoryPaths[i] = getRepositoryPath(paths[i]); } StringBuffer request = DAVMergeInfoHandler.generateMergeInfoRequest(null, revision, repositoryPaths, inherit, includeDescendants); DAVMergeInfoHandler handler = new DAVMergeInfoHandler(); HTTPStatus status = connection.doReport(path, request, handler); if (status.getCode() == 501) { SVNErrorMessage err = status.getError() != null ? status.getError() : SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Server does not support mergeinfo"); SVNErrorManager.error(err, SVNLogType.NETWORK); } if (status.getError() != null) { SVNErrorManager.error(status.getError(), SVNLogType.NETWORK); } Map mergeInfo = handler.getMergeInfo(); if (mergeInfo == null) { return null; } Map mergeInfoWithPath = new HashMap(); for (Iterator items = mergeInfo.entrySet().iterator(); items.hasNext();) { Map.Entry item = (Map.Entry) items.next(); SVNMergeInfo value = (SVNMergeInfo) item.getValue(); if (value != null) { String repositoryPath = (String) item.getKey(); if (repositoryPath.startsWith("/")) { repositoryPath = repositoryPath.substring("/".length()); } repositoryPath = doGetRepositoryPath(repositoryPath); mergeInfoWithPath.put(repositoryPath, new SVNMergeInfo(repositoryPath, value.getMergeSourcesToMergeLists())); } } return mergeInfoWithPath; } private void runReport(SVNURL url, long targetRevision, String target, String dstPath, SVNDepth depth, boolean ignoreAncestry, boolean resourceWalk, boolean fetchContents, boolean sendCopyFromArgs, boolean sendAll, boolean closeEditorOnException, boolean spool, ISVNReporterBaton reporter, ISVNEditor editor) throws SVNException { boolean serverSupportsDepth = hasCapability(SVNCapability.DEPTH); if (depth != SVNDepth.FILES && depth != SVNDepth.INFINITY && !serverSupportsDepth) { editor = SVNDepthFilterEditor.getDepthFilterEditor(depth, editor, target != null); } DAVEditorHandler handler = null; try { openConnection(); DAVConnection connection = getConnection(); Map lockTokens = new SVNHashMap(); StringBuffer request = DAVEditorHandler.generateEditorRequest(connection, null, url.toString(), targetRevision, target, dstPath, depth, lockTokens, ignoreAncestry, resourceWalk, fetchContents, sendCopyFromArgs, sendAll, reporter); handler = new DAVEditorHandler(myConnectionFactory, this, editor, lockTokens, fetchContents, target != null && !"".equals(target)); String bcPath = SVNEncodingUtil.uriEncode(getLocation().getPath()); try { bcPath = DAVUtil.getVCCPath(connection, this, bcPath); } catch (SVNException e) { if (closeEditorOnException) { editor.closeEdit(); } throw e; } HTTPStatus status = connection.doReport(bcPath, request, handler, spool); if (status.getError() != null) { SVNErrorManager.error(status.getError(), SVNLogType.NETWORK); } } finally { if (handler != null) { handler.closeConnection(); } closeConnection(); } } private SVNDirEntry createDirEntry(String fullPath, DAVProperties child) throws SVNException { String href = child.getURL(); href = SVNEncodingUtil.uriDecode(href); String name = SVNPathUtil.tail(href); // build direntry SVNNodeKind kind = SVNNodeKind.FILE; Object revisionStr = child.getPropertyValue(DAVElement.VERSION_NAME); long lastRevision = -1; try { lastRevision = Long.parseLong(revisionStr.toString()); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA, nfe), SVNLogType.NETWORK); } SVNPropertyValue sizeValue = child.getPropertyValue(DAVElement.GET_CONTENT_LENGTH); long size = 0; if (sizeValue != null) { try { size = Long.parseLong(sizeValue.getString()); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA, nfe), SVNLogType.NETWORK); } } if (child.isCollection()) { kind = SVNNodeKind.DIR; } SVNPropertyValue authorValue = child.getPropertyValue(DAVElement.CREATOR_DISPLAY_NAME); String author = authorValue == null ? null : authorValue.getString(); SVNPropertyValue dateValue = child.getPropertyValue(DAVElement.CREATION_DATE); Date date = dateValue != null ? SVNDate.parseDate(dateValue.getString()) : null; boolean hasProperties = false; for (Iterator props = child.getProperties().keySet().iterator(); props.hasNext();) { DAVElement property = (DAVElement) props.next(); if (DAVElement.SVN_CUSTOM_PROPERTY_NAMESPACE.equals(property.getNamespace()) || DAVElement.SVN_SVN_PROPERTY_NAMESPACE.equals(property.getNamespace())) { hasProperties = true; break; } } DAVConnection connection = getConnection(); connection.fetchRepositoryRoot(this); SVNURL repositoryRoot = getRepositoryRoot(false); SVNURL url = getLocation().setPath(fullPath, true); return new SVNDirEntry(url, repositoryRoot, name, kind, size, hasProperties, lastRevision, date, author); } }
true
true
public long getDir(String path, long revision, SVNProperties properties, int entryFields, ISVNDirEntryHandler handler) throws SVNException { long dirRevision = revision; try { openConnection(); path = doGetFullPath(path); path = SVNEncodingUtil.uriEncode(path); final String fullPath = path; DAVConnection connection = getConnection(); if (revision != -2) { DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, path, revision, false, true, null); path = SVNPathUtil.append(info.baselineBase, info.baselinePath); dirRevision = info.revision; } DAVProperties deadProp = DAVUtil.getResourceProperties(connection, path, null, new DAVElement[] {DAVElement.DEADPROP_COUNT}); boolean supportsDeadPropCount = deadProp != null && deadProp.getPropertyValue(DAVElement.DEADPROP_COUNT) != null ; if (handler != null) { DAVElement[] whichProps = null; if ((entryFields & SVNDirEntry.DIRENT_HAS_PROPERTIES) == 0 || supportsDeadPropCount) { List individualProps = new LinkedList(); if ((entryFields & SVNDirEntry.DIRENT_KIND) != 0) { individualProps.add(DAVElement.RESOURCE_TYPE); } if ((entryFields & SVNDirEntry.DIRENT_SIZE) != 0) { individualProps.add(DAVElement.GET_CONTENT_LENGTH); } if ((entryFields & SVNDirEntry.DIRENT_HAS_PROPERTIES) != 0) { individualProps.add(DAVElement.DEADPROP_COUNT); } if ((entryFields & SVNDirEntry.DIRENT_CREATED_REVISION) != 0) { individualProps.add(DAVElement.VERSION_NAME); } if ((entryFields & SVNDirEntry.DIRENT_TIME) != 0) { individualProps.add(DAVElement.CREATION_DATE); } if ((entryFields & SVNDirEntry.DIRENT_LAST_AUTHOR) != 0) { individualProps.add(DAVElement.CREATOR_DISPLAY_NAME); } whichProps = (DAVElement[]) individualProps.toArray(new DAVElement[individualProps.size()]); } final int parentPathSegments = SVNPathUtil.getSegmentsCount(path); Map dirEntsMap = new SVNHashMap(); HTTPStatus status = DAVUtil.getProperties(connection, path, DAVUtil.DEPTH_ONE, null, whichProps, dirEntsMap); if (status.getError() != null) { SVNErrorManager.error(status.getError(), SVNLogType.NETWORK); } if (!hasRepositoryRoot()) { connection.fetchRepositoryRoot(this); } SVNURL repositryRoot = getRepositoryRoot(false); for(Iterator dirEnts = dirEntsMap.keySet().iterator(); dirEnts.hasNext();) { String url = (String) dirEnts.next(); DAVProperties child = (DAVProperties) dirEntsMap.get(url); String href = child.getURL(); if (parentPathSegments == SVNPathUtil.getSegmentsCount(href)) { continue; } String name = SVNEncodingUtil.uriDecode(SVNPathUtil.tail(href)); SVNNodeKind kind = SVNNodeKind.UNKNOWN; if ((entryFields & SVNDirEntry.DIRENT_KIND) != 0) { kind = child.isCollection() ? SVNNodeKind.DIR : SVNNodeKind.FILE; } long size = 0; if ((entryFields & SVNDirEntry.DIRENT_SIZE) != 0) { SVNPropertyValue sizeValue = child.getPropertyValue(DAVElement.GET_CONTENT_LENGTH); if (sizeValue != null) { try { size = Long.parseLong(sizeValue.getString()); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA, nfe), SVNLogType.NETWORK); } } } boolean hasProperties = false; if ((entryFields & SVNDirEntry.DIRENT_HAS_PROPERTIES) != 0) { if (supportsDeadPropCount) { SVNPropertyValue propVal = child.getPropertyValue(DAVElement.DEADPROP_COUNT); if (propVal == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.INCOMPLETE_DATA, "Server response missing the expected deadprop-count property"); SVNErrorManager.error(err, SVNLogType.NETWORK); } else { long propCount = -1; try { propCount = Long.parseLong(propVal.getString()); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA, nfe), SVNLogType.NETWORK); } hasProperties = propCount > 0; } } else { for(Iterator props = child.getProperties().keySet().iterator(); props.hasNext();) { DAVElement property = (DAVElement) props.next(); if (DAVElement.SVN_CUSTOM_PROPERTY_NAMESPACE.equals(property.getNamespace()) || DAVElement.SVN_SVN_PROPERTY_NAMESPACE.equals(property.getNamespace())) { hasProperties = true; break; } } } } long lastRevision = INVALID_REVISION; if ((entryFields & SVNDirEntry.DIRENT_CREATED_REVISION) != 0) { Object revisionStr = child.getPropertyValue(DAVElement.VERSION_NAME); try { lastRevision = Long.parseLong(revisionStr.toString()); } catch (NumberFormatException nfe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA); SVNErrorManager.error(err, SVNLogType.NETWORK); } } Date date = null; if ((entryFields & SVNDirEntry.DIRENT_TIME) != 0) { SVNPropertyValue dateValue = child.getPropertyValue(DAVElement.CREATION_DATE); if (dateValue != null) { date = SVNDate.parseDate(dateValue.getString()); } } String author = null; if ((entryFields & SVNDirEntry.DIRENT_LAST_AUTHOR) != 0) { SVNPropertyValue authorValue = child.getPropertyValue(DAVElement.CREATOR_DISPLAY_NAME); author = authorValue == null ? null : authorValue.getString(); } SVNURL childURL = getLocation().setPath(fullPath, true); childURL = childURL.appendPath(name, false); SVNDirEntry dirEntry = new SVNDirEntry(childURL, repositryRoot, name, kind, size, hasProperties, lastRevision, date, author); handler.handleDirEntry(dirEntry); } } if (properties != null) { DAVProperties dirProps = DAVUtil.getResourceProperties(connection, path, null, null); DAVUtil.filterProperties(dirProps, properties); for(Iterator props = dirProps.getProperties().keySet().iterator(); props.hasNext();) { DAVElement property = (DAVElement) props.next(); DAVUtil.setSpecialWCProperties(properties, property, dirProps.getPropertyValue(property)); } } } finally { closeConnection(); } return dirRevision; }
public long getDir(String path, long revision, SVNProperties properties, int entryFields, ISVNDirEntryHandler handler) throws SVNException { long dirRevision = revision; try { openConnection(); path = doGetFullPath(path); path = SVNEncodingUtil.uriEncode(path); final String fullPath = path; DAVConnection connection = getConnection(); if (revision != -2) { DAVBaselineInfo info = DAVUtil.getBaselineInfo(connection, this, path, revision, false, true, null); path = SVNPathUtil.append(info.baselineBase, info.baselinePath); dirRevision = info.revision; } DAVProperties deadProp = DAVUtil.getResourceProperties(connection, path, null, new DAVElement[] {DAVElement.DEADPROP_COUNT}); boolean supportsDeadPropCount = deadProp != null && deadProp.getPropertyValue(DAVElement.DEADPROP_COUNT) != null ; if (handler != null) { DAVElement[] whichProps = null; if ((entryFields & SVNDirEntry.DIRENT_HAS_PROPERTIES) == 0 || supportsDeadPropCount) { List individualProps = new LinkedList(); if ((entryFields & SVNDirEntry.DIRENT_KIND) != 0) { individualProps.add(DAVElement.RESOURCE_TYPE); } if ((entryFields & SVNDirEntry.DIRENT_SIZE) != 0) { individualProps.add(DAVElement.GET_CONTENT_LENGTH); } if ((entryFields & SVNDirEntry.DIRENT_HAS_PROPERTIES) != 0) { individualProps.add(DAVElement.DEADPROP_COUNT); } if ((entryFields & SVNDirEntry.DIRENT_CREATED_REVISION) != 0) { individualProps.add(DAVElement.VERSION_NAME); } if ((entryFields & SVNDirEntry.DIRENT_TIME) != 0) { individualProps.add(DAVElement.CREATION_DATE); } if ((entryFields & SVNDirEntry.DIRENT_LAST_AUTHOR) != 0) { individualProps.add(DAVElement.CREATOR_DISPLAY_NAME); } whichProps = (DAVElement[]) individualProps.toArray(new DAVElement[individualProps.size()]); } final int parentPathSegments = SVNPathUtil.getSegmentsCount(path); Map dirEntsMap = new SVNHashMap(); HTTPStatus status = DAVUtil.getProperties(connection, path, DAVUtil.DEPTH_ONE, null, whichProps, dirEntsMap); if (status.getError() != null) { SVNErrorManager.error(status.getError(), SVNLogType.NETWORK); } if (!hasRepositoryRoot()) { connection.fetchRepositoryRoot(this); } SVNURL repositryRoot = getRepositoryRoot(false); for(Iterator dirEnts = dirEntsMap.keySet().iterator(); dirEnts.hasNext();) { String url = (String) dirEnts.next(); DAVProperties child = (DAVProperties) dirEntsMap.get(url); String href = child.getURL(); if (parentPathSegments == SVNPathUtil.getSegmentsCount(href)) { continue; } String name = SVNEncodingUtil.uriDecode(SVNPathUtil.tail(href)); SVNNodeKind kind = SVNNodeKind.UNKNOWN; if ((entryFields & SVNDirEntry.DIRENT_KIND) != 0) { kind = child.isCollection() ? SVNNodeKind.DIR : SVNNodeKind.FILE; } long size = 0; if ((entryFields & SVNDirEntry.DIRENT_SIZE) != 0) { SVNPropertyValue sizeValue = child.getPropertyValue(DAVElement.GET_CONTENT_LENGTH); if (sizeValue != null) { try { size = Long.parseLong(sizeValue.getString()); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA, nfe), SVNLogType.NETWORK); } } } boolean hasProperties = false; if ((entryFields & SVNDirEntry.DIRENT_HAS_PROPERTIES) != 0) { if (supportsDeadPropCount) { SVNPropertyValue propVal = child.getPropertyValue(DAVElement.DEADPROP_COUNT); if (propVal == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.INCOMPLETE_DATA, "Server response missing the expected deadprop-count property"); SVNErrorManager.error(err, SVNLogType.NETWORK); } else { long propCount = -1; try { propCount = Long.parseLong(propVal.getString()); } catch (NumberFormatException nfe) { SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA, nfe), SVNLogType.NETWORK); } hasProperties = propCount > 0; } } else { for(Iterator props = child.getProperties().keySet().iterator(); props.hasNext();) { DAVElement property = (DAVElement) props.next(); if (DAVElement.SVN_CUSTOM_PROPERTY_NAMESPACE.equals(property.getNamespace()) || DAVElement.SVN_SVN_PROPERTY_NAMESPACE.equals(property.getNamespace())) { hasProperties = true; break; } } } } long lastRevision = INVALID_REVISION; if ((entryFields & SVNDirEntry.DIRENT_CREATED_REVISION) != 0) { Object revisionStr = child.getPropertyValue(DAVElement.VERSION_NAME); if (revisionStr != null) { try { lastRevision = Long.parseLong(revisionStr.toString()); } catch (NumberFormatException nfe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_MALFORMED_DATA); SVNErrorManager.error(err, SVNLogType.NETWORK); } } } Date date = null; if ((entryFields & SVNDirEntry.DIRENT_TIME) != 0) { SVNPropertyValue dateValue = child.getPropertyValue(DAVElement.CREATION_DATE); if (dateValue != null) { date = SVNDate.parseDate(dateValue.getString()); } } String author = null; if ((entryFields & SVNDirEntry.DIRENT_LAST_AUTHOR) != 0) { SVNPropertyValue authorValue = child.getPropertyValue(DAVElement.CREATOR_DISPLAY_NAME); author = authorValue == null ? null : authorValue.getString(); } SVNURL childURL = getLocation().setPath(fullPath, true); childURL = childURL.appendPath(name, false); SVNDirEntry dirEntry = new SVNDirEntry(childURL, repositryRoot, name, kind, size, hasProperties, lastRevision, date, author); handler.handleDirEntry(dirEntry); } } if (properties != null) { DAVProperties dirProps = DAVUtil.getResourceProperties(connection, path, null, null); DAVUtil.filterProperties(dirProps, properties); for(Iterator props = dirProps.getProperties().keySet().iterator(); props.hasNext();) { DAVElement property = (DAVElement) props.next(); DAVUtil.setSpecialWCProperties(properties, property, dirProps.getPropertyValue(property)); } } } finally { closeConnection(); } return dirRevision; }
diff --git a/nutsnbolts/src/main/java/org/smallmind/nutsnbolts/layout/SequentialBox.java b/nutsnbolts/src/main/java/org/smallmind/nutsnbolts/layout/SequentialBox.java index 9f2e5ff73..69b536b64 100644 --- a/nutsnbolts/src/main/java/org/smallmind/nutsnbolts/layout/SequentialBox.java +++ b/nutsnbolts/src/main/java/org/smallmind/nutsnbolts/layout/SequentialBox.java @@ -1,344 +1,344 @@ /* * Copyright (c) 2007, 2008, 2009, 2010, 2011, 2012 David Berkman * * This file is part of the SmallMind Code Project. * * The SmallMind Code Project is free software, you can redistribute * it and/or modify it under the terms of 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. * * The SmallMind Code Project is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the the GNU Affero General Public * License, along with The SmallMind Code Project. If not, see * <http://www.gnu.org/licenses/>. * * Additional permission under the GNU Affero GPL version 3 section 7 * ------------------------------------------------------------------ * If you modify this Program, or any covered work, by linking or * combining it with other code, such other code is not for that reason * alone subject to any of the requirements of the GNU Affero GPL * version 3. */ package org.smallmind.nutsnbolts.layout; import java.util.Iterator; import java.util.LinkedList; import org.smallmind.nutsnbolts.lang.UnknownSwitchCaseException; public class SequentialBox extends Box<SequentialBox> { private Justification justification; private double gap; private boolean greedy; protected SequentialBox (ParaboxLayout layout) { this(layout, Gap.UNRELATED); } protected SequentialBox (ParaboxLayout layout, boolean greedy) { this(layout, Gap.UNRELATED, greedy); } protected SequentialBox (ParaboxLayout layout, Gap gap) { this(layout, gap.getGap(layout.getContainer().getPlatform())); } protected SequentialBox (ParaboxLayout layout, Gap gap, boolean greedy) { this(layout, gap.getGap(layout.getContainer().getPlatform()), greedy); } protected SequentialBox (ParaboxLayout layout, double gap) { this(layout, gap, Justification.LEADING); } protected SequentialBox (ParaboxLayout layout, double gap, boolean greedy) { this(layout, gap, Justification.LEADING, greedy); } protected SequentialBox (ParaboxLayout layout, Justification justification) { this(layout, Gap.UNRELATED, justification); } protected SequentialBox (ParaboxLayout layout, Justification justification, boolean greedy) { this(layout, Gap.UNRELATED, justification, greedy); } protected SequentialBox (ParaboxLayout layout, Gap gap, Justification justification) { this(layout, gap.getGap(layout.getContainer().getPlatform()), justification); } protected SequentialBox (ParaboxLayout layout, Gap gap, Justification justification, boolean greedy) { this(layout, gap.getGap(layout.getContainer().getPlatform()), justification, greedy); } protected SequentialBox (ParaboxLayout layout, double gap, Justification justification) { this(layout, gap, justification, false); } protected SequentialBox (ParaboxLayout layout, double gap, Justification justification, boolean greedy) { super(SequentialBox.class, layout); this.justification = justification; this.gap = gap; this.greedy = greedy; } public double getGap () { return gap; } public SequentialBox setGap (Gap gap) { return setGap(gap.getGap(getLayout().getContainer().getPlatform())); } public SequentialBox setGap (double gap) { this.gap = gap; return this; } public Justification getJustification () { return justification; } public SequentialBox setJustification (Justification justification) { this.justification = justification; return this; } public boolean isGreedy () { return greedy; } public SequentialBox setGreedy (boolean greedy) { this.greedy = greedy; return this; } @Override public double calculateMinimumMeasurement (Bias bias, LayoutTailor tailor) { return calculateMeasurement(bias, TapeMeasure.MINIMUM, tailor); } @Override public double calculatePreferredMeasurement (Bias bias, LayoutTailor tailor) { return calculateMeasurement(bias, TapeMeasure.PREFERRED, tailor); } @Override public double calculateMaximumMeasurement (Bias bias, LayoutTailor tailor) { return greedy ? Integer.MAX_VALUE : calculateMeasurement(bias, TapeMeasure.MAXIMUM, tailor); } private synchronized double calculateMeasurement (Bias bias, TapeMeasure tapeMeasure, LayoutTailor tailor) { double total = 0.0D; if (!getElements().isEmpty()) { boolean first = true; for (ParaboxElement<?> element : getElements()) { total += tapeMeasure.getMeasure(bias, element, tailor); if (!first) { total += gap; } first = false; } } return total; } @Override public synchronized void doLayout (Bias bias, double containerPosition, double containerMeasurement, LayoutTailor tailor) { if (!getElements().isEmpty()) { double preferredContainerMeasure; if (containerMeasurement <= calculateMeasurement(bias, TapeMeasure.MINIMUM, tailor)) { double currentMeasure; double top = 0; for (ParaboxElement<?> element : getElements()) { tailor.applyLayout(bias, containerPosition + top, currentMeasure = element.getMinimumMeasurement(bias, tailor), element); top += currentMeasure + gap; } } else if (containerMeasurement <= (preferredContainerMeasure = calculateMeasurement(bias, TapeMeasure.PREFERRED, tailor))) { double[] preferredBiasedMeasurements = new double[getElements().size()]; double[] fat = new double[getElements().size()]; double currentMeasure; double totalShrink = 0; double totalFat = 0; double top = 0; int index; index = 0; for (ParaboxElement<?> element : getElements()) { totalShrink += element.getConstraint().getShrink(); - totalFat += (fat[index++] = (preferredBiasedMeasurements[index] = element.getPreferredMeasurement(bias, tailor)) - element.getMinimumMeasurement(bias, tailor)); + totalFat += (fat[index] = (preferredBiasedMeasurements[index++] = element.getPreferredMeasurement(bias, tailor)) - element.getMinimumMeasurement(bias, tailor)); } index = 0; for (ParaboxElement<?> element : getElements()) { double totalRatio = (totalShrink + totalFat == 0) ? 0 : (element.getConstraint().getShrink() + fat[index]) / (totalShrink + totalFat); - tailor.applyLayout(bias, containerPosition + top, currentMeasure = preferredBiasedMeasurements[index] - (totalRatio * (preferredContainerMeasure - containerMeasurement)), element); + tailor.applyLayout(bias, containerPosition + top, currentMeasure = preferredBiasedMeasurements[index++] - (totalRatio * (preferredContainerMeasure - containerMeasurement)), element); top += currentMeasure + gap; } } else { LinkedList<ReorderedElement> reorderedElements = new LinkedList<ReorderedElement>(); double[] tentativeMeasurements = new double[getElements().size()]; double[] maximumMeasurements = new double[getElements().size()]; double unused = containerMeasurement - preferredContainerMeasure; double totalGrow = 0; int index = 0; for (ParaboxElement<?> element : getElements()) { double grow; if ((grow = element.getConstraint().getGrow()) > 0) { totalGrow += grow; reorderedElements.add(new ReorderedElement(element, index)); } tentativeMeasurements[index] = element.getPreferredMeasurement(bias, tailor); maximumMeasurements[index++] = element.getMaximumMeasurement(bias, tailor); } if (!reorderedElements.isEmpty()) { do { Iterator<ReorderedElement> reorderedElementIter = reorderedElements.iterator(); double used = 0; double spentGrowth = 0; while (reorderedElementIter.hasNext()) { ReorderedElement reorderedElement = reorderedElementIter.next(); double currentUnused; double currentGrow; if ((tentativeMeasurements[reorderedElement.getOriginalIndex()] + (currentUnused = ((currentGrow = reorderedElement.getReorderedElement().getConstraint().getGrow()) / totalGrow * unused))) < maximumMeasurements[reorderedElement.getOriginalIndex()]) { used += currentUnused; tentativeMeasurements[reorderedElement.getOriginalIndex()] += currentUnused; } else { used += maximumMeasurements[reorderedElement.getOriginalIndex()] - tentativeMeasurements[reorderedElement.getOriginalIndex()]; tentativeMeasurements[reorderedElement.getOriginalIndex()] = maximumMeasurements[reorderedElement.getOriginalIndex()]; spentGrowth += currentGrow; reorderedElementIter.remove(); } } unused -= used; totalGrow -= spentGrowth; } while ((!reorderedElements.isEmpty()) && (unused >= 1.0)); } switch (getJustification()) { case FIRST: applyLayouts(bias, containerPosition, true, tentativeMeasurements, tailor); break; case LAST: applyLayouts(bias, containerPosition + containerMeasurement, false, tentativeMeasurements, tailor); break; case LEADING: if (!bias.equals(getLayout().getContainer().getPlatform().getOrientation().getBias())) { applyLayouts(bias, containerPosition, true, tentativeMeasurements, tailor); } else { switch (getLayout().getContainer().getPlatform().getOrientation().getFlow()) { case FIRST_TO_LAST: applyLayouts(bias, containerPosition, true, tentativeMeasurements, tailor); break; case LAST_TO_FIRST: applyLayouts(bias, containerPosition + containerMeasurement, false, tentativeMeasurements, tailor); break; default: throw new UnknownSwitchCaseException(getLayout().getContainer().getPlatform().getOrientation().getFlow().name()); } } break; case TRAILING: if (!bias.equals(getLayout().getContainer().getPlatform().getOrientation().getBias())) { applyLayouts(bias, containerPosition + containerMeasurement, false, tentativeMeasurements, tailor); } else { switch (getLayout().getContainer().getPlatform().getOrientation().getFlow()) { case FIRST_TO_LAST: applyLayouts(bias, containerPosition + containerMeasurement, false, tentativeMeasurements, tailor); break; case LAST_TO_FIRST: applyLayouts(bias, containerPosition, true, tentativeMeasurements, tailor); break; default: throw new UnknownSwitchCaseException(getLayout().getContainer().getPlatform().getOrientation().getFlow().name()); } } break; case CENTER: applyLayouts(bias, containerPosition + (unused / 2), true, tentativeMeasurements, tailor); break; default: throw new UnknownSwitchCaseException(getJustification().name()); } } } } private void applyLayouts (Bias bias, double top, Boolean forward, double[] tentativeMeasurements, LayoutTailor tailor) { int index = 0; for (ParaboxElement<?> element : getElements()) { if (forward) { tailor.applyLayout(bias, top, tentativeMeasurements[index], element); top += tentativeMeasurements[index++] + gap; } else { tailor.applyLayout(bias, top -= tentativeMeasurements[index], tentativeMeasurements[index++], element); top -= gap; } } } }
false
true
public synchronized void doLayout (Bias bias, double containerPosition, double containerMeasurement, LayoutTailor tailor) { if (!getElements().isEmpty()) { double preferredContainerMeasure; if (containerMeasurement <= calculateMeasurement(bias, TapeMeasure.MINIMUM, tailor)) { double currentMeasure; double top = 0; for (ParaboxElement<?> element : getElements()) { tailor.applyLayout(bias, containerPosition + top, currentMeasure = element.getMinimumMeasurement(bias, tailor), element); top += currentMeasure + gap; } } else if (containerMeasurement <= (preferredContainerMeasure = calculateMeasurement(bias, TapeMeasure.PREFERRED, tailor))) { double[] preferredBiasedMeasurements = new double[getElements().size()]; double[] fat = new double[getElements().size()]; double currentMeasure; double totalShrink = 0; double totalFat = 0; double top = 0; int index; index = 0; for (ParaboxElement<?> element : getElements()) { totalShrink += element.getConstraint().getShrink(); totalFat += (fat[index++] = (preferredBiasedMeasurements[index] = element.getPreferredMeasurement(bias, tailor)) - element.getMinimumMeasurement(bias, tailor)); } index = 0; for (ParaboxElement<?> element : getElements()) { double totalRatio = (totalShrink + totalFat == 0) ? 0 : (element.getConstraint().getShrink() + fat[index]) / (totalShrink + totalFat); tailor.applyLayout(bias, containerPosition + top, currentMeasure = preferredBiasedMeasurements[index] - (totalRatio * (preferredContainerMeasure - containerMeasurement)), element); top += currentMeasure + gap; } } else { LinkedList<ReorderedElement> reorderedElements = new LinkedList<ReorderedElement>(); double[] tentativeMeasurements = new double[getElements().size()]; double[] maximumMeasurements = new double[getElements().size()]; double unused = containerMeasurement - preferredContainerMeasure; double totalGrow = 0; int index = 0; for (ParaboxElement<?> element : getElements()) { double grow; if ((grow = element.getConstraint().getGrow()) > 0) { totalGrow += grow; reorderedElements.add(new ReorderedElement(element, index)); } tentativeMeasurements[index] = element.getPreferredMeasurement(bias, tailor); maximumMeasurements[index++] = element.getMaximumMeasurement(bias, tailor); } if (!reorderedElements.isEmpty()) { do { Iterator<ReorderedElement> reorderedElementIter = reorderedElements.iterator(); double used = 0; double spentGrowth = 0; while (reorderedElementIter.hasNext()) { ReorderedElement reorderedElement = reorderedElementIter.next(); double currentUnused; double currentGrow; if ((tentativeMeasurements[reorderedElement.getOriginalIndex()] + (currentUnused = ((currentGrow = reorderedElement.getReorderedElement().getConstraint().getGrow()) / totalGrow * unused))) < maximumMeasurements[reorderedElement.getOriginalIndex()]) { used += currentUnused; tentativeMeasurements[reorderedElement.getOriginalIndex()] += currentUnused; } else { used += maximumMeasurements[reorderedElement.getOriginalIndex()] - tentativeMeasurements[reorderedElement.getOriginalIndex()]; tentativeMeasurements[reorderedElement.getOriginalIndex()] = maximumMeasurements[reorderedElement.getOriginalIndex()]; spentGrowth += currentGrow; reorderedElementIter.remove(); } } unused -= used; totalGrow -= spentGrowth; } while ((!reorderedElements.isEmpty()) && (unused >= 1.0)); } switch (getJustification()) { case FIRST: applyLayouts(bias, containerPosition, true, tentativeMeasurements, tailor); break; case LAST: applyLayouts(bias, containerPosition + containerMeasurement, false, tentativeMeasurements, tailor); break; case LEADING: if (!bias.equals(getLayout().getContainer().getPlatform().getOrientation().getBias())) { applyLayouts(bias, containerPosition, true, tentativeMeasurements, tailor); } else { switch (getLayout().getContainer().getPlatform().getOrientation().getFlow()) { case FIRST_TO_LAST: applyLayouts(bias, containerPosition, true, tentativeMeasurements, tailor); break; case LAST_TO_FIRST: applyLayouts(bias, containerPosition + containerMeasurement, false, tentativeMeasurements, tailor); break; default: throw new UnknownSwitchCaseException(getLayout().getContainer().getPlatform().getOrientation().getFlow().name()); } } break; case TRAILING: if (!bias.equals(getLayout().getContainer().getPlatform().getOrientation().getBias())) { applyLayouts(bias, containerPosition + containerMeasurement, false, tentativeMeasurements, tailor); } else { switch (getLayout().getContainer().getPlatform().getOrientation().getFlow()) { case FIRST_TO_LAST: applyLayouts(bias, containerPosition + containerMeasurement, false, tentativeMeasurements, tailor); break; case LAST_TO_FIRST: applyLayouts(bias, containerPosition, true, tentativeMeasurements, tailor); break; default: throw new UnknownSwitchCaseException(getLayout().getContainer().getPlatform().getOrientation().getFlow().name()); } } break; case CENTER: applyLayouts(bias, containerPosition + (unused / 2), true, tentativeMeasurements, tailor); break; default: throw new UnknownSwitchCaseException(getJustification().name()); } } } }
public synchronized void doLayout (Bias bias, double containerPosition, double containerMeasurement, LayoutTailor tailor) { if (!getElements().isEmpty()) { double preferredContainerMeasure; if (containerMeasurement <= calculateMeasurement(bias, TapeMeasure.MINIMUM, tailor)) { double currentMeasure; double top = 0; for (ParaboxElement<?> element : getElements()) { tailor.applyLayout(bias, containerPosition + top, currentMeasure = element.getMinimumMeasurement(bias, tailor), element); top += currentMeasure + gap; } } else if (containerMeasurement <= (preferredContainerMeasure = calculateMeasurement(bias, TapeMeasure.PREFERRED, tailor))) { double[] preferredBiasedMeasurements = new double[getElements().size()]; double[] fat = new double[getElements().size()]; double currentMeasure; double totalShrink = 0; double totalFat = 0; double top = 0; int index; index = 0; for (ParaboxElement<?> element : getElements()) { totalShrink += element.getConstraint().getShrink(); totalFat += (fat[index] = (preferredBiasedMeasurements[index++] = element.getPreferredMeasurement(bias, tailor)) - element.getMinimumMeasurement(bias, tailor)); } index = 0; for (ParaboxElement<?> element : getElements()) { double totalRatio = (totalShrink + totalFat == 0) ? 0 : (element.getConstraint().getShrink() + fat[index]) / (totalShrink + totalFat); tailor.applyLayout(bias, containerPosition + top, currentMeasure = preferredBiasedMeasurements[index++] - (totalRatio * (preferredContainerMeasure - containerMeasurement)), element); top += currentMeasure + gap; } } else { LinkedList<ReorderedElement> reorderedElements = new LinkedList<ReorderedElement>(); double[] tentativeMeasurements = new double[getElements().size()]; double[] maximumMeasurements = new double[getElements().size()]; double unused = containerMeasurement - preferredContainerMeasure; double totalGrow = 0; int index = 0; for (ParaboxElement<?> element : getElements()) { double grow; if ((grow = element.getConstraint().getGrow()) > 0) { totalGrow += grow; reorderedElements.add(new ReorderedElement(element, index)); } tentativeMeasurements[index] = element.getPreferredMeasurement(bias, tailor); maximumMeasurements[index++] = element.getMaximumMeasurement(bias, tailor); } if (!reorderedElements.isEmpty()) { do { Iterator<ReorderedElement> reorderedElementIter = reorderedElements.iterator(); double used = 0; double spentGrowth = 0; while (reorderedElementIter.hasNext()) { ReorderedElement reorderedElement = reorderedElementIter.next(); double currentUnused; double currentGrow; if ((tentativeMeasurements[reorderedElement.getOriginalIndex()] + (currentUnused = ((currentGrow = reorderedElement.getReorderedElement().getConstraint().getGrow()) / totalGrow * unused))) < maximumMeasurements[reorderedElement.getOriginalIndex()]) { used += currentUnused; tentativeMeasurements[reorderedElement.getOriginalIndex()] += currentUnused; } else { used += maximumMeasurements[reorderedElement.getOriginalIndex()] - tentativeMeasurements[reorderedElement.getOriginalIndex()]; tentativeMeasurements[reorderedElement.getOriginalIndex()] = maximumMeasurements[reorderedElement.getOriginalIndex()]; spentGrowth += currentGrow; reorderedElementIter.remove(); } } unused -= used; totalGrow -= spentGrowth; } while ((!reorderedElements.isEmpty()) && (unused >= 1.0)); } switch (getJustification()) { case FIRST: applyLayouts(bias, containerPosition, true, tentativeMeasurements, tailor); break; case LAST: applyLayouts(bias, containerPosition + containerMeasurement, false, tentativeMeasurements, tailor); break; case LEADING: if (!bias.equals(getLayout().getContainer().getPlatform().getOrientation().getBias())) { applyLayouts(bias, containerPosition, true, tentativeMeasurements, tailor); } else { switch (getLayout().getContainer().getPlatform().getOrientation().getFlow()) { case FIRST_TO_LAST: applyLayouts(bias, containerPosition, true, tentativeMeasurements, tailor); break; case LAST_TO_FIRST: applyLayouts(bias, containerPosition + containerMeasurement, false, tentativeMeasurements, tailor); break; default: throw new UnknownSwitchCaseException(getLayout().getContainer().getPlatform().getOrientation().getFlow().name()); } } break; case TRAILING: if (!bias.equals(getLayout().getContainer().getPlatform().getOrientation().getBias())) { applyLayouts(bias, containerPosition + containerMeasurement, false, tentativeMeasurements, tailor); } else { switch (getLayout().getContainer().getPlatform().getOrientation().getFlow()) { case FIRST_TO_LAST: applyLayouts(bias, containerPosition + containerMeasurement, false, tentativeMeasurements, tailor); break; case LAST_TO_FIRST: applyLayouts(bias, containerPosition, true, tentativeMeasurements, tailor); break; default: throw new UnknownSwitchCaseException(getLayout().getContainer().getPlatform().getOrientation().getFlow().name()); } } break; case CENTER: applyLayouts(bias, containerPosition + (unused / 2), true, tentativeMeasurements, tailor); break; default: throw new UnknownSwitchCaseException(getJustification().name()); } } } }
diff --git a/src/uk/co/quartzcraft/kingdoms/command/KingdomCreateSubCommand.java b/src/uk/co/quartzcraft/kingdoms/command/KingdomCreateSubCommand.java index 839c270..1155ca1 100644 --- a/src/uk/co/quartzcraft/kingdoms/command/KingdomCreateSubCommand.java +++ b/src/uk/co/quartzcraft/kingdoms/command/KingdomCreateSubCommand.java @@ -1,47 +1,47 @@ package uk.co.quartzcraft.kingdoms.command; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import uk.co.quartzcraft.core.chat.ChatPhrase; import uk.co.quartzcraft.core.command.QSubCommand; import uk.co.quartzcraft.kingdoms.QuartzKingdoms; import uk.co.quartzcraft.kingdoms.kingdom.Kingdom;; public class KingdomCreateSubCommand extends QSubCommand { @Override public String getPermission() { return "QCK.Kingdom.create"; } @Override public void onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(args[1] != null) { if(args[2] != null) { sender.sendMessage(ChatPhrase.getPhrase("kingdom_name_single_word")); } else { String kingdomName = Kingdom.createKingdom(args[1], sender); if(kingdomName != null) { if(kingdomName == args[1]) { sender.sendMessage(ChatPhrase.getPhrase("created_kingdom_yes") + ChatColor.WHITE + kingdomName); - } else if(kingdomName == "quartz error") { + } else if(kingdomName == "name_error") { sender.sendMessage(ChatPhrase.getPhrase("kingdomname_already_used") + ChatColor.WHITE + kingdomName); } } else { sender.sendMessage(ChatPhrase.getPhrase("created_kingdom_no") + ChatColor.WHITE + kingdomName); } } } else { sender.sendMessage(ChatPhrase.getPhrase("specify_kingdom_name") + ChatColor.WHITE + args[1]); } } }
true
true
public void onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(args[1] != null) { if(args[2] != null) { sender.sendMessage(ChatPhrase.getPhrase("kingdom_name_single_word")); } else { String kingdomName = Kingdom.createKingdom(args[1], sender); if(kingdomName != null) { if(kingdomName == args[1]) { sender.sendMessage(ChatPhrase.getPhrase("created_kingdom_yes") + ChatColor.WHITE + kingdomName); } else if(kingdomName == "quartz error") { sender.sendMessage(ChatPhrase.getPhrase("kingdomname_already_used") + ChatColor.WHITE + kingdomName); } } else { sender.sendMessage(ChatPhrase.getPhrase("created_kingdom_no") + ChatColor.WHITE + kingdomName); } } } else { sender.sendMessage(ChatPhrase.getPhrase("specify_kingdom_name") + ChatColor.WHITE + args[1]); } }
public void onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(args[1] != null) { if(args[2] != null) { sender.sendMessage(ChatPhrase.getPhrase("kingdom_name_single_word")); } else { String kingdomName = Kingdom.createKingdom(args[1], sender); if(kingdomName != null) { if(kingdomName == args[1]) { sender.sendMessage(ChatPhrase.getPhrase("created_kingdom_yes") + ChatColor.WHITE + kingdomName); } else if(kingdomName == "name_error") { sender.sendMessage(ChatPhrase.getPhrase("kingdomname_already_used") + ChatColor.WHITE + kingdomName); } } else { sender.sendMessage(ChatPhrase.getPhrase("created_kingdom_no") + ChatColor.WHITE + kingdomName); } } } else { sender.sendMessage(ChatPhrase.getPhrase("specify_kingdom_name") + ChatColor.WHITE + args[1]); } }
diff --git a/src/java/net/sf/jabref/journals/ManageJournalsPanel.java b/src/java/net/sf/jabref/journals/ManageJournalsPanel.java index 7c7e8158e..d92f74963 100644 --- a/src/java/net/sf/jabref/journals/ManageJournalsPanel.java +++ b/src/java/net/sf/jabref/journals/ManageJournalsPanel.java @@ -1,645 +1,644 @@ /* Copyright (C) 2003-2011 JabRef contributors. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package net.sf.jabref.journals; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.*; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import javax.swing.*; import javax.swing.table.AbstractTableModel; import net.sf.jabref.GUIGlobals; import net.sf.jabref.Globals; import net.sf.jabref.HelpAction; import net.sf.jabref.JabRefFrame; import net.sf.jabref.gui.FileDialogs; import net.sf.jabref.net.URLDownload; import com.jgoodies.forms.builder.ButtonBarBuilder; import com.jgoodies.forms.builder.ButtonStackBuilder; import com.jgoodies.forms.builder.DefaultFormBuilder; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; /** * Created by IntelliJ IDEA. * User: alver * Date: Sep 19, 2005 * Time: 7:57:29 PM * To browseOld this template use File | Settings | File Templates. */ public class ManageJournalsPanel extends JPanel{ JabRefFrame frame; JTextField personalFile = new JTextField(); AbbreviationsTableModel tableModel = new AbbreviationsTableModel(); JTable userTable; // builtInTable JPanel userPanel = new JPanel(), journalEditPanel, externalFilesPanel = new JPanel(), addExtPan = new JPanel(); JTextField nameTf = new JTextField(), newNameTf = new JTextField(), abbrTf = new JTextField(); List<ExternalFileEntry> externals = new ArrayList<ExternalFileEntry>(); // To hold references to external journal lists. JDialog dialog; JRadioButton newFile = new JRadioButton(Globals.lang("New file")), oldFile = new JRadioButton(Globals.lang("Existing file")); JButton add = new JButton(GUIGlobals.getImage("add")), remove = new JButton(GUIGlobals.getImage("remove")), ok = new JButton(Globals.lang("Ok")), cancel = new JButton(Globals.lang("Cancel")), help = new JButton(Globals.lang("Help")), browseOld = new JButton(Globals.lang("Browse")), browseNew = new JButton(Globals.lang("Browse")), addExt = new JButton(GUIGlobals.getImage("add")), viewBuiltin = new JButton(Globals.lang("View")); public ManageJournalsPanel(final JabRefFrame frame) { this.frame = frame; personalFile.setEditable(false); ButtonGroup group = new ButtonGroup(); group.add(newFile); group.add(oldFile); addExtPan.setLayout(new BorderLayout()); addExtPan.add(addExt, BorderLayout.EAST); addExtPan.setToolTipText(Globals.lang("Add")); //addExtPan.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.red)); FormLayout layout = new FormLayout ("1dlu, 8dlu, left:pref, 4dlu, fill:200dlu:grow, 4dlu, fill:pref",// 4dlu, left:pref, 4dlu", "pref, pref, pref, 20dlu, 20dlu, fill:200dlu, 4dlu, pref");//150dlu"); DefaultFormBuilder builder = new DefaultFormBuilder(layout); CellConstraints cc = new CellConstraints(); /*JLabel description = new JLabel("<HTML>"+Globals.lang("JabRef can switch journal names between " +"abbreviated and full form. Since it knows only a limited number of journal names, " +"you may need to add your own definitions.")+"</HTML>");*/ builder.addSeparator(Globals.lang("Built-in journal list"), cc.xyw(2,1,6)); JLabel description = new JLabel("<HTML>"+Globals.lang("JabRef includes a built-in list of journal abbreviations.") +"<br>"+Globals.lang("You can add additional journal names by setting up a personal journal list,<br>as " +"well as linking to external journal lists.")+"</HTML>"); description.setBorder(BorderFactory.createEmptyBorder(5,0,5,0)); builder.add(description, cc.xyw(2,2,6)); builder.add(viewBuiltin, cc.xy(7,2)); builder.addSeparator(Globals.lang("Personal journal list"), cc.xyw(2,3,6)); //builder.add(description, cc.xyw(2,1,6)); builder.add(newFile, cc.xy(3,4)); builder.add(newNameTf, cc.xy(5,4)); builder.add(browseNew, cc.xy(7,4)); builder.add(oldFile, cc.xy(3,5)); builder.add(personalFile, cc.xy(5,5)); //BrowseAction action = new BrowseAction(personalFile, false); //JButton browse = new JButton(Globals.lang("Browse")); //browse.addActionListener(action); builder.add(browseOld, cc.xy(7,5)); userPanel.setLayout(new BorderLayout()); //builtInTable = new JTable(Globals.journalAbbrev.getTableModel()); builder.add(userPanel, cc.xyw(2,6,4)); ButtonStackBuilder butBul = new ButtonStackBuilder(); butBul.addGridded(add); butBul.addGridded(remove); butBul.addGlue(); builder.add(butBul.getPanel(), cc.xy(7,6)); builder.addSeparator(Globals.lang("External files"), cc.xyw(2,8,6)); externalFilesPanel.setLayout(new BorderLayout()); //builder.add(/*new JScrollPane(*/externalFilesPanel/*)*/, cc.xyw(2,8,6)); setLayout(new BorderLayout()); builder.getPanel().setBorder(BorderFactory.createEmptyBorder(5,5,5,5));//createMatteBorder(1,1,1,1,Color.green)); add(builder.getPanel(), BorderLayout.NORTH); add(externalFilesPanel, BorderLayout.CENTER); ButtonBarBuilder bb = new ButtonBarBuilder(); bb.addGlue(); bb.addGridded(ok); bb.addGridded(cancel); bb.addUnrelatedGap(); bb.addGridded(help); bb.addGlue(); bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); dialog = new JDialog(frame, Globals.lang("Journal abbreviations"), false); dialog.getContentPane().add(this, BorderLayout.CENTER); dialog.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH); //add(new JScrollPane(builtInTable), BorderLayout.CENTER); // Set up panel for editing a single journal, to be used in a dialog box: FormLayout layout2 = new FormLayout ("right:pref, 4dlu, fill:180dlu", ""); DefaultFormBuilder builder2 = new DefaultFormBuilder(layout2); builder2.append(Globals.lang("Journal name")); builder2.append(nameTf); builder2.nextLine(); builder2.append(Globals.lang("ISO abbreviation")); builder2.append(abbrTf); journalEditPanel = builder2.getPanel(); viewBuiltin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JournalAbbreviations abbr = new JournalAbbreviations(Globals.JOURNALS_FILE_BUILTIN); JTable table = new JTable(abbr.getTableModel()); JScrollPane pane = new JScrollPane(table); JOptionPane.showMessageDialog(null, pane, Globals.lang("Journal list preview"), JOptionPane.INFORMATION_MESSAGE); } }); browseNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File old = null; if (!newNameTf.getText().equals("")) old = new File(newNameTf.getText()); String name = FileDialogs.getNewFile(frame, old, null, JFileChooser.SAVE_DIALOG, false); if (name != null) { if ((old != null) && (tableModel.getRowCount() > 0)) { } newNameTf.setText(name); newFile.setSelected(true); } } }); browseOld.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File old = null; if (!personalFile.getText().equals("")) old = new File(personalFile.getText()); String name = FileDialogs.getNewFile(frame, old, null, JFileChooser.OPEN_DIALOG, false); if (name != null) { if ((old != null) && (tableModel.getRowCount() > 0)) { } personalFile.setText(name); oldFile.setSelected(true); oldFile.setEnabled(true); setupUserTable(); } } }); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (readyToClose()) { storeSettings(); dialog.dispose(); } } }); help.addActionListener(new HelpAction(Globals.helpDiag, GUIGlobals.journalAbbrHelp)); AbstractAction cancelAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { dialog.dispose(); } }; cancel.addActionListener(cancelAction); add.addActionListener(tableModel); remove.addActionListener(tableModel); addExt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { externals.add(new ExternalFileEntry()); buildExternalsPanel(); } }); // Key bindings: ActionMap am = getActionMap(); InputMap im = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); im.put(Globals.prefs.getKey("Close dialog"), "close"); am.put("close", cancelAction); //dialog.pack(); int xSize = getPreferredSize().width; dialog.setSize(xSize+10,700); } public JDialog getDialog() { return dialog; } public void setValues() { personalFile.setText(Globals.prefs.get("personalJournalList")); if (personalFile.getText().length() == 0) { newFile.setSelected(true); oldFile.setEnabled(false); } else { oldFile.setSelected(true); oldFile.setEnabled(true); } setupUserTable(); setupExternals(); buildExternalsPanel(); } private void buildExternalsPanel() { DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout("fill:pref:grow","")); for (Iterator<ExternalFileEntry> i=externals.iterator(); i.hasNext();) { ExternalFileEntry efe = i.next(); builder.append(efe.getPanel()); builder.nextLine(); } builder.append(Box.createVerticalGlue()); builder.nextLine(); builder.append(addExtPan); builder.nextLine(); builder.append(Box.createVerticalGlue()); //builder.getPanel().setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.green)); //externalFilesPanel.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.red)); JScrollPane pane = new JScrollPane(builder.getPanel()); pane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); externalFilesPanel.setMinimumSize(new Dimension(400,400)); externalFilesPanel.setPreferredSize(new Dimension(400,400)); externalFilesPanel.removeAll(); externalFilesPanel.add(pane, BorderLayout.CENTER); externalFilesPanel.revalidate(); externalFilesPanel.repaint(); } private void setupExternals() { String[] externalFiles = Globals.prefs.getStringArray("externalJournalLists"); if ((externalFiles == null) || (externalFiles.length == 0)) { ExternalFileEntry efe = new ExternalFileEntry(); externals.add(efe); } else { for (int i=0; i<externalFiles.length; i++) { ExternalFileEntry efe = new ExternalFileEntry(externalFiles[i]); externals.add(efe); } } //efe = new ExternalFileEntry(); //externals.add(efe); } public void setupUserTable() { JournalAbbreviations userAbbr = new JournalAbbreviations(); String filename = personalFile.getText(); if (!filename.equals("") && (new File(filename)).exists()) { try { userAbbr.readJournalList(new File(filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } } tableModel.setJournals(userAbbr.getJournals()); userTable = new JTable(tableModel); userTable.addMouseListener(tableModel.getMouseListener()); userPanel.add(new JScrollPane(userTable), BorderLayout.CENTER); } public boolean readyToClose() { File f; if (newFile.isSelected()) { if (newNameTf.getText().length() > 0) { f = new File(newNameTf.getText()); return (!f.exists() || (JOptionPane.showConfirmDialog (this, "'"+f.getName()+"' "+Globals.lang("exists. Overwrite file?"), Globals.lang("Store journal abbreviations"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION)); } else { if (tableModel.getRowCount() > 0) { JOptionPane.showMessageDialog(this, Globals.lang("You must choose a file name to store journal abbreviations"), Globals.lang("Store journal abbreviations"), JOptionPane.ERROR_MESSAGE); return false; } else return true; } } return true; } public void storeSettings() { File f = null; if (newFile.isSelected()) { if (newNameTf.getText().length() > 0) { f = new File(newNameTf.getText()); }// else { // return; // Nothing to do. //} } else f = new File(personalFile.getText()); if (f != null) { FileWriter fw = null; try { fw = new FileWriter(f, false); for (Iterator<JournalEntry> i=tableModel.getJournals().iterator(); i.hasNext();) { JournalEntry entry = i.next(); fw.write(entry.name); fw.write(" = "); fw.write(entry.abbreviation); fw.write(Globals.NEWLINE); } } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } String filename = f.getPath(); if (filename.equals("")) filename = null; Globals.prefs.put("personalJournalList", filename); } // Store the list of external files set up: ArrayList<String> extFiles = new ArrayList<String>(); for (Iterator<ExternalFileEntry> i=externals.iterator(); i.hasNext();) { ExternalFileEntry efe = i.next(); if (!efe.getValue().equals("")) { extFiles.add(efe.getValue()); } } if (extFiles.size() == 0) Globals.prefs.put("externalJournalLists", ""); else { String[] list = extFiles.toArray(new String[extFiles.size()]); Globals.prefs.putStringArray("externalJournalLists", list); } Globals.initializeJournalNames(); // Update the autocompleter for the "journal" field in all base panels, // so added journal names are available: for (int i=0; i<frame.baseCount(); i++) { frame.baseAt(i).addJournalListToAutoCompleter(); } } class DownloadAction extends AbstractAction { JTextField comp; public DownloadAction(JTextField tc) { super(Globals.lang("Download")); comp = tc; } public void actionPerformed(ActionEvent e) { String chosen = null; chosen = JOptionPane.showInputDialog(Globals.lang("Choose the URL to download. The default value points to a list provided by the JabRef developers."), "http://jabref.sf.net/journals/journal_abbreviations_general.txt"); if (chosen == null) return; File toFile; try { URL url = new URL(chosen); String toName = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")), null, JFileChooser.SAVE_DIALOG, false); if (toName == null) return; else toFile = new File(toName); URLDownload ud = new URLDownload(comp, url, toFile); ud.download(); comp.setText(toFile.getPath()); - } catch (MalformedURLException ex) { - ex.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } catch (IOException ex2) { - ex2.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, Globals.lang("Error downloading file '%0'", chosen), + Globals.lang("Download failed"), JOptionPane.ERROR_MESSAGE); } } } class BrowseAction extends AbstractAction { JTextField comp; boolean dir; public BrowseAction(JTextField tc, boolean dir) { super(Globals.lang("Browse")); this.dir = dir; comp = tc; } public void actionPerformed(ActionEvent e) { String chosen = null; if (dir) chosen = FileDialogs.getNewDir(frame, new File(comp.getText()), Globals.NONE, JFileChooser.OPEN_DIALOG, false); else chosen = FileDialogs.getNewFile(frame, new File(comp.getText()), Globals.NONE, JFileChooser.OPEN_DIALOG, false); if (chosen != null) { File newFile = new File(chosen); comp.setText(newFile.getPath()); } } } class AbbreviationsTableModel extends AbstractTableModel implements ActionListener { String[] names = new String[] {Globals.lang("Journal name"), Globals.lang("Abbreviation")}; ArrayList<JournalEntry> journals = null; public AbbreviationsTableModel() { } public void setJournals(Map<String, String> journals) { this.journals = new ArrayList<JournalEntry>(); for (Map.Entry<String, String> entry : journals.entrySet()){ this.journals.add(new JournalEntry(entry.getKey(), entry.getValue())); } fireTableDataChanged(); } public ArrayList<JournalEntry> getJournals() { return journals; } public int getColumnCount() { return 2; } public int getRowCount() { return journals.size(); } public Object getValueAt(int row, int col) { if (col == 0) return journals.get(row).name; else return journals.get(row).abbreviation; } public void setValueAt(Object object, int row, int col) { JournalEntry entry = journals.get(row); if (col == 0) entry.name = (String)object; else entry.abbreviation = (String)object; } public String getColumnName(int i) { return names[i]; } public boolean isCellEditable(int i, int i1) { return false; } public MouseListener getMouseListener() { return new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { JTable table = (JTable)e.getSource(); int row = table.rowAtPoint(e.getPoint()); nameTf.setText((String)getValueAt(row,0)); abbrTf.setText((String)getValueAt(row,1)); if (JOptionPane.showConfirmDialog(dialog, journalEditPanel, Globals.lang("Edit journal"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { setValueAt(nameTf.getText(), row, 0); setValueAt(abbrTf.getText(), row, 1); Collections.sort(journals); fireTableDataChanged(); } } } }; } public void actionPerformed(ActionEvent e) { if (e.getSource() == add) { //int sel = userTable.getSelectedRow(); //if (sel < 0) // sel = 0; nameTf.setText(""); abbrTf.setText(""); if (JOptionPane.showConfirmDialog(dialog, journalEditPanel, Globals.lang("Edit journal"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { journals.add(new JournalEntry(nameTf.getText(), abbrTf.getText())); //setValueAt(nameTf.getText(), sel, 0); //setValueAt(abbrTf.getText(), sel, 1); Collections.sort(journals); fireTableDataChanged(); } } else if (e.getSource() == remove) { int[] rows = userTable.getSelectedRows(); if (rows.length > 0) { for (int i=rows.length-1; i>=0; i--) { journals.remove(rows[i]); } fireTableDataChanged(); } } } } class ExternalFileEntry { private JPanel pan; private JTextField tf; private JButton browse = new JButton(Globals.lang("Browse")), view = new JButton(Globals.lang("Preview")), clear = new JButton(GUIGlobals.getImage("delete")), download = new JButton(Globals.lang("Download")); public ExternalFileEntry() { tf = new JTextField(); setupPanel(); } public ExternalFileEntry(String filename) { tf = new JTextField(filename); setupPanel(); } private void setupPanel() { tf.setEditable(false); BrowseAction browseA = new BrowseAction(tf, false); browse.addActionListener(browseA); DownloadAction da = new DownloadAction(tf); download.addActionListener(da); DefaultFormBuilder builder = new DefaultFormBuilder (new FormLayout("fill:pref:grow, 4dlu, fill:pref, 4dlu, fill:pref, 4dlu, fill:pref, 4dlu, fill:pref", "")); builder.append(tf); builder.append(browse); builder.append(download); builder.append(view); builder.append(clear); pan = builder.getPanel(); view.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { JournalAbbreviations abbr = new JournalAbbreviations(new File(tf.getText())); JTable table = new JTable(abbr.getTableModel()); JScrollPane pane = new JScrollPane(table); JOptionPane.showMessageDialog(null, pane, Globals.lang("Journal list preview"), JOptionPane.INFORMATION_MESSAGE); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, Globals.lang("File '%0' not found", tf.getText()), Globals.lang("Error"), JOptionPane.ERROR_MESSAGE); } } }); clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { externals.remove(ExternalFileEntry.this); buildExternalsPanel(); } }); clear.setToolTipText(Globals.lang("Remove")); } public JPanel getPanel() { return pan; } public String getValue() { return tf.getText(); } } class JournalEntry implements Comparable<JournalEntry> { String name, abbreviation; public JournalEntry(String name, String abbreviation) { this.name = name; this.abbreviation = abbreviation; } public int compareTo(JournalEntry other) { return this.name.compareTo(other.name); } } }
true
true
public void storeSettings() { File f = null; if (newFile.isSelected()) { if (newNameTf.getText().length() > 0) { f = new File(newNameTf.getText()); }// else { // return; // Nothing to do. //} } else f = new File(personalFile.getText()); if (f != null) { FileWriter fw = null; try { fw = new FileWriter(f, false); for (Iterator<JournalEntry> i=tableModel.getJournals().iterator(); i.hasNext();) { JournalEntry entry = i.next(); fw.write(entry.name); fw.write(" = "); fw.write(entry.abbreviation); fw.write(Globals.NEWLINE); } } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } String filename = f.getPath(); if (filename.equals("")) filename = null; Globals.prefs.put("personalJournalList", filename); } // Store the list of external files set up: ArrayList<String> extFiles = new ArrayList<String>(); for (Iterator<ExternalFileEntry> i=externals.iterator(); i.hasNext();) { ExternalFileEntry efe = i.next(); if (!efe.getValue().equals("")) { extFiles.add(efe.getValue()); } } if (extFiles.size() == 0) Globals.prefs.put("externalJournalLists", ""); else { String[] list = extFiles.toArray(new String[extFiles.size()]); Globals.prefs.putStringArray("externalJournalLists", list); } Globals.initializeJournalNames(); // Update the autocompleter for the "journal" field in all base panels, // so added journal names are available: for (int i=0; i<frame.baseCount(); i++) { frame.baseAt(i).addJournalListToAutoCompleter(); } } class DownloadAction extends AbstractAction { JTextField comp; public DownloadAction(JTextField tc) { super(Globals.lang("Download")); comp = tc; } public void actionPerformed(ActionEvent e) { String chosen = null; chosen = JOptionPane.showInputDialog(Globals.lang("Choose the URL to download. The default value points to a list provided by the JabRef developers."), "http://jabref.sf.net/journals/journal_abbreviations_general.txt"); if (chosen == null) return; File toFile; try { URL url = new URL(chosen); String toName = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")), null, JFileChooser.SAVE_DIALOG, false); if (toName == null) return; else toFile = new File(toName); URLDownload ud = new URLDownload(comp, url, toFile); ud.download(); comp.setText(toFile.getPath()); } catch (MalformedURLException ex) { ex.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (IOException ex2) { ex2.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } class BrowseAction extends AbstractAction { JTextField comp; boolean dir; public BrowseAction(JTextField tc, boolean dir) { super(Globals.lang("Browse")); this.dir = dir; comp = tc; } public void actionPerformed(ActionEvent e) { String chosen = null; if (dir) chosen = FileDialogs.getNewDir(frame, new File(comp.getText()), Globals.NONE, JFileChooser.OPEN_DIALOG, false); else chosen = FileDialogs.getNewFile(frame, new File(comp.getText()), Globals.NONE, JFileChooser.OPEN_DIALOG, false); if (chosen != null) { File newFile = new File(chosen); comp.setText(newFile.getPath()); } } } class AbbreviationsTableModel extends AbstractTableModel implements ActionListener { String[] names = new String[] {Globals.lang("Journal name"), Globals.lang("Abbreviation")}; ArrayList<JournalEntry> journals = null; public AbbreviationsTableModel() { } public void setJournals(Map<String, String> journals) { this.journals = new ArrayList<JournalEntry>(); for (Map.Entry<String, String> entry : journals.entrySet()){ this.journals.add(new JournalEntry(entry.getKey(), entry.getValue())); } fireTableDataChanged(); } public ArrayList<JournalEntry> getJournals() { return journals; } public int getColumnCount() { return 2; } public int getRowCount() { return journals.size(); } public Object getValueAt(int row, int col) { if (col == 0) return journals.get(row).name; else return journals.get(row).abbreviation; } public void setValueAt(Object object, int row, int col) { JournalEntry entry = journals.get(row); if (col == 0) entry.name = (String)object; else entry.abbreviation = (String)object; } public String getColumnName(int i) { return names[i]; } public boolean isCellEditable(int i, int i1) { return false; } public MouseListener getMouseListener() { return new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { JTable table = (JTable)e.getSource(); int row = table.rowAtPoint(e.getPoint()); nameTf.setText((String)getValueAt(row,0)); abbrTf.setText((String)getValueAt(row,1)); if (JOptionPane.showConfirmDialog(dialog, journalEditPanel, Globals.lang("Edit journal"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { setValueAt(nameTf.getText(), row, 0); setValueAt(abbrTf.getText(), row, 1); Collections.sort(journals); fireTableDataChanged(); } } } }; } public void actionPerformed(ActionEvent e) { if (e.getSource() == add) { //int sel = userTable.getSelectedRow(); //if (sel < 0) // sel = 0; nameTf.setText(""); abbrTf.setText(""); if (JOptionPane.showConfirmDialog(dialog, journalEditPanel, Globals.lang("Edit journal"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { journals.add(new JournalEntry(nameTf.getText(), abbrTf.getText())); //setValueAt(nameTf.getText(), sel, 0); //setValueAt(abbrTf.getText(), sel, 1); Collections.sort(journals); fireTableDataChanged(); } } else if (e.getSource() == remove) { int[] rows = userTable.getSelectedRows(); if (rows.length > 0) { for (int i=rows.length-1; i>=0; i--) { journals.remove(rows[i]); } fireTableDataChanged(); } } } } class ExternalFileEntry { private JPanel pan; private JTextField tf; private JButton browse = new JButton(Globals.lang("Browse")), view = new JButton(Globals.lang("Preview")), clear = new JButton(GUIGlobals.getImage("delete")), download = new JButton(Globals.lang("Download")); public ExternalFileEntry() { tf = new JTextField(); setupPanel(); } public ExternalFileEntry(String filename) { tf = new JTextField(filename); setupPanel(); } private void setupPanel() { tf.setEditable(false); BrowseAction browseA = new BrowseAction(tf, false); browse.addActionListener(browseA); DownloadAction da = new DownloadAction(tf); download.addActionListener(da); DefaultFormBuilder builder = new DefaultFormBuilder (new FormLayout("fill:pref:grow, 4dlu, fill:pref, 4dlu, fill:pref, 4dlu, fill:pref, 4dlu, fill:pref", "")); builder.append(tf); builder.append(browse); builder.append(download); builder.append(view); builder.append(clear); pan = builder.getPanel(); view.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { JournalAbbreviations abbr = new JournalAbbreviations(new File(tf.getText())); JTable table = new JTable(abbr.getTableModel()); JScrollPane pane = new JScrollPane(table); JOptionPane.showMessageDialog(null, pane, Globals.lang("Journal list preview"), JOptionPane.INFORMATION_MESSAGE); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, Globals.lang("File '%0' not found", tf.getText()), Globals.lang("Error"), JOptionPane.ERROR_MESSAGE); } } }); clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { externals.remove(ExternalFileEntry.this); buildExternalsPanel(); } }); clear.setToolTipText(Globals.lang("Remove")); } public JPanel getPanel() { return pan; } public String getValue() { return tf.getText(); } } class JournalEntry implements Comparable<JournalEntry> { String name, abbreviation; public JournalEntry(String name, String abbreviation) { this.name = name; this.abbreviation = abbreviation; } public int compareTo(JournalEntry other) { return this.name.compareTo(other.name); } } }
public void storeSettings() { File f = null; if (newFile.isSelected()) { if (newNameTf.getText().length() > 0) { f = new File(newNameTf.getText()); }// else { // return; // Nothing to do. //} } else f = new File(personalFile.getText()); if (f != null) { FileWriter fw = null; try { fw = new FileWriter(f, false); for (Iterator<JournalEntry> i=tableModel.getJournals().iterator(); i.hasNext();) { JournalEntry entry = i.next(); fw.write(entry.name); fw.write(" = "); fw.write(entry.abbreviation); fw.write(Globals.NEWLINE); } } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } String filename = f.getPath(); if (filename.equals("")) filename = null; Globals.prefs.put("personalJournalList", filename); } // Store the list of external files set up: ArrayList<String> extFiles = new ArrayList<String>(); for (Iterator<ExternalFileEntry> i=externals.iterator(); i.hasNext();) { ExternalFileEntry efe = i.next(); if (!efe.getValue().equals("")) { extFiles.add(efe.getValue()); } } if (extFiles.size() == 0) Globals.prefs.put("externalJournalLists", ""); else { String[] list = extFiles.toArray(new String[extFiles.size()]); Globals.prefs.putStringArray("externalJournalLists", list); } Globals.initializeJournalNames(); // Update the autocompleter for the "journal" field in all base panels, // so added journal names are available: for (int i=0; i<frame.baseCount(); i++) { frame.baseAt(i).addJournalListToAutoCompleter(); } } class DownloadAction extends AbstractAction { JTextField comp; public DownloadAction(JTextField tc) { super(Globals.lang("Download")); comp = tc; } public void actionPerformed(ActionEvent e) { String chosen = null; chosen = JOptionPane.showInputDialog(Globals.lang("Choose the URL to download. The default value points to a list provided by the JabRef developers."), "http://jabref.sf.net/journals/journal_abbreviations_general.txt"); if (chosen == null) return; File toFile; try { URL url = new URL(chosen); String toName = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")), null, JFileChooser.SAVE_DIALOG, false); if (toName == null) return; else toFile = new File(toName); URLDownload ud = new URLDownload(comp, url, toFile); ud.download(); comp.setText(toFile.getPath()); } catch (Exception ex) { JOptionPane.showMessageDialog(null, Globals.lang("Error downloading file '%0'", chosen), Globals.lang("Download failed"), JOptionPane.ERROR_MESSAGE); } } } class BrowseAction extends AbstractAction { JTextField comp; boolean dir; public BrowseAction(JTextField tc, boolean dir) { super(Globals.lang("Browse")); this.dir = dir; comp = tc; } public void actionPerformed(ActionEvent e) { String chosen = null; if (dir) chosen = FileDialogs.getNewDir(frame, new File(comp.getText()), Globals.NONE, JFileChooser.OPEN_DIALOG, false); else chosen = FileDialogs.getNewFile(frame, new File(comp.getText()), Globals.NONE, JFileChooser.OPEN_DIALOG, false); if (chosen != null) { File newFile = new File(chosen); comp.setText(newFile.getPath()); } } } class AbbreviationsTableModel extends AbstractTableModel implements ActionListener { String[] names = new String[] {Globals.lang("Journal name"), Globals.lang("Abbreviation")}; ArrayList<JournalEntry> journals = null; public AbbreviationsTableModel() { } public void setJournals(Map<String, String> journals) { this.journals = new ArrayList<JournalEntry>(); for (Map.Entry<String, String> entry : journals.entrySet()){ this.journals.add(new JournalEntry(entry.getKey(), entry.getValue())); } fireTableDataChanged(); } public ArrayList<JournalEntry> getJournals() { return journals; } public int getColumnCount() { return 2; } public int getRowCount() { return journals.size(); } public Object getValueAt(int row, int col) { if (col == 0) return journals.get(row).name; else return journals.get(row).abbreviation; } public void setValueAt(Object object, int row, int col) { JournalEntry entry = journals.get(row); if (col == 0) entry.name = (String)object; else entry.abbreviation = (String)object; } public String getColumnName(int i) { return names[i]; } public boolean isCellEditable(int i, int i1) { return false; } public MouseListener getMouseListener() { return new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { JTable table = (JTable)e.getSource(); int row = table.rowAtPoint(e.getPoint()); nameTf.setText((String)getValueAt(row,0)); abbrTf.setText((String)getValueAt(row,1)); if (JOptionPane.showConfirmDialog(dialog, journalEditPanel, Globals.lang("Edit journal"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { setValueAt(nameTf.getText(), row, 0); setValueAt(abbrTf.getText(), row, 1); Collections.sort(journals); fireTableDataChanged(); } } } }; } public void actionPerformed(ActionEvent e) { if (e.getSource() == add) { //int sel = userTable.getSelectedRow(); //if (sel < 0) // sel = 0; nameTf.setText(""); abbrTf.setText(""); if (JOptionPane.showConfirmDialog(dialog, journalEditPanel, Globals.lang("Edit journal"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { journals.add(new JournalEntry(nameTf.getText(), abbrTf.getText())); //setValueAt(nameTf.getText(), sel, 0); //setValueAt(abbrTf.getText(), sel, 1); Collections.sort(journals); fireTableDataChanged(); } } else if (e.getSource() == remove) { int[] rows = userTable.getSelectedRows(); if (rows.length > 0) { for (int i=rows.length-1; i>=0; i--) { journals.remove(rows[i]); } fireTableDataChanged(); } } } } class ExternalFileEntry { private JPanel pan; private JTextField tf; private JButton browse = new JButton(Globals.lang("Browse")), view = new JButton(Globals.lang("Preview")), clear = new JButton(GUIGlobals.getImage("delete")), download = new JButton(Globals.lang("Download")); public ExternalFileEntry() { tf = new JTextField(); setupPanel(); } public ExternalFileEntry(String filename) { tf = new JTextField(filename); setupPanel(); } private void setupPanel() { tf.setEditable(false); BrowseAction browseA = new BrowseAction(tf, false); browse.addActionListener(browseA); DownloadAction da = new DownloadAction(tf); download.addActionListener(da); DefaultFormBuilder builder = new DefaultFormBuilder (new FormLayout("fill:pref:grow, 4dlu, fill:pref, 4dlu, fill:pref, 4dlu, fill:pref, 4dlu, fill:pref", "")); builder.append(tf); builder.append(browse); builder.append(download); builder.append(view); builder.append(clear); pan = builder.getPanel(); view.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { JournalAbbreviations abbr = new JournalAbbreviations(new File(tf.getText())); JTable table = new JTable(abbr.getTableModel()); JScrollPane pane = new JScrollPane(table); JOptionPane.showMessageDialog(null, pane, Globals.lang("Journal list preview"), JOptionPane.INFORMATION_MESSAGE); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, Globals.lang("File '%0' not found", tf.getText()), Globals.lang("Error"), JOptionPane.ERROR_MESSAGE); } } }); clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { externals.remove(ExternalFileEntry.this); buildExternalsPanel(); } }); clear.setToolTipText(Globals.lang("Remove")); } public JPanel getPanel() { return pan; } public String getValue() { return tf.getText(); } } class JournalEntry implements Comparable<JournalEntry> { String name, abbreviation; public JournalEntry(String name, String abbreviation) { this.name = name; this.abbreviation = abbreviation; } public int compareTo(JournalEntry other) { return this.name.compareTo(other.name); } } }
diff --git a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/ESBExampleTest.java b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/ESBExampleTest.java index d9fab4a65..14459daf8 100644 --- a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/ESBExampleTest.java +++ b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/ESBExampleTest.java @@ -1,54 +1,57 @@ package org.jboss.tools.esb.ui.bot.tests.examples; import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu; import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem; import org.jboss.tools.ui.bot.ext.SWTTestExt; import org.jboss.tools.ui.bot.ext.helper.ContextMenuHelper; import org.jboss.tools.ui.bot.ext.types.IDELabel; public class ESBExampleTest extends SWTTestExt{ protected void fixLibrary(String project, String lib) { SWTBotTree tree = projectExplorer.show().bot().tree(); SWTBotTreeItem proj = tree.select(project).getTreeItem(project); boolean fixed=false; + boolean found=false; for (SWTBotTreeItem item : proj.getItems()) { if (item.getText().startsWith(lib)) { + found = true; ContextMenuHelper.prepareTreeItemForContextMenu(tree, item); new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.PROPERTIES, false)).click(); SWTBotShell shell = bot.activeShell(); shell.bot().table().select(configuredState.getServer().name); open.finish(shell.bot(),IDELabel.Button.OK); fixed=true; break; } } - if (!fixed) { + if (!fixed && found) { + log.error("Libray starting with '"+lib+"' in project '"+project+"' was not fixed."); bot.sleep(Long.MAX_VALUE); } } /** * gets label in project examples tree derived by version of soa we currently run * @return */ protected String getRunningSoaVersionTreeLabel() { String ret = "ESB for SOA-P "; if (configuredState.getServer().version.equals("5.0")) { ret+="5.0"; } if (configuredState.getServer().version.equals("5.1")) { ret+="5.0"; } else if (configuredState.getServer().version.equals("4.3")) { ret+="4.3"; if (jbt.isJBDSRun()) { return "ESB"; } } else { return null; } return ret; } }
false
true
protected void fixLibrary(String project, String lib) { SWTBotTree tree = projectExplorer.show().bot().tree(); SWTBotTreeItem proj = tree.select(project).getTreeItem(project); boolean fixed=false; for (SWTBotTreeItem item : proj.getItems()) { if (item.getText().startsWith(lib)) { ContextMenuHelper.prepareTreeItemForContextMenu(tree, item); new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.PROPERTIES, false)).click(); SWTBotShell shell = bot.activeShell(); shell.bot().table().select(configuredState.getServer().name); open.finish(shell.bot(),IDELabel.Button.OK); fixed=true; break; } } if (!fixed) { bot.sleep(Long.MAX_VALUE); } }
protected void fixLibrary(String project, String lib) { SWTBotTree tree = projectExplorer.show().bot().tree(); SWTBotTreeItem proj = tree.select(project).getTreeItem(project); boolean fixed=false; boolean found=false; for (SWTBotTreeItem item : proj.getItems()) { if (item.getText().startsWith(lib)) { found = true; ContextMenuHelper.prepareTreeItemForContextMenu(tree, item); new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.PROPERTIES, false)).click(); SWTBotShell shell = bot.activeShell(); shell.bot().table().select(configuredState.getServer().name); open.finish(shell.bot(),IDELabel.Button.OK); fixed=true; break; } } if (!fixed && found) { log.error("Libray starting with '"+lib+"' in project '"+project+"' was not fixed."); bot.sleep(Long.MAX_VALUE); } }
diff --git a/src/org/biojava/bio/program/sax/BlastSAXParser.java b/src/org/biojava/bio/program/sax/BlastSAXParser.java index 08324b0c8..36560cc6d 100755 --- a/src/org/biojava/bio/program/sax/BlastSAXParser.java +++ b/src/org/biojava/bio/program/sax/BlastSAXParser.java @@ -1,715 +1,715 @@ /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.bio.program.sax; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * A SAX-like parser for dealing with native NCBI-Blast,Wu-Blastoutput, * and HMMER output (a single dataset). That is this class allows * native BLAST-like format files to be processed as if they were in * an XML format i.e. it sends messages to a user-written XML Handler. * * This class has package-level visibility, and is used * by generic BlastLikeSAXParser objects. * * Some functionality is delegated to Part objects within the class * whose implementations are selected on-the-fly according * the the program/version that produced the output. * SummaryLineHelperIF * * NB Support for HMMER is currently only partial and likely to change * without notice as more functionality is added. * * Copyright 2000 Cambridge Antibody Technology Group plc. * * * This code released to the biojava project, May 2000 * under the LGPL license. * * @author Simon Brocklehurst (CAT) * @author Tim Dilks (CAT) * @author Colin Hardman (CAT) * @author Stuart Johnston (CAT) * @author Mathieu Wiepert (Mayo Foundation) * @author Keith James (Sanger Institute) * @author Mark Schreiber (NITD) * @version 0.2 * * @see BlastLikeSAXParser */ final class BlastSAXParser extends AbstractNativeAppSAXParser { private BufferedReader oContents; private AttributesImpl oAtts = new AttributesImpl(); private QName oAttQName = new QName(this); private ArrayList oBuffer = new ArrayList(); private char[] aoChars; private char[] aoLineSeparator; private String[] aoKeys; private String[] aoArrayType = new String[1]; private HashMap oMap = new HashMap(); private int iVer; private BlastLikeVersionSupport oVersion; private HitSectionSAXParser oHits; private SummaryLineHelperIF oSummaryLineHelper; private String oQueryId; private String oDatabaseId; private static final int STARTUP = 0; private static final int IN_TRAILER = 1; private static final int AT_END = 2; private static final int IN_HEADER = 3; private static final int IN_SUMMARY = 4; private static final int FINISHED_HITS = 5; private boolean tDoneSummary = false; /** * Creates a new <code>BlastSAXParser</code> instance. * @param poNamespacePrefix the namespace prefix to use * @param poVersion a <code>BlastLikeVersionSupport</code> value. * @exception SAXException if an error occurs */ BlastSAXParser(BlastLikeVersionSupport poVersion, String poNamespacePrefix) throws SAXException { oVersion = poVersion; this.setNamespacePrefix(poNamespacePrefix); this.addPrefixMapping("biojava","http://www.biojava.org"); oHits = new HitSectionSAXParser(oVersion,this.getNamespacePrefix()); this.changeState(STARTUP); aoLineSeparator = System.getProperty("line.separator").toCharArray(); //Beginnings of using a Builder type pattern to create //parser from part objects. Only for done //Summary sections at present according to program type //at present. Significant benefit would be //for detail, allowing choice of part object optimised //for speed of processing etc. this.choosePartImplementations(); } /** * Parse the blast data and emit SAX events. * @param poContents The <CODE>BufferedReader</CODE> that will read the BLAST * output * @param poLine The first line of the BLAST record * @throws org.xml.sax.SAXException If the input is malformed * @return The last line of the BLAST data */ public String parse(BufferedReader poContents, String poLine) throws SAXException { String oLine = null; oQueryId = ""; oDatabaseId = ""; oContents = poContents; //First deal with first line which must be the start of //a new Blast output //For a brand new collection, check for the start of a //new BlastDataSet //look for characteristic of start of dataset if (oVersion.isStartOfDataSet(poLine)) { //just figure out whether it's a new DataSet //or not. i The onNewBlastDatSet method //takes care of the rest... this.onNewBlastDataSet(poLine); } else { throw new SAXException("unexpected poLine parameter, expecting start of BLAST like record"); //return poLine; } //now parse stream... try { oLine = oContents.readLine(); while ((oLine != null) && (!checkNewBlastLikeDataSet(oLine))) { //System.out.println(oLine); //interpret line and send messages accordingly this.interpret(oLine); oLine = oContents.readLine(); } // end while } catch (java.io.IOException x) { System.out.println(x.getMessage()); System.out.println("File read interrupted"); } // end try/catch //Now close open elements... if (iState == IN_TRAILER) { this.emitRawOutput(oBuffer); this.endElement(new QName(this,this.prefix("Trailer"))); this.changeState(AT_END); } this.endElement(new QName(this,this.prefix("BlastLikeDataSet"))); return oLine; } /** * Deal with line according to state parser is in. * * @param poLine A line of Blast output */ private void interpret(String poLine) throws SAXException { if (iState == IN_HEADER) { //accumulate header information //things that can end header section //start of summmary section //start of detail section //start of trailer when there are no hits if (poLine.startsWith("Query=")) { StringTokenizer st = new StringTokenizer(poLine); // Skip the first token st.nextToken(); if (st.hasMoreTokens()) oQueryId = st.nextToken(); } if (poLine.startsWith("Database:")) { int i = poLine.indexOf(":"); oDatabaseId = poLine.substring(i + 1); while(true){ try { poLine = oContents.readLine(); - if (poLine.startsWith("Searching")) { + if (poLine.startsWith("Searching") || poLine.startsWith("Sequences")) { break; } else if (poLine.startsWith("Results of")) { // in PSI-blast is this line... System.err.println("this looks like a PSI-blast file, this is currently not supported, yet!"); break; } else { oDatabaseId = oDatabaseId.concat(poLine); } } catch(java.io.IOException x){ System.err.println(x.getMessage()); System.err.println("File read interrupted"); } } } if ((poLine.startsWith("Sequences producing significant alignments")) || (poLine.startsWith("Sequences producing High-scoring Segment Pairs")) || (poLine.startsWith(" ***** No hits found ******")) || (poLine.startsWith("-------- "))) { this.emitRawOutput(oBuffer); this.emitHeaderIds(); oAtts.clear(); this.endElement(new QName(this,this.prefix("Header"))); if (poLine.startsWith(" ***** No hits found ******")) { oAtts.clear(); this.startElement(new QName(this,this.prefix("Trailer")), (Attributes) oAtts); this.changeState(IN_TRAILER); oBuffer.clear(); return; } //change state this.changeState(IN_SUMMARY); oAtts.clear(); this.startElement(new QName(this,this.prefix("Summary")), (Attributes)oAtts); //eat a blank line if there is one... // this.interpret(oLine); //read next line try { poLine = oContents.readLine(); } catch (java.io.IOException x) { System.err.println(x.getMessage()); System.err.println("File read interrupted"); } // end try/catch if (poLine.trim().equals("")) { //System.out.println("BLANK LINE"); } else { //recursively interpret it... this.interpret(poLine); } return; } //end check start of summary //Currently doesn't handle output that starts //with a detail section i.e. no summary. //This is a BUG/FEATURE. oBuffer.add(poLine); } //end if inHeader state //Deal with summary state if (iState == IN_SUMMARY) { //check to see if end of summary //has been reached... //(signal is a blank line for NCBIBlast and Wu-Blast, //(signal is either a blank line or //Signal is \\End of List for GCG // HMMR has a longer summary section to include the // domain summary and the check for a blank line // will prematurely end the summary section so // skip this check for HMMR int iProgram = oVersion.getProgram(); if (iProgram == BlastLikeVersionSupport.HMMER) { if (poLine.trim().equals("")) { return; // skip } //HMMER-specific if (poLine.startsWith("Parsed for domains:")) { //signifies domain summary info // System.err.println( "Last-->" + oAfterHmmr + "<--" ); return; } } else if ((poLine.trim().equals("")) || (poLine.trim().startsWith("[no more scores")) || (poLine.trim().startsWith("\\")) ) { //Can't change state, because we still want to //check for start of detail... //Forgive non-standard white-space //between end of summary and start of detail if (!tDoneSummary) { tDoneSummary = true; this.endElement(new QName(this,this.prefix("Summary"))); } return; //return before attempting to parse Summary Line } if (poLine.startsWith(">")) { //signifies start of detail section this.hitsSectionReached(poLine); return; } //need to check that we've end of summary //'cos could be spurious data between end of //summary and start of detail e.g. multi-line WARNINGs //at end of Summary section in Wu-Blast. if (!tDoneSummary) { this.parseSummaryLine(poLine); } return; } //State set to this when parsing of Hits finished if (iState == FINISHED_HITS) { //check end of detail section this.endElement(new QName(this,this.prefix("Detail"))); oAtts.clear(); this.startElement(new QName(this,this.prefix("Trailer")), (Attributes)oAtts); //change state to Trailer and initialse Buffer this.changeState(IN_TRAILER); oBuffer.clear(); return; } //end if finishedHists if (iState == IN_TRAILER) { oBuffer.add(poLine); } } /** * This method is called when a line indicating that * that a new BlastLikeDataSet has been reached. * * NB This class deals NCBI-BLAST WU-BLAST and HMMER: * * o flavours of NCBI Blast (e.g. blastn, blastp etc) * o flavours of WU Blast (e.g. blastn, blastp etc) * * When this method is called, the line will look something line: * * BLASTN 2.0.11 [Jan-20-2000] for NCBI Blast * * The above would be parsed to program ncbi-blastn, and version number * 2.0.11 * * @param poLine - */ private void onNewBlastDataSet(String poLine) throws SAXException { if (!oVersion.isSupported()) { throw (new SAXException( "Program " + oVersion.getProgramString() + " Version " + oVersion.getVersionString() + " is not supported by the biojava blast-like parsing framework")); } oAtts.clear(); oAttQName.setQName("program"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",oVersion.getProgramString()); oAttQName.setQName("version"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",oVersion.getVersionString()); this.startElement(new QName(this,this.prefix("BlastLikeDataSet")), (Attributes)oAtts); //change state to reflect the fact we're in the Header iState = IN_HEADER; oBuffer.clear(); oAtts.clear(); this.startElement(new QName(this,this.prefix("Header")), (Attributes)oAtts); } /** * Describe constructor here. * * @param oArrayList - */ private void emitRawOutput(ArrayList poList) throws SAXException { oAtts.clear(); oAttQName.setQName("xml:space"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "NMTOKEN","preserve"); this.startElement(new QName (this,this.prefix("RawOutput")), (Attributes)oAtts); //Cycle through ArrayList and send character array data to //XML ContentHandler. int iTmpListSize = poList.size(); for (int i = 0; i < iTmpListSize; i++) { //System.out.println("RAW:" + (String)poList.get(i)); aoChars = ((String)poList.get(i)).toCharArray(); this.characters(aoLineSeparator,0,1); this.characters(aoChars,0,aoChars.length); } this.endElement(new QName(this,this.prefix("RawOutput"))); } /** * Parses a summary line. Actually parsing functionality * is delegated to static method of a reusable Helper Class. * * For NCBI Blast, a summary line looks something like: * * U00431 Mus musculus HMG-1 mRNA, complete cds. 353 7e-95 * * UO0431 is typically a database accession code * Mus musculs.. is a description of the hit (this is optional) * * 353 is a bit score * * 7e-95 is an E Value * */ private void parseSummaryLine(String poLine) throws SAXException { //Also remember in header add query attribute and database type? //Should split this out into different implementations //according to program and version oSummaryLineHelper.parse(poLine,oMap,oVersion); //Eat a line for GCG, which has two lines for a summary. //The first line becomes the beginning of the description if (iVer == BlastLikeVersionSupport.GCG_BLASTN) { try { poLine = oContents.readLine(); oSummaryLineHelper.parse(poLine,oMap,oVersion); } catch (IOException x) { System.out.println(x.getMessage()); System.out.println("GCG File read interrupted"); } // end try/catch } /* Note have to do this check a hmmer can have empty summary * sections and oMap.keySet().toArray will return an array * of size 1 with a null first element if the map is empty. */ if ( oMap.size() == 0 ) { return; } aoKeys = (String[])(oMap.keySet().toArray(aoArrayType)); oAtts.clear(); //output contents of Map as either elements or //attribute lists //two passes first get HitsSummary element started for (int i = 0; i < aoKeys.length; i++) { if ((aoKeys[i].equals("hitId")) || (aoKeys[i].equals("hitDescription")) ) { //do nothing } else { oAttQName.setQName(aoKeys[i]); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",(String)oMap.get(aoKeys[i])); } } this.startElement(new QName(this,this.prefix("HitSummary")), (Attributes)oAtts); for (int i = 0; i < aoKeys.length; i++) { if (aoKeys[i].equals("hitId")) { oAtts.clear(); oAttQName.setQName("id"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA",(String)oMap.get(aoKeys[i])); oAttQName.setQName("metaData"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA","none"); this.startElement(new QName(this,this.prefix("HitId")), (Attributes)oAtts); this.endElement(new QName(this,this.prefix("HitId"))); } else if (aoKeys[i].equals("hitDescription")) { oAtts.clear(); this.startElement(new QName(this,this.prefix("HitDescription")), (Attributes)oAtts); aoChars = ((String)oMap.get(aoKeys[i])).toCharArray(); this.characters(aoChars,0,aoChars.length); this.endElement(new QName(this,this.prefix("HitDescription"))); } //System.out.print(aoKeys[i] + ": "); //System.out.println(oMap.get(aoKeys[i])); } this.endElement(new QName(this,this.prefix("HitSummary"))); oMap.clear(); } /** * Fires the QueryId and DatabaseId events. */ private void emitHeaderIds() throws SAXException { // Set attributes for QueryId element oAtts.clear(); oAttQName.setQName("id"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA", oQueryId); oAttQName.setQName("metaData"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA", "none"); // Fire the QueryId element this.startElement(new QName(this,this.prefix("QueryId")), (Attributes) oAtts); this.endElement(new QName(this,this.prefix("QueryId"))); // Set attributes for DatabaseId element oAtts.clear(); oAttQName.setQName("id"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA", oDatabaseId); oAttQName.setQName("metaData"); oAtts.addAttribute(oAttQName.getURI(), oAttQName.getLocalName(), oAttQName.getQName(), "CDATA", "none"); // Fire the DatabaseId element this.startElement(new QName(this,this.prefix("DatabaseId")), (Attributes) oAtts); this.endElement(new QName(this,this.prefix("DatabaseId"))); } /** * From the specified line, hand over * parsing of stream to a helperclass * * @param poLine - * @exception SAXException thrown if * @exception thrown if */ private void hitsSectionReached(String poLine) throws SAXException { //Parse Contents stream up to end of Hits oHits.setContentHandler(oHandler); //this returns when end of hits section reached... oAtts.clear(); this.startElement(new QName(this,this.prefix("Detail")), (Attributes)oAtts); int iProgram = oVersion.getProgram(); if ((iProgram == BlastLikeVersionSupport.NCBI_BLASTN) || (iProgram == BlastLikeVersionSupport.NCBI_BLASTX) || (iProgram == BlastLikeVersionSupport.NCBI_BLASTP) || (iProgram == BlastLikeVersionSupport.NCBI_TBLASTN) || (iProgram == BlastLikeVersionSupport.NCBI_TBLASTX)) { oHits.parse(oContents,poLine,"Database:"); } if ((iProgram == BlastLikeVersionSupport.WU_BLASTN) || (iProgram == BlastLikeVersionSupport.WU_BLASTX) || (iProgram == BlastLikeVersionSupport.WU_BLASTP) || (iProgram == BlastLikeVersionSupport.WU_TBLASTN) || (iProgram == BlastLikeVersionSupport.WU_TBLASTX)) { oHits.parse(oContents,poLine,"Parameters:"); } //Same as NCBI, left here for organization I suppose if (iProgram == BlastLikeVersionSupport.GCG_BLASTN) { oHits.parse(oContents,poLine,"Database:"); } this.changeState(FINISHED_HITS); } /** * Checks to see if a line of Blast like output * represents the start of a new BlastLike data set. * Current supports: * o ncbi-blast all variants * o wu-blast all variants * * @param poLine A String representation of the line * @return boolean true if it is a new dataset, false if not. */ private boolean checkNewBlastLikeDataSet(String poLine) { if ((poLine.startsWith("BLAST")) || (poLine.startsWith("TBLAST"))) { return true; } else { return false; } } /** * Choose particular implementations of Part objects * that comprise the aggregate object according * to version/type of program * * @param nil - */ private void choosePartImplementations() throws SAXException { iVer = oVersion.getProgram(); if ((iVer == BlastLikeVersionSupport.NCBI_BLASTN) || (iVer == BlastLikeVersionSupport.NCBI_BLASTX) || (iVer == BlastLikeVersionSupport.NCBI_BLASTP) || (iVer == BlastLikeVersionSupport.NCBI_TBLASTN) || (iVer == BlastLikeVersionSupport.NCBI_TBLASTX)) { oSummaryLineHelper = (SummaryLineHelperIF) new NcbiBlastSummaryLineHelper(); return; } if ((iVer == BlastLikeVersionSupport.WU_BLASTN) || (iVer == BlastLikeVersionSupport.WU_BLASTX) || (iVer == BlastLikeVersionSupport.WU_BLASTP) || (iVer == BlastLikeVersionSupport.WU_TBLASTN) || (iVer == BlastLikeVersionSupport.WU_TBLASTX)) { oSummaryLineHelper = (SummaryLineHelperIF) new WuBlastSummaryLineHelper(); return; } if (iVer == BlastLikeVersionSupport.HMMER) { oSummaryLineHelper = (SummaryLineHelperIF) new HmmerSummaryLineHelper(); return; } if (iVer == BlastLikeVersionSupport.GCG_BLASTN) { oSummaryLineHelper = (SummaryLineHelperIF) new GCGBlastSummaryLineHelper(); return; } //If get to here, no implementation available //Exception to help SAX parser writers track down //problems writing software to support the framework throw (new SAXException("Could not choose a suitable implementation of the ". concat("SummaryLineHelperIF for program "). concat(oVersion.getProgramString()). concat(" version "). concat(oVersion.getVersionString()))); } }
true
true
private void interpret(String poLine) throws SAXException { if (iState == IN_HEADER) { //accumulate header information //things that can end header section //start of summmary section //start of detail section //start of trailer when there are no hits if (poLine.startsWith("Query=")) { StringTokenizer st = new StringTokenizer(poLine); // Skip the first token st.nextToken(); if (st.hasMoreTokens()) oQueryId = st.nextToken(); } if (poLine.startsWith("Database:")) { int i = poLine.indexOf(":"); oDatabaseId = poLine.substring(i + 1); while(true){ try { poLine = oContents.readLine(); if (poLine.startsWith("Searching")) { break; } else if (poLine.startsWith("Results of")) { // in PSI-blast is this line... System.err.println("this looks like a PSI-blast file, this is currently not supported, yet!"); break; } else { oDatabaseId = oDatabaseId.concat(poLine); } } catch(java.io.IOException x){ System.err.println(x.getMessage()); System.err.println("File read interrupted"); } } } if ((poLine.startsWith("Sequences producing significant alignments")) || (poLine.startsWith("Sequences producing High-scoring Segment Pairs")) || (poLine.startsWith(" ***** No hits found ******")) || (poLine.startsWith("-------- "))) { this.emitRawOutput(oBuffer); this.emitHeaderIds(); oAtts.clear(); this.endElement(new QName(this,this.prefix("Header"))); if (poLine.startsWith(" ***** No hits found ******")) { oAtts.clear(); this.startElement(new QName(this,this.prefix("Trailer")), (Attributes) oAtts); this.changeState(IN_TRAILER); oBuffer.clear(); return; } //change state this.changeState(IN_SUMMARY); oAtts.clear(); this.startElement(new QName(this,this.prefix("Summary")), (Attributes)oAtts); //eat a blank line if there is one... // this.interpret(oLine); //read next line try { poLine = oContents.readLine(); } catch (java.io.IOException x) { System.err.println(x.getMessage()); System.err.println("File read interrupted"); } // end try/catch if (poLine.trim().equals("")) { //System.out.println("BLANK LINE"); } else { //recursively interpret it... this.interpret(poLine); } return; } //end check start of summary //Currently doesn't handle output that starts //with a detail section i.e. no summary. //This is a BUG/FEATURE. oBuffer.add(poLine); } //end if inHeader state //Deal with summary state if (iState == IN_SUMMARY) { //check to see if end of summary //has been reached... //(signal is a blank line for NCBIBlast and Wu-Blast, //(signal is either a blank line or //Signal is \\End of List for GCG // HMMR has a longer summary section to include the // domain summary and the check for a blank line // will prematurely end the summary section so // skip this check for HMMR int iProgram = oVersion.getProgram(); if (iProgram == BlastLikeVersionSupport.HMMER) { if (poLine.trim().equals("")) { return; // skip } //HMMER-specific if (poLine.startsWith("Parsed for domains:")) { //signifies domain summary info // System.err.println( "Last-->" + oAfterHmmr + "<--" ); return; } } else if ((poLine.trim().equals("")) || (poLine.trim().startsWith("[no more scores")) || (poLine.trim().startsWith("\\")) ) { //Can't change state, because we still want to //check for start of detail... //Forgive non-standard white-space //between end of summary and start of detail if (!tDoneSummary) { tDoneSummary = true; this.endElement(new QName(this,this.prefix("Summary"))); } return; //return before attempting to parse Summary Line } if (poLine.startsWith(">")) { //signifies start of detail section this.hitsSectionReached(poLine); return; } //need to check that we've end of summary //'cos could be spurious data between end of //summary and start of detail e.g. multi-line WARNINGs //at end of Summary section in Wu-Blast. if (!tDoneSummary) { this.parseSummaryLine(poLine); } return; } //State set to this when parsing of Hits finished if (iState == FINISHED_HITS) { //check end of detail section this.endElement(new QName(this,this.prefix("Detail"))); oAtts.clear(); this.startElement(new QName(this,this.prefix("Trailer")), (Attributes)oAtts); //change state to Trailer and initialse Buffer this.changeState(IN_TRAILER); oBuffer.clear(); return; } //end if finishedHists if (iState == IN_TRAILER) { oBuffer.add(poLine); } }
private void interpret(String poLine) throws SAXException { if (iState == IN_HEADER) { //accumulate header information //things that can end header section //start of summmary section //start of detail section //start of trailer when there are no hits if (poLine.startsWith("Query=")) { StringTokenizer st = new StringTokenizer(poLine); // Skip the first token st.nextToken(); if (st.hasMoreTokens()) oQueryId = st.nextToken(); } if (poLine.startsWith("Database:")) { int i = poLine.indexOf(":"); oDatabaseId = poLine.substring(i + 1); while(true){ try { poLine = oContents.readLine(); if (poLine.startsWith("Searching") || poLine.startsWith("Sequences")) { break; } else if (poLine.startsWith("Results of")) { // in PSI-blast is this line... System.err.println("this looks like a PSI-blast file, this is currently not supported, yet!"); break; } else { oDatabaseId = oDatabaseId.concat(poLine); } } catch(java.io.IOException x){ System.err.println(x.getMessage()); System.err.println("File read interrupted"); } } } if ((poLine.startsWith("Sequences producing significant alignments")) || (poLine.startsWith("Sequences producing High-scoring Segment Pairs")) || (poLine.startsWith(" ***** No hits found ******")) || (poLine.startsWith("-------- "))) { this.emitRawOutput(oBuffer); this.emitHeaderIds(); oAtts.clear(); this.endElement(new QName(this,this.prefix("Header"))); if (poLine.startsWith(" ***** No hits found ******")) { oAtts.clear(); this.startElement(new QName(this,this.prefix("Trailer")), (Attributes) oAtts); this.changeState(IN_TRAILER); oBuffer.clear(); return; } //change state this.changeState(IN_SUMMARY); oAtts.clear(); this.startElement(new QName(this,this.prefix("Summary")), (Attributes)oAtts); //eat a blank line if there is one... // this.interpret(oLine); //read next line try { poLine = oContents.readLine(); } catch (java.io.IOException x) { System.err.println(x.getMessage()); System.err.println("File read interrupted"); } // end try/catch if (poLine.trim().equals("")) { //System.out.println("BLANK LINE"); } else { //recursively interpret it... this.interpret(poLine); } return; } //end check start of summary //Currently doesn't handle output that starts //with a detail section i.e. no summary. //This is a BUG/FEATURE. oBuffer.add(poLine); } //end if inHeader state //Deal with summary state if (iState == IN_SUMMARY) { //check to see if end of summary //has been reached... //(signal is a blank line for NCBIBlast and Wu-Blast, //(signal is either a blank line or //Signal is \\End of List for GCG // HMMR has a longer summary section to include the // domain summary and the check for a blank line // will prematurely end the summary section so // skip this check for HMMR int iProgram = oVersion.getProgram(); if (iProgram == BlastLikeVersionSupport.HMMER) { if (poLine.trim().equals("")) { return; // skip } //HMMER-specific if (poLine.startsWith("Parsed for domains:")) { //signifies domain summary info // System.err.println( "Last-->" + oAfterHmmr + "<--" ); return; } } else if ((poLine.trim().equals("")) || (poLine.trim().startsWith("[no more scores")) || (poLine.trim().startsWith("\\")) ) { //Can't change state, because we still want to //check for start of detail... //Forgive non-standard white-space //between end of summary and start of detail if (!tDoneSummary) { tDoneSummary = true; this.endElement(new QName(this,this.prefix("Summary"))); } return; //return before attempting to parse Summary Line } if (poLine.startsWith(">")) { //signifies start of detail section this.hitsSectionReached(poLine); return; } //need to check that we've end of summary //'cos could be spurious data between end of //summary and start of detail e.g. multi-line WARNINGs //at end of Summary section in Wu-Blast. if (!tDoneSummary) { this.parseSummaryLine(poLine); } return; } //State set to this when parsing of Hits finished if (iState == FINISHED_HITS) { //check end of detail section this.endElement(new QName(this,this.prefix("Detail"))); oAtts.clear(); this.startElement(new QName(this,this.prefix("Trailer")), (Attributes)oAtts); //change state to Trailer and initialse Buffer this.changeState(IN_TRAILER); oBuffer.clear(); return; } //end if finishedHists if (iState == IN_TRAILER) { oBuffer.add(poLine); } }
diff --git a/project/src/de/topobyte/livecg/algorithms/polygon/shortestpath/ShortestPathPainter.java b/project/src/de/topobyte/livecg/algorithms/polygon/shortestpath/ShortestPathPainter.java index 3fa678e..ec8fc3d 100644 --- a/project/src/de/topobyte/livecg/algorithms/polygon/shortestpath/ShortestPathPainter.java +++ b/project/src/de/topobyte/livecg/algorithms/polygon/shortestpath/ShortestPathPainter.java @@ -1,367 +1,371 @@ /* This file is part of LiveCG. * * Copyright (C) 2013 Sebastian Kuerten * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.topobyte.livecg.algorithms.polygon.shortestpath; import java.awt.Shape; import java.util.Collection; import java.util.List; import java.util.Set; import de.topobyte.livecg.algorithms.polygon.monotonepieces.Diagonal; import de.topobyte.livecg.core.config.LiveConfig; import de.topobyte.livecg.core.geometry.geom.Chain; import de.topobyte.livecg.core.geometry.geom.Coordinate; import de.topobyte.livecg.core.geometry.geom.Node; import de.topobyte.livecg.core.geometry.geom.Polygon; import de.topobyte.livecg.core.geometry.geom.PolygonHelper; import de.topobyte.livecg.core.painting.BasicAlgorithmPainter; import de.topobyte.livecg.core.painting.Color; import de.topobyte.livecg.core.painting.Painter; import de.topobyte.livecg.util.MouseOver; import de.topobyte.livecg.util.ShapeUtil; import de.topobyte.livecg.util.circular.IntRing; import de.topobyte.livecg.util.graph.Edge; public class ShortestPathPainter extends BasicAlgorithmPainter { private String q(String property) { return "algorithm.polygon.shortestpath.colors." + property; } private Color COLOR_BG = LiveConfig.getColor(q("background")); private Color COLOR_POLYGON_BG = LiveConfig.getColor(q("polygon")); private Color COLOR_TRIANGLE_SLEEVE = LiveConfig.getColor(q("sleeve")); private Color COLOR_TRIANGLE_SLEEVE_DONE = LiveConfig .getColor(q("sleeve.done")); private Color COLOR_POLYGON_EDGES = LiveConfig.getColor(q("boundary")); private Color COLOR_DIAGONALS_NONSLEEVE = LiveConfig .getColor(q("diagonals")); private Color COLOR_DIAGONALS_SLEEVE = LiveConfig.getColor(q("diagonals")); private Color COLOR_DUAL_GRAPH = LiveConfig.getColor(q("dualgraph")); private Color COLOR_NODE_START = LiveConfig.getColor(q("node.start")); private Color COLOR_NODE_TARGET = LiveConfig.getColor(q("node.target")); private Color COLOR_NODE_START_OUTLINE = LiveConfig .getColor(q("node.start.outline")); private Color COLOR_NODE_TARGET_OUTLINE = LiveConfig .getColor(q("node.target.outline")); private Color COLOR_APEX = LiveConfig.getColor(q("path.apex")); private Color COLOR_LEFT_TOP = LiveConfig.getColor(q("path.left.top")); private Color COLOR_RIGHT_TOP = LiveConfig.getColor(q("path.right.top")); private Color COLOR_COMMON_PATH = LiveConfig.getColor(q("path.common")); private Color COLOR_LEFT_PATH = LiveConfig.getColor(q("path.left")); private Color COLOR_RIGHT_PATH = LiveConfig.getColor(q("path.right")); private Color COLOR_NODE_IDS = LiveConfig.getColor(q("node.ids")); private double SIZE_FIRST_NODE = LiveConfig.getNumber(q("node.size.first")); private double SIZE_APEX = LiveConfig.getNumber(q("node.size.apex")); private double SIZE_FINAL_NODES = LiveConfig .getNumber(q("node.size.final")); private double SIZE_INTERMEDIATE_NODES = LiveConfig .getNumber(q("node.size.intermediate")); private double SIZE_ST_RADIUS = LiveConfig .getNumber(q("size.start_target.radius")); private double SIZE_ST_WIDTH = LiveConfig .getNumber(q("size.start_target.width")); private double LINE_WIDTH_POLYGON = LiveConfig .getNumber(q("width.polygon")); private double LINE_WIDTH_DIAGONALS = LiveConfig .getNumber(q("width.diagonals")); private double LINE_WIDTH_DUAL_GRAPH = LiveConfig .getNumber(q("width.dual_graph")); private double LINE_WIDTH_PATH = LiveConfig.getNumber(q("width.path")); private ShortestPathAlgorithm algorithm; private Config config; // Variables for handling start / target dragging private Coordinate dragStart = null; private Coordinate dragTarget = null; private MouseOver mouseOverStart = MouseOver.NONE; private MouseOver mouseOverTarget = MouseOver.NONE; public ShortestPathPainter(ShortestPathAlgorithm algorithm, Config config, Painter painter) { super(painter); this.algorithm = algorithm; this.config = config; } public void setDragStart(Coordinate dragStart) { this.dragStart = dragStart; } public void setDragTarget(Coordinate dragTarget) { this.dragTarget = dragTarget; } public boolean setStartMouseOver(MouseOver over) { if (mouseOverStart == over) { return false; } mouseOverStart = over; return true; } public boolean setTargetMouseOver(MouseOver over) { if (mouseOverTarget == over) { return false; } mouseOverTarget = over; return true; } public void paint() { painter.setColor(COLOR_BG); painter.fillRect(0, 0, getWidth(), getHeight()); painter.setColor(COLOR_POLYGON_BG); painter.fillPolygon(algorithm.getPolygon()); List<Polygon> triangles = algorithm.getSleeve().getPolygons(); for (int i = 0; i < triangles.size(); i++) { if (i < algorithm.getStatus()) { painter.setColor(COLOR_TRIANGLE_SLEEVE_DONE); } else { painter.setColor(COLOR_TRIANGLE_SLEEVE); } Polygon triangle = triangles.get(i); painter.fillPolygon(triangle); } painter.setStrokeWidth(LINE_WIDTH_POLYGON); painter.setColor(COLOR_POLYGON_EDGES); Chain shell = algorithm.getPolygon().getShell(); IntRing ring = new IntRing(shell.getNumberOfNodes()); for (int i = 0; i < shell.getNumberOfNodes(); i++) { int j = ring.next().value(); Coordinate c1 = shell.getCoordinate(i); Coordinate c2 = shell.getCoordinate(j); painter.drawLine((int) Math.round(c1.getX()), (int) Math.round(c1.getY()), (int) Math.round(c2.getX()), (int) Math.round(c2.getY())); } painter.setStrokeWidth(LINE_WIDTH_DIAGONALS); for (Diagonal diagonal : algorithm.getTriangulationDiagonals()) { painter.setColor(COLOR_DIAGONALS_NONSLEEVE); if (algorithm.getSleeve().getDiagonals().contains(diagonal)) { painter.setColor(COLOR_DIAGONALS_SLEEVE); } Coordinate c1 = diagonal.getA().getCoordinate(); Coordinate c2 = diagonal.getB().getCoordinate(); painter.drawLine((int) Math.round(c1.getX()), (int) Math.round(c1.getY()), (int) Math.round(c2.getX()), (int) Math.round(c2.getY())); } painter.setStrokeWidth(LINE_WIDTH_DUAL_GRAPH); if (config.isDrawDualGraph()) { painter.setColor(COLOR_DUAL_GRAPH); Collection<Polygon> nodes = algorithm.getGraph().getNodes(); for (Polygon p : nodes) { Coordinate cp = PolygonHelper.center(p); Set<Edge<Polygon, Diagonal>> edges = algorithm.getGraph() .getEdgesOut(p); for (Edge<Polygon, Diagonal> edge : edges) { Polygon q = edge.getTarget(); Coordinate cq = PolygonHelper.center(q); painter.drawLine((int) Math.round(cp.getX()), (int) Math.round(cp.getY()), (int) Math.round(cq.getX()), (int) Math.round(cq.getY())); } } } painter.setStrokeWidth(LINE_WIDTH_PATH); Data data = algorithm.getData(); if (data != null) { paintCommonPath(); paintPath(Side.LEFT); paintPath(Side.RIGHT); paintNodes(Side.LEFT); paintNodes(Side.RIGHT); boolean apexVisible = true; if (data.getFunnelLength(Side.LEFT) == 0 || data.getFunnelLength(Side.RIGHT) == 0) { apexVisible = false; } + if (data.getFunnelLength(Side.LEFT) == 0 + && data.getFunnelLength(Side.RIGHT) == 0) { + apexVisible = true; + } Coordinate c = data.getApex().getCoordinate(); if (apexVisible) { painter.setColor(COLOR_APEX); painter.fill(ShapeUtil.createArc(c.getX(), c.getY(), SIZE_APEX)); } } Coordinate cStart = algorithm.getNodeStart().getCoordinate(); Coordinate cTarget = algorithm.getNodeTarget().getCoordinate(); double r = SIZE_ST_RADIUS; double w = SIZE_ST_WIDTH; if (dragStart != null) { cStart = dragStart; } if (dragTarget != null) { cTarget = dragTarget; } Shape arcStart = ShapeUtil.createArc(cStart.getX(), cStart.getY(), r); Shape arcTarget = ShapeUtil .createArc(cTarget.getX(), cTarget.getY(), r); Shape arcStartIn = ShapeUtil.createArc(cStart.getX(), cStart.getY(), r - w / 2); Shape arcTargetIn = ShapeUtil.createArc(cTarget.getX(), cTarget.getY(), r - w / 2); Shape arcStartOut = ShapeUtil.createArc(cStart.getX(), cStart.getY(), r + w / 2); Shape arcTargetOut = ShapeUtil.createArc(cTarget.getX(), cTarget.getY(), r + w / 2); painter.setStrokeWidth(w); painter.setColor(COLOR_NODE_START); painter.draw(arcStart); painter.setColor(COLOR_NODE_TARGET); painter.draw(arcTarget); painter.setColor(new Color(0xaaffffff, true)); if (mouseOverStart == MouseOver.OVER) { painter.draw(arcStart); } if (mouseOverTarget == MouseOver.OVER) { painter.draw(arcTarget); } painter.setStrokeWidth(1.0); painter.setColor(COLOR_NODE_START_OUTLINE); painter.draw(arcStartOut); painter.draw(arcStartIn); painter.setColor(COLOR_NODE_TARGET_OUTLINE); painter.draw(arcTargetOut); painter.draw(arcTargetIn); painter.setStrokeWidth(2.0); painter.setColor(new Color(0xaaffffff, true)); if (mouseOverStart == MouseOver.OVER || mouseOverStart == MouseOver.ACTIVE) { painter.draw(arcStartOut); painter.draw(arcStartIn); } if (mouseOverTarget == MouseOver.OVER || mouseOverTarget == MouseOver.ACTIVE) { painter.draw(arcTargetOut); painter.draw(arcTargetIn); } if (config.isDrawNodeNumbers()) { painter.setColor(COLOR_NODE_IDS); for (int i = 0; i < shell.getNumberOfNodes(); i++) { Coordinate c = shell.getNode(i).getCoordinate(); painter.drawString(String.format("%d", i + 1), (float) c.getX() + 10, (float) c.getY()); } } } private void paintCommonPath() { Data data = algorithm.getData(); painter.setColor(COLOR_COMMON_PATH); for (int i = 0; i < data.getCommonLength() - 1; i++) { Node m = data.getCommon(i); Node n = data.getCommon(i + 1); Coordinate cm = m.getCoordinate(); Coordinate cn = n.getCoordinate(); painter.drawLine((int) Math.round(cm.getX()), (int) Math.round(cm.getY()), (int) Math.round(cn.getX()), (int) Math.round(cn.getY())); } for (int i = 0; i < data.getCommonLength() - 1; i++) { Coordinate c = data.getCommon(i).getCoordinate(); painter.fill(ShapeUtil.createArc(c.getX(), c.getY(), i == 0 ? SIZE_FIRST_NODE : SIZE_INTERMEDIATE_NODES)); } } private void paintPath(Side side) { Data data = algorithm.getData(); if (side == Side.LEFT) { painter.setColor(COLOR_LEFT_PATH); } else { painter.setColor(COLOR_RIGHT_PATH); } Node m = data.getApex(); for (int i = 0; i < data.getFunnelLength(side); i++) { Node n = data.get(side, i); Coordinate cm = m.getCoordinate(); Coordinate cn = n.getCoordinate(); painter.drawLine((int) Math.round(cm.getX()), (int) Math.round(cm.getY()), (int) Math.round(cn.getX()), (int) Math.round(cn.getY())); m = n; } } private void paintNodes(Side side) { Data data = algorithm.getData(); if (side == Side.LEFT) { painter.setColor(COLOR_LEFT_PATH); } else { painter.setColor(COLOR_RIGHT_PATH); } for (int i = 0; i < data.getFunnelLength(side); i++) { Coordinate c = data.get(side, i).getCoordinate(); painter.fill(ShapeUtil.createArc(c.getX(), c.getY(), SIZE_INTERMEDIATE_NODES)); } Node last = data.getLast(side); Coordinate c = last.getCoordinate(); if (side == Side.LEFT) { painter.setColor(COLOR_LEFT_TOP); } else { painter.setColor(COLOR_RIGHT_TOP); } painter.fill(ShapeUtil.createArc(c.getX(), c.getY(), SIZE_FINAL_NODES)); } }
true
true
public void paint() { painter.setColor(COLOR_BG); painter.fillRect(0, 0, getWidth(), getHeight()); painter.setColor(COLOR_POLYGON_BG); painter.fillPolygon(algorithm.getPolygon()); List<Polygon> triangles = algorithm.getSleeve().getPolygons(); for (int i = 0; i < triangles.size(); i++) { if (i < algorithm.getStatus()) { painter.setColor(COLOR_TRIANGLE_SLEEVE_DONE); } else { painter.setColor(COLOR_TRIANGLE_SLEEVE); } Polygon triangle = triangles.get(i); painter.fillPolygon(triangle); } painter.setStrokeWidth(LINE_WIDTH_POLYGON); painter.setColor(COLOR_POLYGON_EDGES); Chain shell = algorithm.getPolygon().getShell(); IntRing ring = new IntRing(shell.getNumberOfNodes()); for (int i = 0; i < shell.getNumberOfNodes(); i++) { int j = ring.next().value(); Coordinate c1 = shell.getCoordinate(i); Coordinate c2 = shell.getCoordinate(j); painter.drawLine((int) Math.round(c1.getX()), (int) Math.round(c1.getY()), (int) Math.round(c2.getX()), (int) Math.round(c2.getY())); } painter.setStrokeWidth(LINE_WIDTH_DIAGONALS); for (Diagonal diagonal : algorithm.getTriangulationDiagonals()) { painter.setColor(COLOR_DIAGONALS_NONSLEEVE); if (algorithm.getSleeve().getDiagonals().contains(diagonal)) { painter.setColor(COLOR_DIAGONALS_SLEEVE); } Coordinate c1 = diagonal.getA().getCoordinate(); Coordinate c2 = diagonal.getB().getCoordinate(); painter.drawLine((int) Math.round(c1.getX()), (int) Math.round(c1.getY()), (int) Math.round(c2.getX()), (int) Math.round(c2.getY())); } painter.setStrokeWidth(LINE_WIDTH_DUAL_GRAPH); if (config.isDrawDualGraph()) { painter.setColor(COLOR_DUAL_GRAPH); Collection<Polygon> nodes = algorithm.getGraph().getNodes(); for (Polygon p : nodes) { Coordinate cp = PolygonHelper.center(p); Set<Edge<Polygon, Diagonal>> edges = algorithm.getGraph() .getEdgesOut(p); for (Edge<Polygon, Diagonal> edge : edges) { Polygon q = edge.getTarget(); Coordinate cq = PolygonHelper.center(q); painter.drawLine((int) Math.round(cp.getX()), (int) Math.round(cp.getY()), (int) Math.round(cq.getX()), (int) Math.round(cq.getY())); } } } painter.setStrokeWidth(LINE_WIDTH_PATH); Data data = algorithm.getData(); if (data != null) { paintCommonPath(); paintPath(Side.LEFT); paintPath(Side.RIGHT); paintNodes(Side.LEFT); paintNodes(Side.RIGHT); boolean apexVisible = true; if (data.getFunnelLength(Side.LEFT) == 0 || data.getFunnelLength(Side.RIGHT) == 0) { apexVisible = false; } Coordinate c = data.getApex().getCoordinate(); if (apexVisible) { painter.setColor(COLOR_APEX); painter.fill(ShapeUtil.createArc(c.getX(), c.getY(), SIZE_APEX)); } } Coordinate cStart = algorithm.getNodeStart().getCoordinate(); Coordinate cTarget = algorithm.getNodeTarget().getCoordinate(); double r = SIZE_ST_RADIUS; double w = SIZE_ST_WIDTH; if (dragStart != null) { cStart = dragStart; } if (dragTarget != null) { cTarget = dragTarget; } Shape arcStart = ShapeUtil.createArc(cStart.getX(), cStart.getY(), r); Shape arcTarget = ShapeUtil .createArc(cTarget.getX(), cTarget.getY(), r); Shape arcStartIn = ShapeUtil.createArc(cStart.getX(), cStart.getY(), r - w / 2); Shape arcTargetIn = ShapeUtil.createArc(cTarget.getX(), cTarget.getY(), r - w / 2); Shape arcStartOut = ShapeUtil.createArc(cStart.getX(), cStart.getY(), r + w / 2); Shape arcTargetOut = ShapeUtil.createArc(cTarget.getX(), cTarget.getY(), r + w / 2); painter.setStrokeWidth(w); painter.setColor(COLOR_NODE_START); painter.draw(arcStart); painter.setColor(COLOR_NODE_TARGET); painter.draw(arcTarget); painter.setColor(new Color(0xaaffffff, true)); if (mouseOverStart == MouseOver.OVER) { painter.draw(arcStart); } if (mouseOverTarget == MouseOver.OVER) { painter.draw(arcTarget); } painter.setStrokeWidth(1.0); painter.setColor(COLOR_NODE_START_OUTLINE); painter.draw(arcStartOut); painter.draw(arcStartIn); painter.setColor(COLOR_NODE_TARGET_OUTLINE); painter.draw(arcTargetOut); painter.draw(arcTargetIn); painter.setStrokeWidth(2.0); painter.setColor(new Color(0xaaffffff, true)); if (mouseOverStart == MouseOver.OVER || mouseOverStart == MouseOver.ACTIVE) { painter.draw(arcStartOut); painter.draw(arcStartIn); } if (mouseOverTarget == MouseOver.OVER || mouseOverTarget == MouseOver.ACTIVE) { painter.draw(arcTargetOut); painter.draw(arcTargetIn); } if (config.isDrawNodeNumbers()) { painter.setColor(COLOR_NODE_IDS); for (int i = 0; i < shell.getNumberOfNodes(); i++) { Coordinate c = shell.getNode(i).getCoordinate(); painter.drawString(String.format("%d", i + 1), (float) c.getX() + 10, (float) c.getY()); } } }
public void paint() { painter.setColor(COLOR_BG); painter.fillRect(0, 0, getWidth(), getHeight()); painter.setColor(COLOR_POLYGON_BG); painter.fillPolygon(algorithm.getPolygon()); List<Polygon> triangles = algorithm.getSleeve().getPolygons(); for (int i = 0; i < triangles.size(); i++) { if (i < algorithm.getStatus()) { painter.setColor(COLOR_TRIANGLE_SLEEVE_DONE); } else { painter.setColor(COLOR_TRIANGLE_SLEEVE); } Polygon triangle = triangles.get(i); painter.fillPolygon(triangle); } painter.setStrokeWidth(LINE_WIDTH_POLYGON); painter.setColor(COLOR_POLYGON_EDGES); Chain shell = algorithm.getPolygon().getShell(); IntRing ring = new IntRing(shell.getNumberOfNodes()); for (int i = 0; i < shell.getNumberOfNodes(); i++) { int j = ring.next().value(); Coordinate c1 = shell.getCoordinate(i); Coordinate c2 = shell.getCoordinate(j); painter.drawLine((int) Math.round(c1.getX()), (int) Math.round(c1.getY()), (int) Math.round(c2.getX()), (int) Math.round(c2.getY())); } painter.setStrokeWidth(LINE_WIDTH_DIAGONALS); for (Diagonal diagonal : algorithm.getTriangulationDiagonals()) { painter.setColor(COLOR_DIAGONALS_NONSLEEVE); if (algorithm.getSleeve().getDiagonals().contains(diagonal)) { painter.setColor(COLOR_DIAGONALS_SLEEVE); } Coordinate c1 = diagonal.getA().getCoordinate(); Coordinate c2 = diagonal.getB().getCoordinate(); painter.drawLine((int) Math.round(c1.getX()), (int) Math.round(c1.getY()), (int) Math.round(c2.getX()), (int) Math.round(c2.getY())); } painter.setStrokeWidth(LINE_WIDTH_DUAL_GRAPH); if (config.isDrawDualGraph()) { painter.setColor(COLOR_DUAL_GRAPH); Collection<Polygon> nodes = algorithm.getGraph().getNodes(); for (Polygon p : nodes) { Coordinate cp = PolygonHelper.center(p); Set<Edge<Polygon, Diagonal>> edges = algorithm.getGraph() .getEdgesOut(p); for (Edge<Polygon, Diagonal> edge : edges) { Polygon q = edge.getTarget(); Coordinate cq = PolygonHelper.center(q); painter.drawLine((int) Math.round(cp.getX()), (int) Math.round(cp.getY()), (int) Math.round(cq.getX()), (int) Math.round(cq.getY())); } } } painter.setStrokeWidth(LINE_WIDTH_PATH); Data data = algorithm.getData(); if (data != null) { paintCommonPath(); paintPath(Side.LEFT); paintPath(Side.RIGHT); paintNodes(Side.LEFT); paintNodes(Side.RIGHT); boolean apexVisible = true; if (data.getFunnelLength(Side.LEFT) == 0 || data.getFunnelLength(Side.RIGHT) == 0) { apexVisible = false; } if (data.getFunnelLength(Side.LEFT) == 0 && data.getFunnelLength(Side.RIGHT) == 0) { apexVisible = true; } Coordinate c = data.getApex().getCoordinate(); if (apexVisible) { painter.setColor(COLOR_APEX); painter.fill(ShapeUtil.createArc(c.getX(), c.getY(), SIZE_APEX)); } } Coordinate cStart = algorithm.getNodeStart().getCoordinate(); Coordinate cTarget = algorithm.getNodeTarget().getCoordinate(); double r = SIZE_ST_RADIUS; double w = SIZE_ST_WIDTH; if (dragStart != null) { cStart = dragStart; } if (dragTarget != null) { cTarget = dragTarget; } Shape arcStart = ShapeUtil.createArc(cStart.getX(), cStart.getY(), r); Shape arcTarget = ShapeUtil .createArc(cTarget.getX(), cTarget.getY(), r); Shape arcStartIn = ShapeUtil.createArc(cStart.getX(), cStart.getY(), r - w / 2); Shape arcTargetIn = ShapeUtil.createArc(cTarget.getX(), cTarget.getY(), r - w / 2); Shape arcStartOut = ShapeUtil.createArc(cStart.getX(), cStart.getY(), r + w / 2); Shape arcTargetOut = ShapeUtil.createArc(cTarget.getX(), cTarget.getY(), r + w / 2); painter.setStrokeWidth(w); painter.setColor(COLOR_NODE_START); painter.draw(arcStart); painter.setColor(COLOR_NODE_TARGET); painter.draw(arcTarget); painter.setColor(new Color(0xaaffffff, true)); if (mouseOverStart == MouseOver.OVER) { painter.draw(arcStart); } if (mouseOverTarget == MouseOver.OVER) { painter.draw(arcTarget); } painter.setStrokeWidth(1.0); painter.setColor(COLOR_NODE_START_OUTLINE); painter.draw(arcStartOut); painter.draw(arcStartIn); painter.setColor(COLOR_NODE_TARGET_OUTLINE); painter.draw(arcTargetOut); painter.draw(arcTargetIn); painter.setStrokeWidth(2.0); painter.setColor(new Color(0xaaffffff, true)); if (mouseOverStart == MouseOver.OVER || mouseOverStart == MouseOver.ACTIVE) { painter.draw(arcStartOut); painter.draw(arcStartIn); } if (mouseOverTarget == MouseOver.OVER || mouseOverTarget == MouseOver.ACTIVE) { painter.draw(arcTargetOut); painter.draw(arcTargetIn); } if (config.isDrawNodeNumbers()) { painter.setColor(COLOR_NODE_IDS); for (int i = 0; i < shell.getNumberOfNodes(); i++) { Coordinate c = shell.getNode(i).getCoordinate(); painter.drawString(String.format("%d", i + 1), (float) c.getX() + 10, (float) c.getY()); } } }
diff --git a/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/JaxRsRestlet.java b/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/JaxRsRestlet.java index 80dea8425..983d0542c 100644 --- a/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/JaxRsRestlet.java +++ b/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/JaxRsRestlet.java @@ -1,1246 +1,1246 @@ /** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.ext.jaxrs; import static org.restlet.ext.jaxrs.internal.util.AlgorithmUtil.addPathVarsToMap; import static org.restlet.ext.jaxrs.internal.util.AlgorithmUtil.getBestMethod; import static org.restlet.ext.jaxrs.internal.util.AlgorithmUtil.getFirstByNoOfLiteralCharsNoOfCapturingGroups; import static org.restlet.ext.jaxrs.internal.util.AlgorithmUtil.removeNotSupportedHttpMethod; import static org.restlet.ext.jaxrs.internal.util.Util.copyResponseHeaders; import static org.restlet.ext.jaxrs.internal.util.Util.getMediaType; import static org.restlet.ext.jaxrs.internal.util.Util.getSupportedCharSet; import static org.restlet.ext.jaxrs.internal.util.Util.sortByConcreteness; import java.lang.annotation.Annotation; import java.lang.reflect.GenericSignatureFormatError; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response.ResponseBuilder; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.engine.Engine; import org.restlet.ext.jaxrs.internal.core.CallContext; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException; import org.restlet.ext.jaxrs.internal.exceptions.ImplementationException; import org.restlet.ext.jaxrs.internal.exceptions.MethodInvokeException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; import org.restlet.ext.jaxrs.internal.exceptions.RequestHandledException; import org.restlet.ext.jaxrs.internal.provider.BufferedReaderProvider; import org.restlet.ext.jaxrs.internal.provider.ByteArrayProvider; import org.restlet.ext.jaxrs.internal.provider.ConverterProvider; import org.restlet.ext.jaxrs.internal.provider.InputStreamProvider; import org.restlet.ext.jaxrs.internal.provider.ReaderProvider; import org.restlet.ext.jaxrs.internal.provider.SourceProvider; import org.restlet.ext.jaxrs.internal.provider.StreamingOutputProvider; import org.restlet.ext.jaxrs.internal.provider.StringProvider; import org.restlet.ext.jaxrs.internal.provider.WebAppExcMapper; import org.restlet.ext.jaxrs.internal.provider.WwwFormFormProvider; import org.restlet.ext.jaxrs.internal.provider.WwwFormMmapProvider; import org.restlet.ext.jaxrs.internal.todo.NotYetImplementedException; import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.util.ExceptionHandler; import org.restlet.ext.jaxrs.internal.util.JaxRsOutputRepresentation; import org.restlet.ext.jaxrs.internal.util.MatchingResult; import org.restlet.ext.jaxrs.internal.util.PathRegExp; import org.restlet.ext.jaxrs.internal.util.RemainingPath; import org.restlet.ext.jaxrs.internal.util.SortedMetadata; import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.ext.jaxrs.internal.util.WrappedRequestForHttpHeaders; import org.restlet.ext.jaxrs.internal.wrappers.AbstractMethodWrapper; import org.restlet.ext.jaxrs.internal.wrappers.ResourceClass; import org.restlet.ext.jaxrs.internal.wrappers.ResourceClasses; import org.restlet.ext.jaxrs.internal.wrappers.ResourceMethod; import org.restlet.ext.jaxrs.internal.wrappers.ResourceMethodOrLocator; import org.restlet.ext.jaxrs.internal.wrappers.ResourceObject; import org.restlet.ext.jaxrs.internal.wrappers.RootResourceClass; import org.restlet.ext.jaxrs.internal.wrappers.SubResourceLocator; import org.restlet.ext.jaxrs.internal.wrappers.provider.ExtensionBackwardMapping; import org.restlet.ext.jaxrs.internal.wrappers.provider.JaxRsProviders; import org.restlet.ext.jaxrs.internal.wrappers.provider.MessageBodyWriter; import org.restlet.ext.jaxrs.internal.wrappers.provider.MessageBodyWriterSubSet; import org.restlet.representation.EmptyRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.ResourceException; import org.restlet.routing.Router; import org.restlet.service.MetadataService; /** * <p> * This class choose the JAX-RS resource class and method to use for a request * and handles the result from he resource method. Typically you should * instantiate a {@link JaxRsApplication} to run JAX-RS resource classes. * </p> * * Concurrency note: instances of this class or its subclasses can be invoked by * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * * @author Stephan Koops */ public class JaxRsRestlet extends Restlet { /** * Structure to return the obtained {@link ResourceObject} and the * identified {@link ResourceMethod}. * * @author Stephan Koops */ class ResObjAndMeth { private ResourceObject resourceObject; private ResourceMethod resourceMethod; ResObjAndMeth(ResourceObject resourceObject, ResourceMethod resourceMethod) { this.resourceObject = resourceObject; this.resourceMethod = resourceMethod; } } /** * Structure to return the obtained {@link ResourceObject} and the remaining * path after identifying the object. * * @author Stephan Koops */ class ResObjAndRemPath { private ResourceObject resourceObject; private RemainingPath u; ResObjAndRemPath(ResourceObject resourceObject, RemainingPath u) { this.resourceObject = resourceObject; this.u = u; } } /** * Structure to return an instance of the identified * {@link RootResourceClass}, the matched URI path and the remaining path * after identifying the root resource class. * * @author Stephan Koops */ class RroRemPathAndMatchedPath { private ResourceObject rootResObj; private RemainingPath u; private String matchedUriPath; RroRemPathAndMatchedPath(ResourceObject rootResObj, RemainingPath u, String matchedUriPath) { this.rootResObj = rootResObj; this.u = u; this.matchedUriPath = matchedUriPath; } } static { javax.ws.rs.ext.RuntimeDelegate .setInstance(new org.restlet.ext.jaxrs.internal.spi.RuntimeDelegateImpl()); } private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0]; private final JaxRsProviders providers; private final ResourceClasses resourceClasses; /** * Contains and handles the exceptions occurring while in resource objects * and providers, and also for the other cases where the runtime environment * should throw {@link WebApplicationException}. */ private final ExceptionHandler excHandler; /** * Contains the thread localized {@link CallContext}s. */ private final ThreadLocalizedContext tlContext = new ThreadLocalizedContext(); private volatile ObjectFactory objectFactory; /** * Creates a new JaxRsRestlet with the given Context. Only the default * providers are loaded. * * @param context * the context from the parent, see * {@link Restlet#Restlet(Context)}. * @param metadataService * the metadata service of the {@link JaxRsApplication}. * @see #JaxRsRestlet(Context, MetadataService) */ public JaxRsRestlet(Context context, MetadataService metadataService) { super(context); final ExtensionBackwardMapping extensionBackwardMapping = new ExtensionBackwardMapping( metadataService); this.excHandler = new ExceptionHandler(getLogger()); this.providers = new JaxRsProviders(this.objectFactory, this.tlContext, extensionBackwardMapping, getLogger()); this.resourceClasses = new ResourceClasses(this.tlContext, this.providers, extensionBackwardMapping, getLogger()); this.loadDefaultProviders(); } /** * Will use the given JAX-RS root resource class.<br> * If the given class is not a valid root resource class, a warning is * logged and false is returned. * * @param jaxRsClass * A JAX-RS root resource class or provider class to add. If the * root resource class is already available in this JaxRsRestlet, * it is ignored for later calls of this method. * @return true if the class is added or was already included, or false if * the given class is not a valid class (a warning was logged). * @throws IllegalArgumentException * if the root resource class is null. */ public boolean addClass(Class<?> jaxRsClass) throws IllegalArgumentException { if (jaxRsClass == null) throw new IllegalArgumentException( "The JAX-RS class to add must not be null"); boolean used = false; if (Util.isRootResourceClass(jaxRsClass)) { used = resourceClasses.addRootClass(jaxRsClass); } if (Util.isProvider(jaxRsClass)) { if (providers.addClass(jaxRsClass)) used = true; } // @see Application#getClasses() // @see Application#getSingletons() if (!used) { getLogger() .warning( "The class " + jaxRsClass + " is neither a provider nor a root resource class"); } return used; } /** * Adds the provider object as default provider to this JaxRsRestlet. * * @param jaxRsProvider * The provider object or class name. * @return true, if the provider is ok and added, otherwise false. * @throws IllegalArgumentException * if null was given * @see {@link javax.ws.rs.ext.Provider} */ private boolean addDefaultProvider(Object jaxRsProvider) { try { return addSingleton(jaxRsProvider, true); } catch (GenericSignatureFormatError e) { getLogger().warning( "Unable to add default provider class : " + jaxRsProvider); } return false; } /** * Adds the provider object to this JaxRsRestlet. * * @param jaxRsProviderOrRootresourceObject * the JAX-RS provider or root resource object * @return true, if the provider is ok and added, otherwise false. * @throws IllegalArgumentException * if null was given * @see javax.ws.rs.ext.Provider */ public boolean addSingleton(Object jaxRsProviderOrRootresourceObject) throws IllegalArgumentException { return addSingleton(jaxRsProviderOrRootresourceObject, false); } /** * Adds the provider object to this JaxRsRestlet. * * @param jaxRsProvider * The provider object or class name. * @param defaultProvider * @return true, if the provider is ok and added, otherwise false. * @throws IllegalArgumentException * if null was given * @see {@link javax.ws.rs.ext.Provider} */ private boolean addSingleton(Object jaxRsProvider, boolean defaultProvider) throws IllegalArgumentException { if (jaxRsProvider instanceof String) { try { jaxRsProvider = Engine.loadClass((String) jaxRsProvider) .newInstance(); } catch (ClassNotFoundException e) { getLogger().fine( "Unable to load provider class : " + jaxRsProvider); jaxRsProvider = null; } catch (InstantiationException e) { getLogger().fine( "Unable to instantiate provider : " + jaxRsProvider); jaxRsProvider = null; } catch (IllegalAccessException e) { getLogger().fine( "Unable to access to provider : " + jaxRsProvider); jaxRsProvider = null; } catch (NoClassDefFoundError e) { getLogger().fine( "Unable to load provider class : " + jaxRsProvider); jaxRsProvider = null; } } else if (jaxRsProvider == null) throw new IllegalArgumentException( "The JAX-RS object to add must not be null"); else if (jaxRsProvider instanceof Class<?>) throw new IllegalArgumentException( "The JAX-RS object to add must not be a java.lang.Class"); boolean used = false; if (jaxRsProvider != null) { if (defaultProvider || Util.isProvider(jaxRsProvider.getClass())) { used = providers.addSingleton(jaxRsProvider, defaultProvider); } if (Util.isRootResourceClass(jaxRsProvider.getClass())) { throw new NotYetImplementedException( "only providers are allowed as singletons for now"); // used = ... } if (!used) { final String warning = ("The class " + jaxRsProvider.getClass() + " is neither a provider nor a root resource class"); getLogger().warning(warning); } } return used; } // now methods for the daily work /** * Sets the Restlet that is called, if no (root) resource class or method * could be found. * * @param notMatchedRestlet * the Restlet to call, if no (root) resource class or method * could be found. * @see #setNoRootResClHandler(Restlet) * @see #setNoResourceClHandler(Restlet) * @see #setNoResMethodHandler(Restlet) * @see Router#attachDefault(Restlet) */ public void attachDefault(Restlet notMatchedRestlet) { this.setNoRootResClHandler(notMatchedRestlet); this.setNoResourceClHandler(notMatchedRestlet); this.setNoResMethodHandler(notMatchedRestlet); } /** * Converts the given entity - returned by the resource method - to a * Restlet {@link Representation}. * * @param entity * the entity to convert. * @param resourceMethod * The resource method created the entity. Could be null, if an * exception is handled, e.g. a {@link WebApplicationException}. * @param jaxRsResponseMediaType * The MediaType of the JAX-RS {@link javax.ws.rs.core.Response}. * May be null. * @param jaxRsRespHeaders * The headers added to the {@link javax.ws.rs.core.Response} by * the {@link ResponseBuilder}. * @param accMediaTypes * the accepted media type from the current call context, or the * returned of the JAX-RS {@link javax.ws.rs.core.Response}. * @return the corresponding Restlet Representation. Returns * <code>null</code> only if null was given. * @throws WebApplicationException * @see AbstractMethodWrapper.EntityGetter */ private Representation convertToRepresentation(Object entity, ResourceMethod resourceMethod, MediaType jaxRsResponseMediaType, MultivaluedMap<String, Object> jaxRsRespHeaders, SortedMetadata<MediaType> accMediaTypes) throws ImplementationException { if (entity instanceof Representation) { Representation repr = (Representation) entity; // ensures that a supported character set is set repr.setCharacterSet(getSupportedCharSet(repr.getCharacterSet())); if (jaxRsResponseMediaType != null) { repr.setMediaType(Converter .getMediaTypeWithoutParams(jaxRsResponseMediaType)); } return repr; } Type genericReturnType; Class<? extends Object> entityClass; Annotation[] methodAnnotations; if (resourceMethod != null) // is default methodAnnotations = resourceMethod.getAnnotations(); else methodAnnotations = EMPTY_ANNOTATION_ARRAY; if (entity instanceof GenericEntity) { GenericEntity<?> genericEntity = (GenericEntity<?>) entity; genericReturnType = genericEntity.getType(); entityClass = genericEntity.getRawType(); entity = genericEntity.getEntity(); } else { entityClass = (entity != null) ? entity.getClass() : null; if (resourceMethod != null) // is default genericReturnType = resourceMethod.getGenericReturnType(); else genericReturnType = null; if (genericReturnType instanceof Class && ((Class<?>) genericReturnType) .isAssignableFrom(javax.ws.rs.core.Response.class)) { genericReturnType = entityClass; } } final MultivaluedMap<String, Object> httpResponseHeaders = new WrappedRequestForHttpHeaders( tlContext.get().getResponse(), jaxRsRespHeaders); final Representation repr; if (entity != null) { final MediaType respMediaType = determineMediaType( jaxRsResponseMediaType, resourceMethod, entityClass, genericReturnType); final MessageBodyWriterSubSet mbws; mbws = providers.writerSubSet(entityClass, genericReturnType); if (mbws.isEmpty()) throw excHandler.noMessageBodyWriter(entityClass, genericReturnType, methodAnnotations, null, null); final MessageBodyWriter mbw = mbws.getBestWriter(respMediaType, methodAnnotations, accMediaTypes); if (mbw == null) throw excHandler.noMessageBodyWriter(entityClass, genericReturnType, methodAnnotations, respMediaType, accMediaTypes); repr = new JaxRsOutputRepresentation<Object>(entity, genericReturnType, respMediaType, methodAnnotations, mbw, httpResponseHeaders); } else { // entity == null repr = new EmptyRepresentation(); repr.setMediaType(determineMediaType(jaxRsResponseMediaType, resourceMethod, entityClass, genericReturnType)); } repr.setCharacterSet(getSupportedCharSet(httpResponseHeaders)); return repr; } /** * @param o * @param subResourceLocator * @param callContext * @return * @throws WebApplicationException * @throws RequestHandledException */ private ResourceObject createSubResource(ResourceObject o, SubResourceLocator subResourceLocator, CallContext callContext) throws WebApplicationException, RequestHandledException { try { o = subResourceLocator.createSubResource(o, resourceClasses, getLogger()); } catch (WebApplicationException e) { throw e; } catch (RuntimeException e) { throw excHandler.runtimeExecption(e, subResourceLocator, callContext, "Could not create new instance of resource class"); } catch (MissingAnnotationException e) { throw excHandler.missingAnnotation(e, callContext, "Could not create new instance of resource class"); } catch (InstantiateException e) { throw excHandler.instantiateExecption(e, callContext, "Could not create new instance of resource class"); } catch (InvocationTargetException e) { throw handleInvocationTargetExc(e); } catch (ConvertRepresentationException e) { throw excHandler.convertRepresentationExc(e); } return o; } /** * Determines the MediaType for a response, see JAX-RS-Spec (2008-08-27), * section 3.8 "Determining the MediaType of Responses" * * @param jaxRsResponseMediaType * @param resourceMethod * The ResourceMethod that created the entity. * @param entityClass * needed, if neither the resource method nor the resource class * is annotated with &#64;{@link Produces}. * @param genericReturnType * needed, if neither the resource method nor the resource class * is annotated with &#64;{@link Produces}. * @param methodAnnotation * needed, if neither the resource method nor the resource class * is annotated with &#64;{@link Produces}. * @param mbws * The {@link MessageBodyWriter}s, that support the class of the * returned entity object as generic type of the * {@link MessageBodyWriter}. * @return the determined {@link MediaType}. If no method is given, * "text/plain" is returned. * @throws WebApplicationException */ private MediaType determineMediaType(MediaType jaxRsResponseMediaType, ResourceMethod resourceMethod, Class<?> entityClass, Type genericReturnType) throws WebApplicationException { // In many cases it is not possible to statically determine the media // type of a response. The following algorithm is used to determine the // response media type, Mselected, at run time: // 1. If the method returns an instance of Response whose metadata // includes the response media type (Mspecified) then set Mselected = // Mspecified, finish. if (jaxRsResponseMediaType != null) return jaxRsResponseMediaType; if (resourceMethod == null) return MediaType.TEXT_PLAIN; CallContext callContext = tlContext.get(); // 2. Gather the set of producible media types P : // // (a) If the method is annotated with @Produces, set P = {V (method)} // where V (t) represents the values of @Produces on the specified // target t. // // (b) Else if the class is annotated with @Produces, set P = {V // (class)}. Collection<MediaType> p = resourceMethod.getProducedMimes(); - // (c) Else set P = {V (writers)} where ‘writers’ is the set of + // (c) Else set P = {V (writers)} where 'writers' is the set of // MessageBodyWriter that support the class of the returned entity // object. if (p.isEmpty()) { p = providers.writerSubSet(entityClass, genericReturnType) .getAllProducibleMediaTypes(); } - // 3. If P = {}, set P = {‘*/*’} + // 3. If P = {}, set P = {'*/*'} if (p.isEmpty()) return MediaType.ALL; else p = sortByConcreteness(p); - // 4. Obtain the acceptable media types A. If A = {}, set A = {‘*/*’} + // 4. Obtain the acceptable media types A. If A = {}, set A = {'*/*'} SortedMetadata<MediaType> a = callContext.getAccMediaTypes(); if (a.isEmpty()) a = SortedMetadata.getMediaTypeAll(); // 5. Set M = {}. For each member of A,a: // (a) For each member of P,p: // (a.1) If a is compatible with p, add S(a,p) to M, where the function // S returns the most specific media type of the pair with the q-value // of a. List<MediaType> m = new ArrayList<MediaType>(); // First test equality (ideal) for (MediaType a1 : a) { for (MediaType p1 : p) { if (a1.equals(p1)) { m.add(a1); } } } // Otherwise test inclusion (good) for (MediaType a1 : a) { for (MediaType p1 : p) { if (a1.includes(p1)) { m.add(MediaType.getMostSpecific(a1, p1)); } } } // Finally test compatibility (most flexible) for (MediaType a1 : a) { for (MediaType p1 : p) { if (a1.isCompatible(p1)) { m.add(MediaType.getMostSpecific(a1, p1)); } } } // 6. If M = {} then generate a WebApplicationException with a not // acceptable response (HTTP 406 status) and no entity. The exception // MUST be processed as described in section 3.3.4. Finish. if (m.isEmpty()) excHandler.notAcceptableWhileDetermineMediaType(); // 7. Sort M in descending order, with a primary key of specificity (n/m // > n/* > */*) and secondary key of q-value. // TODO // 8. For each member of M,m: // (a) If m is a concrete type, set Mselected = m, finish. for (MediaType mediaType : m) if (mediaType.isConcrete()) return mediaType; - // 9. If M contains ‘*/*’ or ‘application/*’, set Mselected = - // ‘application/octet-stream’, finish. + // 9. If M contains '*/*' or 'application/*', set Mselected = + // 'application/octet-stream', finish. if (m.contains(MediaType.ALL) || m.contains(MediaType.APPLICATION_ALL)) return MediaType.APPLICATION_OCTET_STREAM; // 10. Generate a WebApplicationException with a not acceptable response // (HTTP 406 status) and no entity. The exception MUST be processed as // described in section 3.3.4. Finish. throw excHandler.notAcceptableWhileDetermineMediaType(); } /** * Returns the Restlet that is called, if no resource method class could be * found. * * @return the Restlet that is called, if no resource method class could be * found. * @see #setNoResMethodHandler(Restlet) */ public Restlet getNoResMethodHandler() { return excHandler.getNoResMethodHandler(); } /** * Returns the Restlet that is called, if no resource class could be found. * * @return the Restlet that is called, if no resource class could be found. */ public Restlet getNoResourceClHandler() { return excHandler.getNoResourceClHandler(); } /** * Returns the Restlet that is called, if no root resource class could be * found. You could remove a given Restlet by set null here.<br> * If no Restlet is given here, status 404 will be returned. * * @return the Restlet that is called, if no root resource class could be * found. * @see #setNoRootResClHandler(Restlet) */ public Restlet getNoRootResClHandler() { return excHandler.getNoRootResClHandler(); } /** * Returns the ObjectFactory for root resource class and provider * instantiation, if given. * * @return the ObjectFactory for root resource class and provider * instantiation, if given. */ public ObjectFactory getObjectFactory() { return this.objectFactory; } /** * Returns an unmodifiable set with the attached root resource classes. * * @return an unmodifiable set with the attached root resource classes. */ public Set<Class<?>> getRootResourceClasses() { Set<Class<?>> rrcs = new HashSet<Class<?>>(); for (RootResourceClass rootResourceClass : this.resourceClasses.roots()) rrcs.add(rootResourceClass.getJaxRsClass()); return Collections.unmodifiableSet(rrcs); } /** * Returns a Collection with all root uris attached to this JaxRsRestlet. * * @return a Collection with all root uris attached to this JaxRsRestlet. */ public Collection<String> getRootUris() { List<String> uris = new ArrayList<String>(); for (RootResourceClass rrc : this.resourceClasses.roots()) uris.add(rrc.getPathRegExp().getPathTemplateEnc()); return Collections.unmodifiableCollection(uris); } /** * Handles a call by looking for the resource metod to call, call it and * return the result. * * @param request * The {@link Request} to handle. * @param response * The {@link Response} to update. */ @Override public void handle(Request request, Response response) { super.handle(request, response); ResourceObject resourceObject = null; final Reference baseRef = request.getResourceRef().getBaseRef(); request.setRootRef(new Reference(baseRef.toString())); // NICE Normally, the "rootRef" property is set by the VirtualHost, each // time a request is handled by one of its routes. // Email from Jerome, 2008-09-22 try { CallContext callContext; callContext = new CallContext(request, response); tlContext.set(callContext); try { ResObjAndMeth resObjAndMeth; resObjAndMeth = requestMatching(); callContext.setReadOnly(); ResourceMethod resourceMethod = resObjAndMeth.resourceMethod; resourceObject = resObjAndMeth.resourceObject; Object result = invokeMethod(resourceMethod, resourceObject); handleResult(result, resourceMethod); } catch (WebApplicationException e) { // the message of the Exception is not used in the // WebApplicationException jaxRsRespToRestletResp(this.providers.convert(e), null); return; } } catch (RequestHandledException e) { // Exception was handled and data were set into the Response. } finally { Representation entity = request.getEntity(); if (entity != null) entity.release(); } } /** * Handles the given Exception, catched by an invoke of a resource method or * a creation if a sub resource object. * * @param ite * @param methodName * @throws RequestHandledException * throws this message to exit the method and indicate, that the * request was handled. * @throws RequestHandledException */ private RequestHandledException handleInvocationTargetExc( InvocationTargetException ite) throws RequestHandledException { Throwable cause = ite.getCause(); if (cause instanceof ResourceException) { // avoid mapping to a JAX-RS Response and back to a Restlet Response Status status = ((ResourceException) cause).getStatus(); Response restletResponse = tlContext.get().getResponse(); restletResponse.setStatus(status); } else { javax.ws.rs.core.Response jaxRsResp = this.providers.convert(cause); jaxRsRespToRestletResp(jaxRsResp, null); } throw new RequestHandledException(); } /** * Sets the result of the resource method invocation into the response. Do * necessary converting. * * @param result * the object returned by the resource method * @param resourceMethod * the resource method; it is needed for the conversion. Could be * null, if an exception is handled, e.g. a * {@link WebApplicationException}. */ private void handleResult(Object result, ResourceMethod resourceMethod) { Response restletResponse = tlContext.get().getResponse(); if (result instanceof javax.ws.rs.core.Response) { jaxRsRespToRestletResp((javax.ws.rs.core.Response) result, resourceMethod); } else if (result instanceof ResponseBuilder) { String warning = "the method " + resourceMethod + " returnef a ResponseBuilder. You should " + "call responseBuilder.build() in the resource method"; getLogger().warning(warning); jaxRsRespToRestletResp(((ResponseBuilder) result).build(), resourceMethod); } else { if (result == null) // no representation restletResponse.setStatus(Status.SUCCESS_NO_CONTENT); else restletResponse.setStatus(Status.SUCCESS_OK); SortedMetadata<MediaType> accMediaTypes; accMediaTypes = tlContext.get().getAccMediaTypes(); restletResponse.setEntity(convertToRepresentation(result, resourceMethod, null, null, accMediaTypes)); } } /** * Identifies the method that will handle the request, see JAX-RS-Spec * (2008-04-16), section 3.7.2 "Request Matching", Part 3: Identify the * method that will handle the request:" * * @return Resource Object and Method, that handle the request. * @throws RequestHandledException * for example if the method was OPTIONS, but no special * Resource Method for OPTIONS is available. * @throws ResourceMethodNotFoundException */ private ResObjAndMeth identifyMethod(ResObjAndRemPath resObjAndRemPath, MediaType givenMediaType) throws RequestHandledException { CallContext callContext = tlContext.get(); org.restlet.data.Method httpMethod = callContext.getRequest() .getMethod(); // 3. Identify the method that will handle the request: // (a) ResourceObject resObj = resObjAndRemPath.resourceObject; RemainingPath u = resObjAndRemPath.u; // (a) 1 ResourceClass resourceClass = resObj.getResourceClass(); Collection<ResourceMethod> resourceMethods = resourceClass .getMethodsForPath(u); if (resourceMethods.isEmpty()) excHandler.resourceMethodNotFound();// NICE (resourceClass, u); // (a) 2: remove methods not support the given method boolean alsoGet = httpMethod.equals(Method.HEAD); removeNotSupportedHttpMethod(resourceMethods, httpMethod, alsoGet); if (resourceMethods.isEmpty()) { Set<Method> allowedMethods = resourceClass.getAllowedMethods(u); if (httpMethod.equals(Method.OPTIONS)) { callContext.getResponse().getAllowedMethods() .addAll(allowedMethods); throw new RequestHandledException(); } excHandler.methodNotAllowed(allowedMethods); } // (a) 3 if (givenMediaType != null) { Collection<ResourceMethod> supporting = resourceMethods; resourceMethods = new ArrayList<ResourceMethod>(); for (ResourceMethod resourceMethod : supporting) { if (resourceMethod.isGivenMediaTypeSupported(givenMediaType)) resourceMethods.add(resourceMethod); } if (resourceMethods.isEmpty()) excHandler.unsupportedMediaType(supporting); } // (a) 4 SortedMetadata<MediaType> accMediaTypes = callContext .getAccMediaTypes(); Collection<ResourceMethod> supporting = resourceMethods; resourceMethods = new ArrayList<ResourceMethod>(); for (ResourceMethod resourceMethod : supporting) { if (resourceMethod.isAcceptedMediaTypeSupported(accMediaTypes)) resourceMethods.add(resourceMethod); } if (resourceMethods.isEmpty()) { excHandler.noResourceMethodForAccMediaTypes(supporting); } // (b) and (c) ResourceMethod bestResourceMethod = getBestMethod(resourceMethods, givenMediaType, accMediaTypes, httpMethod); MatchingResult mr = bestResourceMethod.getPathRegExp().match(u); addPathVarsToMap(mr, callContext); String matchedUriPart = mr.getMatched(); if (matchedUriPart.length() > 0) { Object jaxRsResObj = resObj.getJaxRsResourceObject(); callContext.addForMatched(jaxRsResObj, matchedUriPart); } return new ResObjAndMeth(resObj, bestResourceMethod); } /** * Identifies the root resource class, see JAX-RS-Spec (2008-04-16), section * 3.7.2 "Request Matching", Part 1: "Identify the root resource class" * * @param u * the remaining path after the base ref * @return The identified root resource object, the remaining path after * identifying and the matched template parameters; see * {@link RroRemPathAndMatchedPath}. * @throws WebApplicationException * @throws RequestHandledException */ private RroRemPathAndMatchedPath identifyRootResource(RemainingPath u) throws WebApplicationException, RequestHandledException { // 1. Identify the root resource class: // (a) // c: Set<Class>: root resource classes // e: Set<RegExp> // Map<UriTemplateRegExp, Class> eAndCs = new HashMap(); Collection<RootResourceClass> eAndCs = new ArrayList<RootResourceClass>(); // (a) and (b) and (c) Filter E for (RootResourceClass rootResourceClass : this.resourceClasses.roots()) { // Map.Entry<UriTemplateRegExp, Class> eAndC = eAndCIter.next(); // UriTemplateRegExp regExp = eAndC.getKey(); // Class clazz = eAndC.getValue(); PathRegExp rrcPathRegExp = rootResourceClass.getPathRegExp(); MatchingResult matchingResult = rrcPathRegExp.match(u); if (matchingResult == null) continue; // doesn't match if (matchingResult.getFinalCapturingGroup().isEmptyOrSlash()) eAndCs.add(rootResourceClass); else if (rootResourceClass.hasSubResourceMethodsOrLocators()) eAndCs.add(rootResourceClass); } // (d) if (eAndCs.isEmpty()) excHandler.rootResourceNotFound(); // (e) and (f) RootResourceClass tClass = getFirstByNoOfLiteralCharsNoOfCapturingGroups(eAndCs); // (f) PathRegExp rMatch = tClass.getPathRegExp(); MatchingResult matchResult = rMatch.match(u); u = matchResult.getFinalCapturingGroup(); addPathVarsToMap(matchResult, tlContext.get()); ResourceObject o = instantiateRrc(tClass); return new RroRemPathAndMatchedPath(o, u, matchResult.getMatched()); } /** * Instantiates the root resource class and handles thrown exceptions. * * @param rrc * the root resource class to instantiate * @return the instance of the root resource * @throws WebApplicationException * if a WebApplicationException was thrown while creating the * instance. * @throws RequestHandledException * If an Exception was thrown and the request is already * handeled. */ private ResourceObject instantiateRrc(RootResourceClass rrc) throws WebApplicationException, RequestHandledException { ResourceObject o; try { o = rrc.getInstance(this.objectFactory); } catch (WebApplicationException e) { throw e; } catch (RuntimeException e) { throw excHandler.runtimeExecption(e, null, tlContext.get(), "Could not create new instance of root resource class"); } catch (InstantiateException e) { throw excHandler.instantiateExecption(e, tlContext.get(), "Could not create new instance of root resource class"); } catch (InvocationTargetException e) { throw handleInvocationTargetExc(e); } return o; } /** * Invokes the (sub) resource method. Handles / converts also occuring * exceptions. * * @param resourceMethod * the (sub) resource method to invoke * @param resourceObject * the resource object to invoke the method on. * @return the object returned by the (sub) resource method. * @throws RequestHandledException * if the request is already handled * @throws WebApplicationException * if a JAX-RS class throws an WebApplicationException */ private Object invokeMethod(ResourceMethod resourceMethod, ResourceObject resourceObject) throws WebApplicationException, RequestHandledException { Object result; try { result = resourceMethod.invoke(resourceObject); } catch (WebApplicationException e) { throw e; } catch (InvocationTargetException ite) { throw handleInvocationTargetExc(ite); } catch (RuntimeException e) { throw excHandler.runtimeExecption(e, resourceMethod, tlContext.get(), "Can not invoke the resource method"); } catch (MethodInvokeException e) { throw excHandler.methodInvokeException(e, tlContext.get(), "Can not invoke the resource method"); } catch (ConvertRepresentationException e) { throw excHandler.convertRepresentationExc(e); } return result; } /** * Converts the given JAX-RS {@link javax.ws.rs.core.Response} to a Restlet * {@link Response}. * * @param jaxRsResponse * The response returned by the resource method, perhaps as * attribute of a {@link WebApplicationException}. * @param resourceMethod * The resource method creating the response. Could be null, if * an exception is handled, e.g. a * {@link WebApplicationException}. */ private void jaxRsRespToRestletResp( javax.ws.rs.core.Response jaxRsResponse, ResourceMethod resourceMethod) { Response restletResponse = tlContext.get().getResponse(); restletResponse.setStatus(Status.valueOf(jaxRsResponse.getStatus())); MultivaluedMap<String, Object> httpHeaders = jaxRsResponse .getMetadata(); MediaType respMediaType = getMediaType(httpHeaders); Object jaxRsEntity = jaxRsResponse.getEntity(); SortedMetadata<MediaType> accMediaType; if (respMediaType != null) accMediaType = SortedMetadata.get(respMediaType); else accMediaType = tlContext.get().getAccMediaTypes(); restletResponse.setEntity(convertToRepresentation(jaxRsEntity, resourceMethod, respMediaType, httpHeaders, accMediaType)); copyResponseHeaders(httpHeaders, restletResponse); } private void loadDefaultProviders() { addDefaultProvider(new BufferedReaderProvider()); addDefaultProvider(new ByteArrayProvider()); addDefaultProvider("org.restlet.ext.jaxrs.internal.provider.DataSourceProvider"); // not yet tested addDefaultProvider("org.restlet.ext.jaxrs.internal.provider.FileUploadProvider"); // Fall-back on the Restlet converter service addDefaultProvider(new ConverterProvider()); // [ifndef gae] instruction addDefaultProvider(new org.restlet.ext.jaxrs.internal.provider.FileProvider()); addDefaultProvider(new InputStreamProvider()); addDefaultProvider("org.restlet.ext.jaxrs.internal.provider.JaxbElementProvider"); addDefaultProvider("org.restlet.ext.jaxrs.internal.provider.JaxbProvider"); // not yet tested addDefaultProvider("org.restlet.ext.jaxrs.internal.provider.MultipartProvider"); addDefaultProvider(new ReaderProvider()); addDefaultProvider(new StreamingOutputProvider()); addDefaultProvider(new StringProvider()); addDefaultProvider(new WwwFormFormProvider()); addDefaultProvider(new WwwFormMmapProvider()); addDefaultProvider(new SourceProvider()); addDefaultProvider(new WebAppExcMapper()); addDefaultProvider("org.restlet.ext.jaxrs.internal.provider.JsonProvider"); } /** * Obtains the object that will handle the request, see JAX-RS-Spec * (2008-04-16), section 3.7.2 "Request Matching", Part 2: "btain the object * that will handle the request" * * @param rroRemPathAndMatchedPath * @throws WebApplicationException * @throws RequestHandledException * @throws RuntimeException */ private ResObjAndRemPath obtainObject( RroRemPathAndMatchedPath rroRemPathAndMatchedPath) throws WebApplicationException, RequestHandledException { ResourceObject o = rroRemPathAndMatchedPath.rootResObj; RemainingPath u = rroRemPathAndMatchedPath.u; ResourceClass resClass = o.getResourceClass(); CallContext callContext = tlContext.get(); callContext.addForMatched(o.getJaxRsResourceObject(), rroRemPathAndMatchedPath.matchedUriPath); // Part 2 for (;;) // (j) { // (a) If U is null or '/' go to step 3 if (u.isEmptyOrSlash()) { return new ResObjAndRemPath(o, u); } // (b) Set C = class ofO,E = {} Collection<ResourceMethodOrLocator> eWithMethod = new ArrayList<ResourceMethodOrLocator>(); // (c) and (d) Filter E: remove members do not match U or final // match not empty for (ResourceMethodOrLocator methodOrLocator : resClass .getResourceMethodsAndLocators()) { PathRegExp pathRegExp = methodOrLocator.getPathRegExp(); MatchingResult matchingResult = pathRegExp.match(u); if (matchingResult == null) continue; if (matchingResult.getFinalCapturingGroup().isEmptyOrSlash()) eWithMethod.add(methodOrLocator); // the following is added by Stephan (is not in spec 2008-03-06) else if (methodOrLocator instanceof SubResourceLocator) eWithMethod.add(methodOrLocator); } // (e) If E is empty -> HTTP 404 if (eWithMethod.isEmpty()) excHandler.resourceNotFound();// NICE (o.getClass(), u); // (f) and (g) sort E, use first member of E ResourceMethodOrLocator firstMeth = getFirstByNoOfLiteralCharsNoOfCapturingGroups(eWithMethod); PathRegExp rMatch = firstMeth.getPathRegExp(); MatchingResult matchingResult = rMatch.match(u); addPathVarsToMap(matchingResult, callContext); // (h) When Method is resource method if (firstMeth instanceof ResourceMethod) return new ResObjAndRemPath(o, u); String matchedUriPart = matchingResult.getMatched(); Object jaxRsResObj = o.getJaxRsResourceObject(); callContext.addForMatched(jaxRsResObj, matchedUriPart); // (g) and (i) u = matchingResult.getFinalCapturingGroup(); SubResourceLocator subResourceLocator = (SubResourceLocator) firstMeth; o = createSubResource(o, subResourceLocator, callContext); resClass = o.getResourceClass(); // (j) Go to step 2a (repeat for) } } /** * Implementation of algorithm in JAX-RS-Spec (2008-04-16), Section 3.7.2 * "Request Matching" * * @return (Sub)Resource Method * @throws RequestHandledException * @throws WebApplicationException */ private ResObjAndMeth requestMatching() throws RequestHandledException, WebApplicationException { Request restletRequest = tlContext.get().getRequest(); // Part 1 RemainingPath u = new RemainingPath(restletRequest.getResourceRef() .getRemainingPart()); RroRemPathAndMatchedPath rrm = identifyRootResource(u); // Part 2 ResObjAndRemPath resourceObjectAndPath = obtainObject(rrm); Representation entity = restletRequest.getEntity(); // Part 3 MediaType givenMediaType; if (entity != null) givenMediaType = entity.getMediaType(); else givenMediaType = null; ResObjAndMeth method = identifyMethod(resourceObjectAndPath, givenMediaType); return method; } /** * Sets the Restlet that will handle the {@link Request}s, if no resource * method could be found. * * @param noResMethodHandler * the noResMethodHandler to set * @see #getNoResMethodHandler() * @see #setNoResourceClHandler(Restlet) * @see #setNoRootResClHandler(Restlet) * @see #attachDefault(Restlet) */ public void setNoResMethodHandler(Restlet noResMethodHandler) { excHandler.setNoResMethodHandler(noResMethodHandler); } /** * Sets the Restlet that will handle the {@link Request}s, if no resource * class could be found. You could remove a given Restlet by set null here.<br> * If no Restlet is given here, status 404 will be returned. * * @param noResourceClHandler * the noResourceClHandler to set * @see #getNoResourceClHandler() * @see #setNoResMethodHandler(Restlet) * @see #setNoRootResClHandler(Restlet) * @see #attachDefault(Restlet) */ public void setNoResourceClHandler(Restlet noResourceClHandler) { excHandler.setNoResourceClHandler(noResourceClHandler); } /** * Sets the Restlet that is called, if no root resource class could be * found. You could remove a given Restlet by set null here.<br> * If no Restlet is given here, status 404 will be returned. * * @param noRootResClHandler * the Restlet to call, if no root resource class could be found. * @see #getNoRootResClHandler() * @see #setNoResourceClHandler(Restlet) * @see #setNoResMethodHandler(Restlet) * @see #attachDefault(Restlet) */ public void setNoRootResClHandler(Restlet noRootResClHandler) { excHandler.setNoRootResClHandler(noRootResClHandler); } /** * Sets the ObjectFactory for root resource class and provider * instantiation. * * @param objectFactory * the ObjectFactory for root resource class and provider * instantiation. */ public void setObjectFactory(ObjectFactory objectFactory) { this.objectFactory = objectFactory; this.providers.setObjectFactory(objectFactory); } @Override public void start() throws Exception { providers.initAll(); super.start(); } }
false
true
private MediaType determineMediaType(MediaType jaxRsResponseMediaType, ResourceMethod resourceMethod, Class<?> entityClass, Type genericReturnType) throws WebApplicationException { // In many cases it is not possible to statically determine the media // type of a response. The following algorithm is used to determine the // response media type, Mselected, at run time: // 1. If the method returns an instance of Response whose metadata // includes the response media type (Mspecified) then set Mselected = // Mspecified, finish. if (jaxRsResponseMediaType != null) return jaxRsResponseMediaType; if (resourceMethod == null) return MediaType.TEXT_PLAIN; CallContext callContext = tlContext.get(); // 2. Gather the set of producible media types P : // // (a) If the method is annotated with @Produces, set P = {V (method)} // where V (t) represents the values of @Produces on the specified // target t. // // (b) Else if the class is annotated with @Produces, set P = {V // (class)}. Collection<MediaType> p = resourceMethod.getProducedMimes(); // (c) Else set P = {V (writers)} where ‘writers’ is the set of // MessageBodyWriter that support the class of the returned entity // object. if (p.isEmpty()) { p = providers.writerSubSet(entityClass, genericReturnType) .getAllProducibleMediaTypes(); } // 3. If P = {}, set P = {‘*/*’} if (p.isEmpty()) return MediaType.ALL; else p = sortByConcreteness(p); // 4. Obtain the acceptable media types A. If A = {}, set A = {‘*/*’} SortedMetadata<MediaType> a = callContext.getAccMediaTypes(); if (a.isEmpty()) a = SortedMetadata.getMediaTypeAll(); // 5. Set M = {}. For each member of A,a: // (a) For each member of P,p: // (a.1) If a is compatible with p, add S(a,p) to M, where the function // S returns the most specific media type of the pair with the q-value // of a. List<MediaType> m = new ArrayList<MediaType>(); // First test equality (ideal) for (MediaType a1 : a) { for (MediaType p1 : p) { if (a1.equals(p1)) { m.add(a1); } } } // Otherwise test inclusion (good) for (MediaType a1 : a) { for (MediaType p1 : p) { if (a1.includes(p1)) { m.add(MediaType.getMostSpecific(a1, p1)); } } } // Finally test compatibility (most flexible) for (MediaType a1 : a) { for (MediaType p1 : p) { if (a1.isCompatible(p1)) { m.add(MediaType.getMostSpecific(a1, p1)); } } } // 6. If M = {} then generate a WebApplicationException with a not // acceptable response (HTTP 406 status) and no entity. The exception // MUST be processed as described in section 3.3.4. Finish. if (m.isEmpty()) excHandler.notAcceptableWhileDetermineMediaType(); // 7. Sort M in descending order, with a primary key of specificity (n/m // > n/* > */*) and secondary key of q-value. // TODO // 8. For each member of M,m: // (a) If m is a concrete type, set Mselected = m, finish. for (MediaType mediaType : m) if (mediaType.isConcrete()) return mediaType; // 9. If M contains ‘*/*’ or ‘application/*’, set Mselected = // ‘application/octet-stream’, finish. if (m.contains(MediaType.ALL) || m.contains(MediaType.APPLICATION_ALL)) return MediaType.APPLICATION_OCTET_STREAM; // 10. Generate a WebApplicationException with a not acceptable response // (HTTP 406 status) and no entity. The exception MUST be processed as // described in section 3.3.4. Finish. throw excHandler.notAcceptableWhileDetermineMediaType(); }
private MediaType determineMediaType(MediaType jaxRsResponseMediaType, ResourceMethod resourceMethod, Class<?> entityClass, Type genericReturnType) throws WebApplicationException { // In many cases it is not possible to statically determine the media // type of a response. The following algorithm is used to determine the // response media type, Mselected, at run time: // 1. If the method returns an instance of Response whose metadata // includes the response media type (Mspecified) then set Mselected = // Mspecified, finish. if (jaxRsResponseMediaType != null) return jaxRsResponseMediaType; if (resourceMethod == null) return MediaType.TEXT_PLAIN; CallContext callContext = tlContext.get(); // 2. Gather the set of producible media types P : // // (a) If the method is annotated with @Produces, set P = {V (method)} // where V (t) represents the values of @Produces on the specified // target t. // // (b) Else if the class is annotated with @Produces, set P = {V // (class)}. Collection<MediaType> p = resourceMethod.getProducedMimes(); // (c) Else set P = {V (writers)} where 'writers' is the set of // MessageBodyWriter that support the class of the returned entity // object. if (p.isEmpty()) { p = providers.writerSubSet(entityClass, genericReturnType) .getAllProducibleMediaTypes(); } // 3. If P = {}, set P = {'*/*'} if (p.isEmpty()) return MediaType.ALL; else p = sortByConcreteness(p); // 4. Obtain the acceptable media types A. If A = {}, set A = {'*/*'} SortedMetadata<MediaType> a = callContext.getAccMediaTypes(); if (a.isEmpty()) a = SortedMetadata.getMediaTypeAll(); // 5. Set M = {}. For each member of A,a: // (a) For each member of P,p: // (a.1) If a is compatible with p, add S(a,p) to M, where the function // S returns the most specific media type of the pair with the q-value // of a. List<MediaType> m = new ArrayList<MediaType>(); // First test equality (ideal) for (MediaType a1 : a) { for (MediaType p1 : p) { if (a1.equals(p1)) { m.add(a1); } } } // Otherwise test inclusion (good) for (MediaType a1 : a) { for (MediaType p1 : p) { if (a1.includes(p1)) { m.add(MediaType.getMostSpecific(a1, p1)); } } } // Finally test compatibility (most flexible) for (MediaType a1 : a) { for (MediaType p1 : p) { if (a1.isCompatible(p1)) { m.add(MediaType.getMostSpecific(a1, p1)); } } } // 6. If M = {} then generate a WebApplicationException with a not // acceptable response (HTTP 406 status) and no entity. The exception // MUST be processed as described in section 3.3.4. Finish. if (m.isEmpty()) excHandler.notAcceptableWhileDetermineMediaType(); // 7. Sort M in descending order, with a primary key of specificity (n/m // > n/* > */*) and secondary key of q-value. // TODO // 8. For each member of M,m: // (a) If m is a concrete type, set Mselected = m, finish. for (MediaType mediaType : m) if (mediaType.isConcrete()) return mediaType; // 9. If M contains '*/*' or 'application/*', set Mselected = // 'application/octet-stream', finish. if (m.contains(MediaType.ALL) || m.contains(MediaType.APPLICATION_ALL)) return MediaType.APPLICATION_OCTET_STREAM; // 10. Generate a WebApplicationException with a not acceptable response // (HTTP 406 status) and no entity. The exception MUST be processed as // described in section 3.3.4. Finish. throw excHandler.notAcceptableWhileDetermineMediaType(); }
diff --git a/sql12/fw/src/main/java/net/sourceforge/squirrel_sql/fw/dialects/H2DialectExt.java b/sql12/fw/src/main/java/net/sourceforge/squirrel_sql/fw/dialects/H2DialectExt.java index a95b52330..1fd059c25 100644 --- a/sql12/fw/src/main/java/net/sourceforge/squirrel_sql/fw/dialects/H2DialectExt.java +++ b/sql12/fw/src/main/java/net/sourceforge/squirrel_sql/fw/dialects/H2DialectExt.java @@ -1,1074 +1,1075 @@ package net.sourceforge.squirrel_sql.fw.dialects; /* * Copyright (C) 2008 Rob Manning * [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import net.sourceforge.squirrel_sql.fw.sql.DatabaseObjectType; import net.sourceforge.squirrel_sql.fw.sql.IDatabaseObjectInfo; import net.sourceforge.squirrel_sql.fw.sql.ISQLDatabaseMetaData; import net.sourceforge.squirrel_sql.fw.sql.ITableInfo; import net.sourceforge.squirrel_sql.fw.sql.TableColumnInfo; import org.antlr.stringtemplate.StringTemplate; import org.hibernate.HibernateException; /** * A dialect delegate for the H2 database. */ public class H2DialectExt extends CommonHibernateDialect implements HibernateDialect { /** * A subclass to allow access to getTypeName without having to extend Dialect. * * @author manningr */ private class H2DialectHelper extends org.hibernate.dialect.Dialect { public H2DialectHelper() { super(); registerColumnType(Types.ARRAY, "array"); registerColumnType(Types.BIGINT, "bigint"); registerColumnType(Types.BINARY, "binary"); registerColumnType(Types.BIT, "boolean"); registerColumnType(Types.BOOLEAN, "boolean"); registerColumnType(Types.BLOB, "blob"); registerColumnType(Types.CHAR, "varchar($l)"); registerColumnType(Types.CLOB, "clob"); registerColumnType(Types.DATE, "date"); registerColumnType(Types.DECIMAL, "decimal($p,$s)"); registerColumnType(Types.DOUBLE, "double"); registerColumnType(Types.FLOAT, "float"); registerColumnType(Types.INTEGER, "integer"); registerColumnType(Types.LONGVARBINARY, "longvarbinary"); registerColumnType(Types.LONGVARCHAR, "longvarchar"); registerColumnType(Types.NUMERIC, "numeric"); registerColumnType(Types.REAL, "real"); registerColumnType(Types.SMALLINT, "smallint"); registerColumnType(Types.TIME, "time"); registerColumnType(Types.TIMESTAMP, "timestamp"); registerColumnType(Types.TINYINT, "tinyint"); registerColumnType(Types.VARBINARY, "binary($l)"); registerColumnType(Types.VARCHAR, "varchar($l)"); } } /** extended hibernate dialect used in this wrapper */ private H2DialectHelper _dialect = new H2DialectHelper(); public H2DialectExt() { /* override common behavior to use drop column style two */ super.DROP_COLUMN_SQL_TEMPLATE = ST_DROP_COLUMN_STYLE_TWO; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.CommonHibernateDialect#getTypeName(int, int, int, int) */ @Override public String getTypeName(int code, int length, int precision, int scale) throws HibernateException { return _dialect.getTypeName(code, length, precision, scale); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.CommonHibernateDialect#canPasteTo(net.sourceforge.squirrel_sql.fw.sql.IDatabaseObjectInfo) */ public boolean canPasteTo(IDatabaseObjectInfo info) { boolean result = true; DatabaseObjectType type = info.getDatabaseObjectType(); if (type.getName().equalsIgnoreCase("database")) { result = false; } return result; } /** * The string which identifies this dialect in the dialect chooser. * * @return a descriptive name that tells the user what database this dialect is design to work with. */ public String getDisplayName() { return "H2"; } /** * Returns boolean value indicating whether or not this dialect supports the specified database * product/version. * * @param databaseProductName * the name of the database as reported by DatabaseMetaData.getDatabaseProductName() * @param databaseProductVersion * the version of the database as reported by DatabaseMetaData.getDatabaseProductVersion() * @return true if this dialect can be used for the specified product name and version; false otherwise. */ public boolean supportsProduct(String databaseProductName, String databaseProductVersion) { if (databaseProductName == null) { return false; } if (databaseProductName.trim().startsWith("H2")) { // We don't yet have the need to discriminate by version. return true; } return false; } /** * Returns a boolean value indicating whether or not this dialect supports adding comments to columns. * * @return true if column comments are supported; false otherwise. */ public boolean supportsColumnComment() { return true; } /** * Returns the SQL that forms the command to drop the specified table. If cascade contraints is supported * by the dialect and cascadeConstraints is true, then a drop statement with cascade constraints clause * will be formed. * * @param iTableInfo * the table to drop * @param cascadeConstraints * whether or not to drop any FKs that may reference the specified table. * @return the drop SQL command. */ public List<String> getTableDropSQL(ITableInfo iTableInfo, boolean cascadeConstraints, boolean isMaterializedView, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { return DialectUtils.getTableDropSQL(iTableInfo, true, cascadeConstraints, false, DialectUtils.CASCADE_CLAUSE, false, qualifier, prefs, this); } /** * Returns the SQL that forms the command to add a primary key to the specified table composed of the given * column names. alter table test alter column mychar char(10) not null alter table test add primary key * (mychar) alter table pktest add constraint pk_pktest primary key (pkcol) * * @param pkName * the name of the constraint * @param columns * the columns that form the key * @return */ public String[] getAddPrimaryKeySQL(String pkName, TableColumnInfo[] columns, ITableInfo ti, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { ArrayList<String> result = new ArrayList<String>(); StringBuffer addPKSQL = new StringBuffer(); addPKSQL.append("ALTER TABLE "); addPKSQL.append(DialectUtils.shapeQualifiableIdentifier(ti.getSimpleName(), qualifier, prefs, this)); addPKSQL.append(" ADD CONSTRAINT "); addPKSQL.append(pkName); addPKSQL.append(" PRIMARY KEY ("); for (int i = 0; i < columns.length; i++) { TableColumnInfo info = columns[i]; if (info.isNullable().equals("YES")) { String alterClause = DialectUtils.ALTER_COLUMN_CLAUSE; String notNullSql = DialectUtils.getColumnNullableAlterSQL(info, false, this, alterClause, true, qualifier, prefs); result.add(notNullSql); } addPKSQL.append(DialectUtils.shapeIdentifier(info.getColumnName(), prefs, this)); if (i + 1 < columns.length) { addPKSQL.append(", "); } } addPKSQL.append(")"); result.add(addPKSQL.toString()); return result.toArray(new String[result.size()]); } /** * Returns the SQL statement to use to add a comment to the specified column of the specified table. * * @param info * information about the column such as type, name, etc. * @return * @throws UnsupportedOperationException * if the database doesn't support annotating columns with a comment. */ public String getColumnCommentAlterSQL(TableColumnInfo info, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) throws UnsupportedOperationException { return DialectUtils.getColumnCommentAlterSQL(info, qualifier, prefs, this); } /** * Returns the SQL used to alter the nullability of the specified column ALTER TABLE tableName ALTER COLUMN * columnName dataType [DEFAULT expression] [NOT [NULL]] * * @param info * the column to modify * @return the SQL to execute */ public String[] getColumnNullableAlterSQL(TableColumnInfo info, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { String alterClause = DialectUtils.ALTER_COLUMN_CLAUSE; return new String[] { DialectUtils.getColumnNullableAlterSQL(info, this, alterClause, true, qualifier, prefs) }; } /** * Returns a boolean value indicating whether or not this database dialect supports changing a column from * null to not-null and vice versa. * * @return true if the database supports dropping columns; false otherwise. */ public boolean supportsAlterColumnNull() { return true; } /** * Returns a boolean value indicating whether or not this database dialect supports renaming columns. * * @return true if the database supports changing the name of columns; false otherwise. */ public boolean supportsRenameColumn() { return true; } /** * Returns the SQL that is used to change the column name. ALTER TABLE tableName ALTER COLUMN columnName * RENAME TO name * * @param from * the TableColumnInfo as it is * @param to * the TableColumnInfo as it wants to be * @return the SQL to make the change */ public String getColumnNameAlterSQL(TableColumnInfo from, TableColumnInfo to, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { String alterClause = DialectUtils.ALTER_COLUMN_CLAUSE; String renameToClause = DialectUtils.RENAME_TO_CLAUSE; return DialectUtils.getColumnNameAlterSQL(from, to, alterClause, renameToClause, qualifier, prefs, this); } /** * Returns a boolean value indicating whether or not this dialect supports modifying a columns type. * * @return true if supported; false otherwise */ public boolean supportsAlterColumnType() { return true; } /** * Returns the SQL that is used to change the column type. ALTER TABLE table_name ALTER COLUMN column_name * data_type * * @param from * the TableColumnInfo as it is * @param to * the TableColumnInfo as it wants to be * @return the SQL to make the change * @throw UnsupportedOperationException if the database doesn't support modifying column types. */ public List<String> getColumnTypeAlterSQL(TableColumnInfo from, TableColumnInfo to, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) throws UnsupportedOperationException { String alterClause = DialectUtils.ALTER_COLUMN_CLAUSE; String setClause = ""; return DialectUtils.getColumnTypeAlterSQL(this, alterClause, setClause, false, from, to, qualifier, prefs); } /** * Returns a boolean value indicating whether or not this database dialect supports changing a column's * default value. * * @return true if the database supports modifying column defaults; false otherwise */ public boolean supportsAlterColumnDefault() { return true; } /** * Returns the SQL command to change the specified column's default value ALTER TABLE table_name ALTER * COLUMN column_name SET DEFAULT 'default value' * * @param info * the column to modify and it's default value. * @return SQL to make the change */ public String getColumnDefaultAlterSQL(TableColumnInfo info, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { String alterClause = DialectUtils.ALTER_COLUMN_CLAUSE; String defaultClause = DialectUtils.SET_DEFAULT_CLAUSE; return DialectUtils.getColumnDefaultAlterSQL(this, info, alterClause, false, defaultClause, qualifier, prefs); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.CommonHibernateDialect#getColumnDropSQL(java.lang.String, * java.lang.String, net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ @Override public String getColumnDropSQL(String tableName, String columnName, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) throws UnsupportedOperationException { StringTemplate st = new StringTemplate(DROP_COLUMN_SQL_TEMPLATE); HashMap<String, String> valuesMap = DialectUtils.getValuesMap(ST_TABLE_NAME_KEY, tableName, ST_COLUMN_NAME_KEY, columnName); return DialectUtils.bindTemplateAttributes(this, st, valuesMap, qualifier, prefs); } /** * Returns the SQL command to drop the specified table's primary key. * * @param pkName * the name of the primary key that should be dropped * @param tableName * the name of the table whose primary key should be dropped * @return */ public String getDropPrimaryKeySQL(String pkName, String tableName, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { return DialectUtils.getDropPrimaryKeySQL(pkName, tableName, false, false, qualifier, prefs, this); } /** * Returns the SQL command to drop the specified table's foreign key constraint. * * @param fkName * the name of the foreign key that should be dropped * @param tableName * the name of the table whose foreign key should be dropped * @return */ public String getDropForeignKeySQL(String fkName, String tableName, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { return DialectUtils.getDropForeignKeySQL(fkName, tableName, qualifier, prefs, this); } /** * Returns the SQL command to create the specified table. * * @param tables * the tables to get create statements for * @param md * the metadata from the ISession * @param prefs * preferences about how the resultant SQL commands should be formed. * @param isJdbcOdbc * whether or not the connection is via JDBC-ODBC bridge. * @return the SQL that is used to create the specified table */ public List<String> getCreateTableSQL(List<ITableInfo> tables, ISQLDatabaseMetaData md, CreateScriptPreferences prefs, boolean isJdbcOdbc) throws SQLException { return DialectUtils.getCreateTableSQL(tables, md, this, prefs, isJdbcOdbc); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getDialectType() */ public DialectType getDialectType() { return DialectType.H2; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getIndexAccessMethodsTypes() */ public String[] getIndexAccessMethodsTypes() { return new String[] { "DEFAULT", "HASH" }; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getIndexStorageOptions() */ public String[] getIndexStorageOptions() { return null; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getAddAutoIncrementSQL(net.sourceforge.squirrel_sql.fw.sql.TableColumnInfo, * net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String[] getAddAutoIncrementSQL(TableColumnInfo column, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // "ALTER TABLE $tableName$ ALTER COLUMN $columnName$ IDENTITY"; StringTemplate st = new StringTemplate(ST_ADD_AUTO_INCREMENT_STYLE_TWO); HashMap<String, String> valuesMap = DialectUtils.getValuesMap(ST_TABLE_NAME_KEY, column.getTableName(), ST_COLUMN_NAME_KEY, column.getColumnName()); return new String[] { DialectUtils.bindTemplateAttributes(this, st, valuesMap, qualifier, prefs) }; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getAddColumnSQL(net.sourceforge.squirrel_sql.fw.sql.TableColumnInfo, * net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String[] getAddColumnSQL(TableColumnInfo column, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { ArrayList<String> result = new ArrayList<String>(); boolean addDefaultClause = true; boolean supportsNullQualifier = true; boolean addNullClause = true; String sql = DialectUtils.getAddColumSQL(column, this, addDefaultClause, supportsNullQualifier, addNullClause, qualifier, prefs); result.add(sql); if (column.getRemarks() != null && !"".equals(column.getRemarks())) { result.add(getColumnCommentAlterSQL(column, qualifier, prefs)); } return result.toArray(new String[result.size()]); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getAddForeignKeyConstraintSQL(java.lang.String, * java.lang.String, java.lang.String, java.lang.Boolean, java.lang.Boolean, java.lang.Boolean, * boolean, java.lang.String, java.util.Collection, java.lang.String, java.lang.String, * net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String[] getAddForeignKeyConstraintSQL(String localTableName, String refTableName, String constraintName, Boolean deferrable, Boolean initiallyDeferred, Boolean matchFull, boolean autoFKIndex, String fkIndexName, Collection<String[]> localRefColumns, String onUpdateAction, String onDeleteAction, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // FOREIGN KEY (columnName [,...]) // REFERENCES [refTableName] [(refColumnName[,...])] // [ON DELETE {CASCADE | RESTRICT | NO ACTION | SET DEFAULT | SET NULL}] // [ON UPDATE {CASCADE | SET DEFAULT | SET NULL}] // "ALTER TABLE $childTableName$ " + // "ADD $constraint$ $constraintName$ FOREIGN KEY ( $childColumn; separator=\",\"$ ) " + // "REFERENCES $parentTableName$ ( $parentColumn; separator=\",\"$ )"; StringTemplate fkST = new StringTemplate(ST_ADD_FOREIGN_KEY_CONSTRAINT_STYLE_ONE); HashMap<String, String> fkValuesMap = DialectUtils.getValuesMap(ST_CHILD_TABLE_KEY, localTableName); fkValuesMap.put(ST_CONSTRAINT_KEY, "CONSTRAINT"); fkValuesMap.put(ST_CONSTRAINT_NAME_KEY, constraintName); fkValuesMap.put(ST_PARENT_TABLE_KEY, refTableName); StringTemplate childIndexST = null; HashMap<String, String> ckIndexValuesMap = null; if (autoFKIndex) { // "CREATE $unique$ $storageOption$ INDEX $indexName$ " + // "ON $tableName$ ( $columnName; separator=\",\"$ )"; childIndexST = new StringTemplate(ST_CREATE_INDEX_STYLE_TWO); ckIndexValuesMap = new HashMap<String, String>(); ckIndexValuesMap.put(ST_INDEX_NAME_KEY, "fk_child_idx"); + ckIndexValuesMap.put(ST_TABLE_NAME_KEY, localTableName); } return DialectUtils.getAddForeignKeyConstraintSQL(fkST, fkValuesMap, childIndexST, ckIndexValuesMap, localRefColumns, qualifier, prefs, this); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getAddUniqueConstraintSQL(java.lang.String, * java.lang.String, net.sourceforge.squirrel_sql.fw.sql.TableColumnInfo[], * net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String[] getAddUniqueConstraintSQL(String tableName, String constraintName, TableColumnInfo[] columns, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // "ALTER TABLE $tableName$ " + // "ADD $constraint$ $constraintName$ UNIQUE $index$ $indexName$ $indexType$ ( $indexColumnName$ )"; StringTemplate st = new StringTemplate(ST_ADD_UNIQUE_CONSTRAINT_STYLE_ONE); HashMap<String, String> valuesMap = DialectUtils.getValuesMap(ST_TABLE_NAME_KEY, tableName, ST_CONSTRAINT_KEY, "CONSTRAINT", ST_CONSTRAINT_NAME_KEY, constraintName); return new String[] { DialectUtils.bindTemplateAttributes(this, st, valuesMap, columns, qualifier, prefs) }; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getAlterSequenceSQL(java.lang.String, * java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, boolean, * net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String[] getAlterSequenceSQL(String sequenceName, String increment, String minimum, String maximum, String restart, String cache, boolean cycle, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // "ALTER SEQUENCE $sequenceName$ " + // "$restartWith$ $startValue$ " + // "$incrementBy$ $incrementValue$ "; StringTemplate st = new StringTemplate(ST_ALTER_SEQUENCE_STYLE_ONE); HashMap<String, String> valuesMap = DialectUtils.getValuesMap(ST_SEQUENCE_NAME_KEY, sequenceName); if (DialectUtils.isNotEmptyString(restart)) { valuesMap.put(ST_RESTART_WITH_KEY, "RESTART WITH"); valuesMap.put(ST_START_VALUE_KEY, restart); } if (DialectUtils.isNotEmptyString(increment)) { valuesMap.put(ST_INCREMENT_BY_KEY, "INCREMENT BY"); valuesMap.put(ST_INCREMENT_VALUE_KEY, increment); } return new String[] { DialectUtils.bindTemplateAttributes(this, st, valuesMap, qualifier, prefs) }; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getCreateIndexSQL(java.lang.String, * java.lang.String, java.lang.String, java.lang.String[], boolean, java.lang.String, * java.lang.String, net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String getCreateIndexSQL(String indexName, String tableName, String accessMethod, String[] columns, boolean unique, String tablespace, String constraints, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // CREATE {[UNIQUE [HASH]] INDEX [[IF NOT EXISTS] newIndexName] // | PRIMARY KEY [HASH]} ON (columnName [,...]) StringTemplate st = new StringTemplate(ST_CREATE_INDEX_STYLE_TWO); // "CREATE $unique$ $storageOption$ INDEX $indexName$ " + // "ON $tableName$ ( $columnName; separator=\",\"$ )"; HashMap<String, String> valuesMap = new HashMap<String, String>(); if (unique) { valuesMap.put(ST_UNIQUE_KEY, "UNIQUE"); if (accessMethod != null && "HASH".equalsIgnoreCase(accessMethod)) { valuesMap.put(ST_STORAGE_OPTION_KEY, "HASH"); } } valuesMap.put(ST_INDEX_NAME_KEY, indexName); valuesMap.put(ST_TABLE_NAME_KEY, tableName); return DialectUtils.getAddIndexSQL(this, st, valuesMap, columns, qualifier, prefs); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getCreateSequenceSQL(java.lang.String, * java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, boolean, * net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String getCreateSequenceSQL(String sequenceName, String increment, String minimum, String maximum, String start, String cache, boolean cycle, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // CREATE SEQUENCE [IF NOT EXISTS] newSequenceName // [START WITH long] // [INCREMENT BY long] // [CACHE long] // "CREATE SEQUENCE $sequenceName$ START WITH $startValue$ " + // "INCREMENT BY $incrementValue$ $cache$ $cacheValue$"; StringTemplate st = new StringTemplate(ST_CREATE_SEQUENCE_STYLE_ONE); HashMap<String, String> valuesMap = DialectUtils.getValuesMap(ST_SEQUENCE_NAME_KEY, sequenceName); if (DialectUtils.isNotEmptyString(cache)) { valuesMap.put(ST_CACHE_KEY, "CACHE"); valuesMap.put(ST_CACHE_VALUE_KEY, cache); } if (DialectUtils.isNotEmptyString(increment)) { valuesMap.put(ST_INCREMENT_VALUE_KEY, increment); } if (DialectUtils.isNotEmptyString(start)) { valuesMap.put(ST_START_VALUE_KEY, start); } return DialectUtils.bindTemplateAttributes(this, st, valuesMap, qualifier, prefs); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getCreateTableSQL(java.lang.String, * java.util.List, java.util.List, net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences, * net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier) */ public String getCreateTableSQL(String tableName, List<TableColumnInfo> columns, List<TableColumnInfo> primaryKeys, SqlGenerationPreferences prefs, DatabaseObjectQualifier qualifier) { return DialectUtils.getCreateTableSQL(tableName, columns, primaryKeys, prefs, qualifier, this); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getCreateViewSQL(java.lang.String, * java.lang.String, java.lang.String, * net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String getCreateViewSQL(String viewName, String definition, String checkOption, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // CREATE [FORCE] VIEW [IF NOT EXISTS] newViewName [(columnName [,..])] // AS select // "CREATE VIEW $viewName$ " + // "AS $selectStatement$ $with$ $checkOptionType$ $checkOption$"; StringTemplate st = new StringTemplate(ST_CREATE_VIEW_STYLE_ONE); HashMap<String, String> valuesMap = DialectUtils.getValuesMap(ST_VIEW_NAME_KEY, viewName, ST_SELECT_STATEMENT_KEY, definition); return DialectUtils.bindTemplateAttributes(this, st, valuesMap, qualifier, prefs); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getDropConstraintSQL(java.lang.String, * java.lang.String, net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String getDropConstraintSQL(String tableName, String constraintName, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // ALTER TABLE $tableName$ DROP CONSTRAINT $constraintName$ StringTemplate st = new StringTemplate(ST_DROP_CONSTRAINT_STYLE_ONE); HashMap<String, String> valuesMap = DialectUtils.getValuesMap(ST_TABLE_NAME_KEY, tableName, ST_CONSTRAINT_NAME_KEY, constraintName); return DialectUtils.bindTemplateAttributes(this, st, valuesMap, qualifier, prefs); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getDropIndexSQL(java.lang.String, * java.lang.String, boolean, net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String getDropIndexSQL(String tableName, String indexName, boolean cascade, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // "DROP INDEX $indexName$"; StringTemplate st = new StringTemplate(ST_DROP_INDEX_STYLE_THREE); HashMap<String, String> valuesMap = DialectUtils.getValuesMap(ST_INDEX_NAME_KEY, indexName); return DialectUtils.bindTemplateAttributes(this, st, valuesMap, qualifier, prefs); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getDropSequenceSQL(java.lang.String, * boolean, net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String getDropSequenceSQL(String sequenceName, boolean cascade, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // "DROP SEQUENCE $sequenceName$ $cascade$"; StringTemplate st = new StringTemplate(ST_DROP_SEQUENCE_STYLE_ONE); HashMap<String, String> valuesMap = DialectUtils.getValuesMap(ST_SEQUENCE_NAME_KEY, sequenceName); return DialectUtils.bindTemplateAttributes(this, st, valuesMap, qualifier, prefs); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getDropViewSQL(java.lang.String, boolean, * net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String getDropViewSQL(String viewName, boolean cascade, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // "DROP VIEW $viewName$"; StringTemplate st = new StringTemplate(ST_DROP_VIEW_STYLE_ONE); HashMap<String, String> valuesMap = DialectUtils.getValuesMap(ST_VIEW_NAME_KEY, viewName); return DialectUtils.bindTemplateAttributes(this, st, valuesMap, qualifier, prefs); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getInsertIntoSQL(java.lang.String, * java.util.List, java.lang.String, net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String getInsertIntoSQL(String tableName, List<String> columns, String valuesPart, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { return DialectUtils.getInsertIntoSQL(tableName, columns, valuesPart, qualifier, prefs, this); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getRenameTableSQL(java.lang.String, * java.lang.String, net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String getRenameTableSQL(String oldTableName, String newTableName, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // "ALTER TABLE $oldObjectName$ RENAME TO $newObjectName$"; StringTemplate st = new StringTemplate(ST_RENAME_OBJECT_STYLE_ONE); HashMap<String, String> valuesMap = DialectUtils.getValuesMap(ST_OLD_OBJECT_NAME_KEY, oldTableName, ST_NEW_OBJECT_NAME_KEY, newTableName); return DialectUtils.bindTemplateAttributes(this, st, valuesMap, qualifier, prefs); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getRenameViewSQL(java.lang.String, * java.lang.String, net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String[] getRenameViewSQL(String oldViewName, String newViewName, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { String msg = DialectUtils.getUnsupportedMessage(this, DialectUtils.RENAME_VIEW_TYPE); throw new UnsupportedOperationException(msg); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getSequenceInformationSQL(java.lang.String, * net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String getSequenceInformationSQL(String sequenceName, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // "SELECT CURRENT_VALUE, 'NONE', 'NONE', CACHE, INCREMENT, 0 " + // "FROM INFORMATION_SCHEMA.SEQUENCES " + // "WHERE SEQUENCE_SCHEMA = ? " + // "AND SEQUENCE_NAME = ? "; String templateStr = "SELECT CURRENT_VALUE, 'NONE', 'NONE', CACHE, INCREMENT, 0 " + "FROM INFORMATION_SCHEMA.SEQUENCES " + "WHERE SEQUENCE_SCHEMA = '$schemaName$' " + "AND SEQUENCE_NAME = '$sequenceName$' " + "AND SEQUENCE_CATALOG = '$catalogName$'"; StringTemplate st = new StringTemplate(templateStr); st.setAttribute(ST_SCHEMA_NAME_KEY, qualifier.getSchema()); st.setAttribute(ST_CATALOG_NAME_KEY, qualifier.getCatalog()); st.setAttribute(ST_SEQUENCE_NAME_KEY, sequenceName); return st.toString(); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsAccessMethods() */ public boolean supportsAccessMethods() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsAddForeignKeyConstraint() */ public boolean supportsAddForeignKeyConstraint() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsAddUniqueConstraint() */ public boolean supportsAddUniqueConstraint() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsAlterSequence() */ public boolean supportsAlterSequence() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsAutoIncrement() */ public boolean supportsAutoIncrement() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsCheckOptionsForViews() */ public boolean supportsCheckOptionsForViews() { return false; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsCreateIndex() */ public boolean supportsCreateIndex() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsCreateSequence() */ public boolean supportsCreateSequence() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsCreateTable() */ public boolean supportsCreateTable() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsCreateView() */ public boolean supportsCreateView() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsDropConstraint() */ public boolean supportsDropConstraint() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsDropIndex() */ public boolean supportsDropIndex() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsDropSequence() */ public boolean supportsDropSequence() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsDropView() */ public boolean supportsDropView() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsEmptyTables() */ public boolean supportsEmptyTables() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsIndexes() */ public boolean supportsIndexes() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsInsertInto() */ public boolean supportsInsertInto() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsMultipleRowInserts() */ public boolean supportsMultipleRowInserts() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsRenameTable() */ public boolean supportsRenameTable() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsRenameView() */ public boolean supportsRenameView() { return false; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsSequence() */ public boolean supportsSequence() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsSequenceInformation() */ public boolean supportsSequenceInformation() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsTablespace() */ public boolean supportsTablespace() { return false; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsUpdate() */ public boolean supportsUpdate() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsAddColumn() */ public boolean supportsAddColumn() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsViewDefinition() */ public boolean supportsViewDefinition() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getViewDefinitionSQL(java.lang.String, * net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String getViewDefinitionSQL(String viewName, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // "select view_definition " + // "from information_schema.views " + // "where table_schema = ? " + // "and table_name = ? "; String templateStr = "select view_definition from information_schema.views " + "where table_schema = '$schemaName$' and UPPER(table_name) = UPPER('$viewName$') "; StringTemplate st = new StringTemplate(templateStr); st.setAttribute(ST_SCHEMA_NAME_KEY, qualifier.getSchema()); st.setAttribute(ST_VIEW_NAME_KEY, viewName); return st.toString(); } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#getQualifiedIdentifier(java.lang.String, * net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier, * net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences) */ public String getQualifiedIdentifier(String identifier, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { return identifier; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect#supportsCorrelatedSubQuery() */ public boolean supportsCorrelatedSubQuery() { return true; } /** * @see net.sourceforge.squirrel_sql.fw.dialects.CommonHibernateDialect#getTimestampMaximumFractionalDigits() */ @Override public int getTimestampMaximumFractionalDigits() { return 9; } }
true
true
public String[] getAddForeignKeyConstraintSQL(String localTableName, String refTableName, String constraintName, Boolean deferrable, Boolean initiallyDeferred, Boolean matchFull, boolean autoFKIndex, String fkIndexName, Collection<String[]> localRefColumns, String onUpdateAction, String onDeleteAction, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // FOREIGN KEY (columnName [,...]) // REFERENCES [refTableName] [(refColumnName[,...])] // [ON DELETE {CASCADE | RESTRICT | NO ACTION | SET DEFAULT | SET NULL}] // [ON UPDATE {CASCADE | SET DEFAULT | SET NULL}] // "ALTER TABLE $childTableName$ " + // "ADD $constraint$ $constraintName$ FOREIGN KEY ( $childColumn; separator=\",\"$ ) " + // "REFERENCES $parentTableName$ ( $parentColumn; separator=\",\"$ )"; StringTemplate fkST = new StringTemplate(ST_ADD_FOREIGN_KEY_CONSTRAINT_STYLE_ONE); HashMap<String, String> fkValuesMap = DialectUtils.getValuesMap(ST_CHILD_TABLE_KEY, localTableName); fkValuesMap.put(ST_CONSTRAINT_KEY, "CONSTRAINT"); fkValuesMap.put(ST_CONSTRAINT_NAME_KEY, constraintName); fkValuesMap.put(ST_PARENT_TABLE_KEY, refTableName); StringTemplate childIndexST = null; HashMap<String, String> ckIndexValuesMap = null; if (autoFKIndex) { // "CREATE $unique$ $storageOption$ INDEX $indexName$ " + // "ON $tableName$ ( $columnName; separator=\",\"$ )"; childIndexST = new StringTemplate(ST_CREATE_INDEX_STYLE_TWO); ckIndexValuesMap = new HashMap<String, String>(); ckIndexValuesMap.put(ST_INDEX_NAME_KEY, "fk_child_idx"); } return DialectUtils.getAddForeignKeyConstraintSQL(fkST, fkValuesMap, childIndexST, ckIndexValuesMap, localRefColumns, qualifier, prefs, this); }
public String[] getAddForeignKeyConstraintSQL(String localTableName, String refTableName, String constraintName, Boolean deferrable, Boolean initiallyDeferred, Boolean matchFull, boolean autoFKIndex, String fkIndexName, Collection<String[]> localRefColumns, String onUpdateAction, String onDeleteAction, DatabaseObjectQualifier qualifier, SqlGenerationPreferences prefs) { // FOREIGN KEY (columnName [,...]) // REFERENCES [refTableName] [(refColumnName[,...])] // [ON DELETE {CASCADE | RESTRICT | NO ACTION | SET DEFAULT | SET NULL}] // [ON UPDATE {CASCADE | SET DEFAULT | SET NULL}] // "ALTER TABLE $childTableName$ " + // "ADD $constraint$ $constraintName$ FOREIGN KEY ( $childColumn; separator=\",\"$ ) " + // "REFERENCES $parentTableName$ ( $parentColumn; separator=\",\"$ )"; StringTemplate fkST = new StringTemplate(ST_ADD_FOREIGN_KEY_CONSTRAINT_STYLE_ONE); HashMap<String, String> fkValuesMap = DialectUtils.getValuesMap(ST_CHILD_TABLE_KEY, localTableName); fkValuesMap.put(ST_CONSTRAINT_KEY, "CONSTRAINT"); fkValuesMap.put(ST_CONSTRAINT_NAME_KEY, constraintName); fkValuesMap.put(ST_PARENT_TABLE_KEY, refTableName); StringTemplate childIndexST = null; HashMap<String, String> ckIndexValuesMap = null; if (autoFKIndex) { // "CREATE $unique$ $storageOption$ INDEX $indexName$ " + // "ON $tableName$ ( $columnName; separator=\",\"$ )"; childIndexST = new StringTemplate(ST_CREATE_INDEX_STYLE_TWO); ckIndexValuesMap = new HashMap<String, String>(); ckIndexValuesMap.put(ST_INDEX_NAME_KEY, "fk_child_idx"); ckIndexValuesMap.put(ST_TABLE_NAME_KEY, localTableName); } return DialectUtils.getAddForeignKeyConstraintSQL(fkST, fkValuesMap, childIndexST, ckIndexValuesMap, localRefColumns, qualifier, prefs, this); }
diff --git a/src/uk/co/kevinjjones/RunManager.java b/src/uk/co/kevinjjones/RunManager.java index 030ddeb..f2fffde 100755 --- a/src/uk/co/kevinjjones/RunManager.java +++ b/src/uk/co/kevinjjones/RunManager.java @@ -1,536 +1,535 @@ /** * Copyright 2011 Kevin J. Jones (http://www.kevinjjones.co.uk) * * 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 uk.co.kevinjjones; import java.awt.BorderLayout; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.text.ParseException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import javax.swing.*; import uk.co.kevinjjones.model.*; import uk.co.kevinjjones.vehicle.SpeedStream; /** * Manager for all run data */ public class RunManager implements ParamHandler { /** * A stream wrapper for RunManager records */ public class RunStream implements ROStream { private ROStream _stream; private int _start; private int _size; private boolean _rebase; private double _base; private ArrayList<Pair<String, String>> _meta = new ArrayList(); public RunStream(ROStream stream, int start, int size) { _stream = stream; _start = start; _size = size; _rebase = stream.getMeta("rebase").equals("true"); } @Override public String name() { return _stream.name(); } @Override public String description() { return _stream.description(); } @Override public String axis() { return _stream.axis(); } @Override public String units() { return _stream.units(); } @Override public int size() { return _size; } @Override public String getString(int position) { assert (position < _size); return _stream.getString(_start + position); } @Override public long getTick(int position) throws ParseException { assert (position < _size); return _stream.getTick(_start + position); } @Override public double getNumeric(int position) throws NumberFormatException { assert (position < _size); if (_rebase) { _base = _stream.getNumeric(_start + 0); _rebase = false; } return _stream.getNumeric(_start + position) - _base; } @Override public String[] getStringSet() { return _stream.getStringSet(); } @Override public Double[] toArray() throws NumberFormatException { return _stream.toArray(); } @Override public void setMeta(String id, String value) { _meta.add(new Pair(id, value)); } @Override public String getMeta(String id) { int i = 0; while (i < _meta.size()) { if (_meta.get(i).first().equals(id)) { return _meta.get(i).second(); } } return ""; } } /** * A single Run wrapper */ public class Run { private String _prefix; private Log _log; private int _start; private int _end; private boolean _isSplit; public Run(String prefix, Log log, int start, int end, boolean isSplit) { _prefix = prefix; _log = log; _start = start; _end = end; _isSplit = isSplit; } public Log log() { return _log; } public String name() { if (_prefix.isEmpty()) { return _log.name(); } else { return _prefix + " " + _log.name(); } } public int length() { return _end - _start; } public boolean isSplit() { return _isSplit; } public int streamCount() { return _log.streamCount(); } public boolean hasStream(String name) { return _log.hasStream(name); } public ROStream getStream(String name) { if (!_log.hasStream(name)) { return null; } return new RunStream(_log.getStream(name), _start, _end - _start); } public ROStream getStream(int index) { if (index < 0 || index >= _log.streamCount()) { return null; } return new RunStream(_log.getStream(index), _start, _end - _start); } /* * Saving for later... */ /* * public double degrees(int i) { * * if (_log.hasLeftSpeed() && _log.hasRightSpeed()) { * * double ls = _log.leftSpeed(_start + i); double rs = * _log.rightSpeed(_start + i); * * Car c = Car.getInstance(); boolean rightTurn = (ls > rs); if * (rightTurn) { return c.getDegrees(ls, rs); } else { return * -c.getDegrees(rs, ls); } } return 0; } * * public double latAccel(int i) { * * if (_log.hasLeftSpeed() && _log.hasRightSpeed()) { * * double ls = _log.leftSpeed(_start + i); double rs = * _log.rightSpeed(_start + i); * * Car c = Car.getInstance(); boolean rightTurn = (ls > rs); if * (rightTurn) { return c.getLatAccel(ls, rs); } else { return * -c.getLatAccel(rs, ls); } } return 0; } * * public double lambda(int index) { if (_lambdaData == null) { * * // Populate with shift _lambdaData = new double[length()]; for (int * j = 0; j < _lambdaData.length; j++) { int idx = (j + lambdaDelay()) % * (_end - _start); _lambdaData[j] = _log.lambda(_start + idx); } * * // Exclude 'bad' section where MAP<80 || map is falling // by 3% * over 0.5 seconds. for (int i = 0; i < _lambdaData.length; i++) { * * // Scan for a switch to bad int r = i; int startBad = 0; while (r + * 1 < _lambdaData.length) { double m = map(r); if (m < 80) { startBad = * r; break; } double d = (map(r + 1) - m) / m; if (d < -0.01) { * startBad = r; break; } r++; } * * if (startBad != 0) { double m = map(startBad); if (m < 80) { while (m * < 80 && startBad<_lambdaData.length) { _lambdaData[startBad] = 0; * startBad++; m = map(startBad); } i=startBad; } else { // Test for * sufficient fall double low = 0.97 * map(startBad); for (int k = * startBad; k < startBad + 5 && k<_lambdaData.length; k++) { if (map(k) * < low) { // Walk until map increases again while (map(k + 1) < * map(k)) { k++; } * * // Got one, so zero out for (int p = startBad - 1; p <= k+1; p++) { * _lambdaData[p] = 0; } i = k; break; } } } } } } * * return _lambdaData[index]; } * */ } private static RunManager _instance = null; private static Frame _frame = null; private List<Log> _logs = new LinkedList<Log>(); private List<Run> _runs = new LinkedList<Run>(); private boolean _autoSplit = false; private int _KPH = 0; protected RunManager() { // Load preferences Preferences prefs = Preferences.userNodeForPackage(RunManager.class); _KPH = prefs.getInt("KPH2", 0); _autoSplit = prefs.getBoolean("AutoSplit", false); } // Singleton access public static RunManager getInstance() { if (_instance == null) { _instance = new RunManager(); } return _instance; } // Set UI frame for allow dialog boxes to be setup public void setFrame(Frame frame) { _frame = frame; } @Override public String getParameter(String name, boolean prompt) { if (name.equals("isKPH")) { if (_KPH == 0 && prompt) { JDialog dialog = new JDialog(_frame, "DTA System Units", true); Container content = dialog.getContentPane(); OptionsDialog oDlg = new OptionsDialog(); content.add(oDlg); dialog.pack(); dialog.setLocationRelativeTo(_frame); dialog.setVisible(true); } if (_KPH == 1) { return "true"; } if (_KPH == 2) { return "false"; } } return null; } public void addLogfile(File file, WithError<Boolean, BasicError> ok) throws IOException { // Parse logile and load runs from it Log l = new Log(file, this, ok); if (ok.value()) { _logs.add(l); addSessions(l, ok); } } public Log[] getLogs() { return _logs.toArray(new Log[0]); } public Run[] getRuns() { return _runs.toArray(new Run[0]); } private void addSessions(Log l, WithError<Boolean, BasicError> ok) { // Now look for multiple sessions ROStream sess = l.getStream(Log.SESSION_STREAM); String c = sess.getString(0); int begin = 1; int end = 1; int s = 1; int runs = 0; for (; end < sess.size(); end++) { if (!sess.getString(end).equals(c)) { runs += addRuns(l, s++, begin, end - 1 - begin); begin = end; c = sess.getString(begin); } } runs += addRuns(l, s++, begin, end - 1 - begin); if (isAutoSplit() && runs == 0) { ok.addError(new BasicError(BasicError.WARN, "No runs detected, try " + "loading file with auto spliting turned off")); } else if (isAutoSplit()) { ok.addError(new BasicError(BasicError.INFO, "Loaded " + (s - 1) + " sessions from " + l.name() + ", containing " + runs + " runs.")); } else { ok.addError(new BasicError(BasicError.INFO, "Loaded " + (s - 1) + " sessions from " + l.name() + ".")); } } private int addRuns(Log l, int session, int begin, int size) { // Should we also split? int endSession = begin + size; int id = 1; ROStream speed = l.getStream(SpeedStream.NAME); if (speed != null && isAutoSplit()) { // Look for runs int at = begin; while (true) { int start = findStartPoint(speed, at, endSession); if (start == -1) { break; } int end = findEndPoint(speed, start, endSession); if (end == -1) { break; } _runs.add(new Run("S" + session + "#" + id++, l, start, end, true)); at = end; } return id - 1; } else { _runs.add(new Run("S" + session, l, begin, begin + size, false)); return 1; } } /** * Test if the current row is a crossing point to the next speed unit. We * use two datums here, crossing from 0->1 kph and crossing over a * speedBucket * * @param data * @param start * @param index * @return */ private static int findStartPoint(ROStream speed, int start, int endSession) { // Loop speed until >60kph int r = start; for (; r < endSession; r++) { if (speed.getNumeric(r) > 60) { break; } } // Didn't find if (r == endSession) { return -1; } // Now loop back to locate the start at lowest speed <10kph while (r > start) { double s = speed.getNumeric(r); double low = s; if (s < 10) { // In right area, find first lowest int t = r - 1; while (t > 0) { double s2 = speed.getNumeric(t); if (s2 < low) { low = s2; r = t; } else { return r; } t--; } } r--; } // Not found; return -1; } private static int findEndPoint(ROStream speed, int start, int endSession) { // Loop speed until >60kph int r = start; for (; r < endSession; r++) { if (speed.getNumeric(r) > 60) { break; } } // Didn't find if (r == endSession) { return -1; } // Continue loop until < 5km/h for (; r < endSession; r++) { if (speed.getNumeric(r) < 5) { return r; } } return -1; } private void flushPrefs() { Preferences prefs = Preferences.userNodeForPackage(RunManager.class); prefs.putInt("KPH2", _KPH); prefs.putBoolean("AutoSplit", _autoSplit); try { prefs.flush(); - throw new BackingStoreException("Test"); } catch (BackingStoreException ex) { final JDialog dialog = new JDialog(_frame, "Error", true); JPanel displayArea = new JPanel(); displayArea.setLayout(new BoxLayout(displayArea, BoxLayout.PAGE_AXIS)); JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING)); displayArea.add(panel); panel.add(new JLabel("Message:")); panel.add(new JLabel("Failed to save user preferences")); JPanel epanel = new JPanel(new FlowLayout(FlowLayout.LEADING)); displayArea.add(epanel); epanel.add(new JLabel("Exception:")); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); ex.printStackTrace(pw); pw.flush(); sw.flush(); epanel.add(new JLabel("<html>" + sw.toString().replaceAll("\n", "<br>"))); JPanel buttonArea = new JPanel(); FlowLayout buttonLayout = new FlowLayout(FlowLayout.RIGHT); buttonArea.setLayout(buttonLayout); JButton okBtn = new JButton("OK"); buttonArea.add(okBtn); okBtn.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(false); } }); JPanel dialogPanel = new JPanel(); BorderLayout dialogLayout = new BorderLayout(); dialogPanel.setLayout(dialogLayout); dialogPanel.add(displayArea, BorderLayout.CENTER); dialogPanel.add(buttonArea, BorderLayout.PAGE_END); Container content = dialog.getContentPane(); content.add(dialogPanel); dialog.pack(); dialog.setLocationRelativeTo(_frame); dialog.setVisible(true); } } public boolean isAutoSplit() { return _autoSplit; } public void setAutoSplit(boolean isAutoSplit) { _autoSplit = isAutoSplit; flushPrefs(); } public int getKPH() { return _KPH; } public void setKPH(boolean isKPH) { _KPH = isKPH ? 1 : 2; flushPrefs(); } public void unsetKPH() { _KPH = 0; flushPrefs(); } }
true
true
private void flushPrefs() { Preferences prefs = Preferences.userNodeForPackage(RunManager.class); prefs.putInt("KPH2", _KPH); prefs.putBoolean("AutoSplit", _autoSplit); try { prefs.flush(); throw new BackingStoreException("Test"); } catch (BackingStoreException ex) { final JDialog dialog = new JDialog(_frame, "Error", true); JPanel displayArea = new JPanel(); displayArea.setLayout(new BoxLayout(displayArea, BoxLayout.PAGE_AXIS)); JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING)); displayArea.add(panel); panel.add(new JLabel("Message:")); panel.add(new JLabel("Failed to save user preferences")); JPanel epanel = new JPanel(new FlowLayout(FlowLayout.LEADING)); displayArea.add(epanel); epanel.add(new JLabel("Exception:")); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); ex.printStackTrace(pw); pw.flush(); sw.flush(); epanel.add(new JLabel("<html>" + sw.toString().replaceAll("\n", "<br>"))); JPanel buttonArea = new JPanel(); FlowLayout buttonLayout = new FlowLayout(FlowLayout.RIGHT); buttonArea.setLayout(buttonLayout); JButton okBtn = new JButton("OK"); buttonArea.add(okBtn); okBtn.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(false); } }); JPanel dialogPanel = new JPanel(); BorderLayout dialogLayout = new BorderLayout(); dialogPanel.setLayout(dialogLayout); dialogPanel.add(displayArea, BorderLayout.CENTER); dialogPanel.add(buttonArea, BorderLayout.PAGE_END); Container content = dialog.getContentPane(); content.add(dialogPanel); dialog.pack(); dialog.setLocationRelativeTo(_frame); dialog.setVisible(true); } }
private void flushPrefs() { Preferences prefs = Preferences.userNodeForPackage(RunManager.class); prefs.putInt("KPH2", _KPH); prefs.putBoolean("AutoSplit", _autoSplit); try { prefs.flush(); } catch (BackingStoreException ex) { final JDialog dialog = new JDialog(_frame, "Error", true); JPanel displayArea = new JPanel(); displayArea.setLayout(new BoxLayout(displayArea, BoxLayout.PAGE_AXIS)); JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING)); displayArea.add(panel); panel.add(new JLabel("Message:")); panel.add(new JLabel("Failed to save user preferences")); JPanel epanel = new JPanel(new FlowLayout(FlowLayout.LEADING)); displayArea.add(epanel); epanel.add(new JLabel("Exception:")); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); ex.printStackTrace(pw); pw.flush(); sw.flush(); epanel.add(new JLabel("<html>" + sw.toString().replaceAll("\n", "<br>"))); JPanel buttonArea = new JPanel(); FlowLayout buttonLayout = new FlowLayout(FlowLayout.RIGHT); buttonArea.setLayout(buttonLayout); JButton okBtn = new JButton("OK"); buttonArea.add(okBtn); okBtn.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(false); } }); JPanel dialogPanel = new JPanel(); BorderLayout dialogLayout = new BorderLayout(); dialogPanel.setLayout(dialogLayout); dialogPanel.add(displayArea, BorderLayout.CENTER); dialogPanel.add(buttonArea, BorderLayout.PAGE_END); Container content = dialog.getContentPane(); content.add(dialogPanel); dialog.pack(); dialog.setLocationRelativeTo(_frame); dialog.setVisible(true); } }
diff --git a/logback/src/main/java/org/apache/sling/extensions/logback/internal/OsgiInternalAction.java b/logback/src/main/java/org/apache/sling/extensions/logback/internal/OsgiInternalAction.java index 55342c6..d256294 100644 --- a/logback/src/main/java/org/apache/sling/extensions/logback/internal/OsgiInternalAction.java +++ b/logback/src/main/java/org/apache/sling/extensions/logback/internal/OsgiInternalAction.java @@ -1,135 +1,135 @@ /* * 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.sling.extensions.logback.internal; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.event.SaxEvent; import ch.qos.logback.core.joran.event.SaxEventRecorder; import ch.qos.logback.core.joran.spi.ActionException; import ch.qos.logback.core.joran.spi.InterpretationContext; import ch.qos.logback.core.joran.spi.JoranException; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import static org.apache.sling.extensions.logback.internal.ConfigSourceTracker.ConfigSourceInfo; /** * Joran action enabling integration between OSGi and Logback. It is based on * {@link ch.qos.logback.core.joran.action.IncludeAction}. It supports including config fragments provided * through OSGi ServiceRegistry */ public class OsgiInternalAction extends Action { private static final String INCLUDED_TAG = "included"; @Override public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { populateSubstitutionProperties(ec); //TO CHECK Should we add the config fragment at end final Collection<ConfigSourceInfo> providers = getFragmentProviders(); List<SaxEvent> consolidatedEventList = new ArrayList<SaxEvent>(); for (ConfigSourceInfo cp : providers) { InputSource is = cp.getConfigProvider().getConfigSource(); try { SaxEventRecorder recorder = new SaxEventRecorder(context); recorder.recordEvents(is); // remove the <included> tag from the beginning and </included> from the end trimHeadAndTail(recorder); consolidatedEventList.addAll(recorder.getSaxEventList()); } catch (JoranException e) { - addError("Error while parsing "+cp, e); + addError("Error while parsing xml obtained from ["+cp+"]", e); } finally { close(is); } } // offset = 2, because we need to get past this element as well as the end element ec.getJoranInterpreter().getEventPlayer().addEventsDynamically(consolidatedEventList, 2); } private void populateSubstitutionProperties(InterpretationContext ec) { getLogbackManager().addSubsitutionProperties(ec); } @Override public void end(InterpretationContext ec, String name) throws ActionException { // do nothing } private Collection<ConfigSourceInfo> getFragmentProviders() { ConfigSourceTracker tracker = (ConfigSourceTracker) getContext().getObject(ConfigSourceTracker.class.getName()); if (tracker != null) { return tracker.getSources(); } return Collections.emptyList(); } private LogbackManager getLogbackManager(){ LogbackManager lm = (LogbackManager) getContext().getObject(LogbackManager.class.getName()); if(lm == null){ throw new IllegalStateException("LogbackManager not found in Context map"); } return lm; } private static void close(InputSource is) { Closeable c = is.getByteStream(); if(c == null){ c = is.getCharacterStream(); } if (c != null) { try { c.close(); } catch (IOException e) { //Ignore } } } private static void trimHeadAndTail(SaxEventRecorder recorder) { // Let's remove the two <included> events before // adding the events to the player. List<SaxEvent> saxEventList = recorder.saxEventList; if (saxEventList.size() == 0) { return; } SaxEvent first = saxEventList.get(0); if (first != null && first.qName.equalsIgnoreCase(INCLUDED_TAG)) { saxEventList.remove(0); } SaxEvent last = saxEventList.get(recorder.saxEventList.size() - 1); if (last != null && last.qName.equalsIgnoreCase(INCLUDED_TAG)) { saxEventList.remove(recorder.saxEventList.size() - 1); } } }
true
true
public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { populateSubstitutionProperties(ec); //TO CHECK Should we add the config fragment at end final Collection<ConfigSourceInfo> providers = getFragmentProviders(); List<SaxEvent> consolidatedEventList = new ArrayList<SaxEvent>(); for (ConfigSourceInfo cp : providers) { InputSource is = cp.getConfigProvider().getConfigSource(); try { SaxEventRecorder recorder = new SaxEventRecorder(context); recorder.recordEvents(is); // remove the <included> tag from the beginning and </included> from the end trimHeadAndTail(recorder); consolidatedEventList.addAll(recorder.getSaxEventList()); } catch (JoranException e) { addError("Error while parsing "+cp, e); } finally { close(is); } } // offset = 2, because we need to get past this element as well as the end element ec.getJoranInterpreter().getEventPlayer().addEventsDynamically(consolidatedEventList, 2); }
public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { populateSubstitutionProperties(ec); //TO CHECK Should we add the config fragment at end final Collection<ConfigSourceInfo> providers = getFragmentProviders(); List<SaxEvent> consolidatedEventList = new ArrayList<SaxEvent>(); for (ConfigSourceInfo cp : providers) { InputSource is = cp.getConfigProvider().getConfigSource(); try { SaxEventRecorder recorder = new SaxEventRecorder(context); recorder.recordEvents(is); // remove the <included> tag from the beginning and </included> from the end trimHeadAndTail(recorder); consolidatedEventList.addAll(recorder.getSaxEventList()); } catch (JoranException e) { addError("Error while parsing xml obtained from ["+cp+"]", e); } finally { close(is); } } // offset = 2, because we need to get past this element as well as the end element ec.getJoranInterpreter().getEventPlayer().addEventsDynamically(consolidatedEventList, 2); }
diff --git a/quick-samples/concurrent-test/src/test/java/iwein/samples/test/concurrent/ConcurrentTest.java b/quick-samples/concurrent-test/src/test/java/iwein/samples/test/concurrent/ConcurrentTest.java index 99deab0..668ada1 100644 --- a/quick-samples/concurrent-test/src/test/java/iwein/samples/test/concurrent/ConcurrentTest.java +++ b/quick-samples/concurrent-test/src/test/java/iwein/samples/test/concurrent/ConcurrentTest.java @@ -1,101 +1,101 @@ package iwein.samples.test.concurrent; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.integration.channel.PollableChannel; import org.springframework.integration.core.Message; import org.springframework.integration.core.MessageChannel; import org.springframework.integration.message.MessageBuilder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.concurrent.atomic.AtomicInteger; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; @ContextConfiguration(locations = {"classpath:context.xml"}) @RunWith(SpringJUnit4ClassRunner.class) /** * This is a test to reproduce http://jira.springframework.org/browse/INT-915 */ public class ConcurrentTest { @Autowired @Qualifier("in") MessageChannel in; @Autowired @Qualifier("out") PollableChannel out; @Autowired @Qualifier("errorChannel") PollableChannel err; @Autowired Service service; @Autowired Transformer transformer; private static final int NUMBER_OF_MESSAGES = 200; @Test(timeout = 200000) public void shouldGoThroughPipeline() throws Throwable { for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { in.send(MessageBuilder.withPayload("Payload"+i).build()); } int outputCount = 0; - while (outputCount < NUMBER_OF_MESSAGES) { + int errCount = 0; + while (outputCount+errCount < NUMBER_OF_MESSAGES) { Message<?> received = out.receive(10); if (received != null) { outputCount++; System.out.println("received: "+received.getPayload()); } else { Message<?> message = err.receive(10); if (message != null) { - outputCount++; + errCount++; } } } - assertThat(outputCount, is(NUMBER_OF_MESSAGES)); - assertThat(transformer.timesInvoked.get(), is(NUMBER_OF_MESSAGES)); - assertThat(service.timesInvoked.get(), is(NUMBER_OF_MESSAGES)); + assertThat(outputCount+errCount, is(NUMBER_OF_MESSAGES)); + assertThat(transformer.timesInvoked.get()+service.timesInvoked.get()-errCount, is(NUMBER_OF_MESSAGES)); } public static class Service { private final AtomicInteger timesInvoked = new AtomicInteger(); @ServiceActivator public String serve(String input) { System.out.println("serving: "+input); assertNotNull(input); timesInvoked.incrementAndGet(); if (Math.random() < 0.5) { throw new IllegalArgumentException("zoinks!"); } return input; } } public static class Transformer { private final AtomicInteger timesInvoked = new AtomicInteger(); @org.springframework.integration.annotation.Transformer public String transform(String input) { System.out.println("transforming: "+input); assertNotNull(input); timesInvoked.incrementAndGet(); if (Math.random() < 0.5) { throw new IllegalArgumentException("zoinks!"); } return input; } } }
false
true
public void shouldGoThroughPipeline() throws Throwable { for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { in.send(MessageBuilder.withPayload("Payload"+i).build()); } int outputCount = 0; while (outputCount < NUMBER_OF_MESSAGES) { Message<?> received = out.receive(10); if (received != null) { outputCount++; System.out.println("received: "+received.getPayload()); } else { Message<?> message = err.receive(10); if (message != null) { outputCount++; } } } assertThat(outputCount, is(NUMBER_OF_MESSAGES)); assertThat(transformer.timesInvoked.get(), is(NUMBER_OF_MESSAGES)); assertThat(service.timesInvoked.get(), is(NUMBER_OF_MESSAGES)); }
public void shouldGoThroughPipeline() throws Throwable { for (int i = 0; i < NUMBER_OF_MESSAGES; i++) { in.send(MessageBuilder.withPayload("Payload"+i).build()); } int outputCount = 0; int errCount = 0; while (outputCount+errCount < NUMBER_OF_MESSAGES) { Message<?> received = out.receive(10); if (received != null) { outputCount++; System.out.println("received: "+received.getPayload()); } else { Message<?> message = err.receive(10); if (message != null) { errCount++; } } } assertThat(outputCount+errCount, is(NUMBER_OF_MESSAGES)); assertThat(transformer.timesInvoked.get()+service.timesInvoked.get()-errCount, is(NUMBER_OF_MESSAGES)); }
diff --git a/src/org/geworkbench/engine/skin/Skin.java b/src/org/geworkbench/engine/skin/Skin.java index ad854808..0c544639 100755 --- a/src/org/geworkbench/engine/skin/Skin.java +++ b/src/org/geworkbench/engine/skin/Skin.java @@ -1,783 +1,787 @@ package org.geworkbench.engine.skin; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JToolBar; import javax.swing.KeyStroke; import javax.swing.Timer; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import net.eleritec.docking.DockableAdapter; import net.eleritec.docking.DockingManager; import net.eleritec.docking.DockingPort; import net.eleritec.docking.defaults.ComponentProviderAdapter; import net.eleritec.docking.defaults.DefaultDockingPort; import org.apache.commons.collections15.map.ReferenceMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.geworkbench.bison.datastructure.biocollections.DSDataSet; import org.geworkbench.bison.datastructure.bioobjects.DSBioObject; import org.geworkbench.builtin.projects.Icons; import org.geworkbench.engine.ccm.ComponentConfigurationManagerWindow2; import org.geworkbench.engine.config.Closable; import org.geworkbench.engine.config.GUIFramework; import org.geworkbench.engine.config.PluginDescriptor; import org.geworkbench.engine.config.VisualPlugin; import org.geworkbench.engine.config.rules.GeawConfigObject; import org.geworkbench.engine.management.ComponentRegistry; import org.geworkbench.engine.properties.PropertiesManager; import org.geworkbench.util.FilePathnameUtils; import org.geworkbench.util.JAutoList; /** * <p>Title: Bioworks</p> * <p>Description: Modular Application Framework for Gene Expession, Sequence and Genotype Analysis</p> * <p>Copyright: Copyright (c) 2003 -2004</p> * <p>Company: Columbia University</p> * * @author manjunath at genomecenter dot columbia dot edu * @version $Id$ */ public class Skin extends GUIFramework { private static final String YES = "yes"; private static final String NO = "no"; private static final long serialVersionUID = 3617137568252369693L; static Log log = LogFactory.getLog(Skin.class); private static Map<Component, String> visualRegistry = new HashMap<Component, String>(); private JPanel contentPane; private JLabel statusBar = new JLabel(); private BorderLayout borderLayout1 = new BorderLayout(); private JSplitPane jSplitPane1 = new JSplitPane(); private DefaultDockingPort visualPanel = new DefaultDockingPort(); private JSplitPane jSplitPane3 = new JSplitPane(); private DefaultDockingPort selectionPanel = new DefaultDockingPort(); private JToolBar jToolBar = new JToolBar(); private DefaultDockingPort projectPanel = new DefaultDockingPort(); private Map<String, DefaultDockingPort> areas = new Hashtable<String, DefaultDockingPort>(); private Set<Class<?>> acceptors; private HashMap<Component, Class<?>> mainComponentClass = new HashMap<Component, Class<?>>(); private ReferenceMap<DSDataSet<? extends DSBioObject>, String> visualLastSelected = new ReferenceMap<DSDataSet<? extends DSBioObject>, String>( ReferenceMap.SOFT, ReferenceMap.SOFT); private ReferenceMap<DSDataSet<? extends DSBioObject>, String> selectionLastSelected = new ReferenceMap<DSDataSet<? extends DSBioObject>, String>( ReferenceMap.SOFT, ReferenceMap.SOFT); private ArrayList<DockableImpl> visualDockables = new ArrayList<DockableImpl>(); private ArrayList<DockableImpl> selectorDockables = new ArrayList<DockableImpl>(); private DSDataSet<? extends DSBioObject> currentDataSet; private boolean tabSwappingMode = false; public static final String APP_SIZE_FILE = "appCoords.txt"; public String getVisualLastSelected(DSDataSet<? extends DSBioObject> dataSet) { return visualLastSelected.get(dataSet); } public String getSelectionLastSelected(DSDataSet<? extends DSBioObject> dataSet) { return selectionLastSelected.get(dataSet); } public void setVisualLastSelected(DSDataSet<? extends DSBioObject> dataSet, String component) { if (component != null) { visualLastSelected.put(dataSet, component); } } public void setSelectionLastSelected(DSDataSet<? extends DSBioObject> dataSet, String component) { if (component != null) { selectionLastSelected.put(dataSet, component); } } public Skin() { registerAreas(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Dimension finalSize = getSize(); Point finalLocation = getLocation(); File f = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE); try { PrintWriter out = new PrintWriter(new FileWriter(f)); out.println("" + finalSize.width); out.println("" + finalSize.height); out.println("" + finalLocation.x); out.println("" + finalLocation.y); out.close(); List<Object> list = ComponentRegistry.getRegistry().getComponentsList(); for(Object obj: list) { if ( obj instanceof Closable) ((Closable)obj).closing(); } } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } }); try { jbInit(); } catch (Exception e) { e.printStackTrace(); } setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } private void setApplicationTitle() { MessageFormat format = new MessageFormat(System.getProperty("application.title")); Object[] version = { VERSION }; appTitle = format.format(version); setTitle(appTitle); } private String appTitle = ""; public String getApplicationTitle() { return appTitle; } private void jbInit() throws Exception { contentPane = (JPanel) this.getContentPane(); this.setIconImage(Icons.MICROARRAYS_ICON.getImage()); contentPane.setLayout(borderLayout1); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int guiHeight = 0; int guiWidth = 0; boolean foundSize = false; File sizeFile = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE); if (sizeFile.exists()) { try { BufferedReader in = new BufferedReader(new FileReader(sizeFile)); guiWidth = Integer.parseInt(in.readLine()); guiHeight = Integer.parseInt(in.readLine()); int guiX = Integer.parseInt(in.readLine()); int guiY = Integer.parseInt(in.readLine()); setLocation(guiX, guiY); foundSize = true; } catch (Exception ex) { ex.printStackTrace(); } } if (!foundSize) { guiWidth = (int) (dim.getWidth() * 0.9); guiHeight = (int) (dim.getHeight() * 0.9); this.setLocation((dim.width - guiWidth) / 2, (dim.height - guiHeight) / 2); } setSize(new Dimension(guiWidth, guiHeight)); setApplicationTitle(); statusBar.setBorder(BorderFactory.createEmptyBorder(3, 10, 3, 10)); statusBar.setText(" "); jSplitPane1.setBorder(BorderFactory.createLineBorder(Color.black)); jSplitPane1.setDoubleBuffered(true); jSplitPane1.setContinuousLayout(true); jSplitPane1.setBackground(Color.black); jSplitPane1.setDividerSize(8); jSplitPane1.setOneTouchExpandable(true); jSplitPane1.setResizeWeight(0); jSplitPane3.setOrientation(JSplitPane.VERTICAL_SPLIT); jSplitPane3.setBorder(BorderFactory.createLineBorder(Color.black)); jSplitPane3.setDoubleBuffered(true); jSplitPane3.setContinuousLayout(true); jSplitPane3.setDividerSize(8); jSplitPane3.setOneTouchExpandable(true); jSplitPane3.setResizeWeight(0.1); jSplitPane3.setMinimumSize(new Dimension(0, 0)); JPanel statusBarPanel = new JPanel(); statusBarPanel.setLayout(new BorderLayout() ); statusBarPanel.add(statusBar, BorderLayout.EAST); contentPane.add(statusBarPanel, BorderLayout.SOUTH); contentPane.add(jSplitPane1, BorderLayout.CENTER); jSplitPane1.add(visualPanel, JSplitPane.RIGHT); jSplitPane1.add(jSplitPane3, JSplitPane.LEFT); jSplitPane3.add(selectionPanel, JSplitPane.BOTTOM); jSplitPane3.add(projectPanel, JSplitPane.LEFT); contentPane.add(jToolBar, BorderLayout.NORTH); jSplitPane1.setDividerLocation(230); jSplitPane3.setDividerLocation((int) (guiHeight * 0.35)); visualPanel.setComponentProvider(new ComponentProvider(VISUAL_AREA)); selectionPanel.setComponentProvider(new ComponentProvider(SELECTION_AREA)); projectPanel.setComponentProvider(new ComponentProvider(PROJECT_AREA)); final String CANCEL_DIALOG = "cancel-dialog"; contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), CANCEL_DIALOG); contentPane.getActionMap().put(CANCEL_DIALOG, new AbstractAction() { private static final long serialVersionUID = 6732252343409902879L; public void actionPerformed(ActionEvent event) { chooseComponent(); } });// contentPane.addKeyListener(new KeyAdapter() { final String RCM_DIALOG = "rcm-dialog"; contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0), RCM_DIALOG); contentPane.getActionMap().put(RCM_DIALOG, new AbstractAction() { private static final long serialVersionUID = 3053589598512384113L; public void actionPerformed(ActionEvent event) { loadRCM(); } }); ActionListener timerAction = new ActionListener() { final private static long MEGABYTE = 1024*1024; public void actionPerformed(ActionEvent evt) { Runtime runtime = Runtime.getRuntime(); long total = runtime.totalMemory(); long free = runtime.freeMemory(); long used = total-free; setStatusBarText("Memory: "+used/MEGABYTE+"M Used, "+free/MEGABYTE+"M Free, "+total/MEGABYTE+"M Total."); } }; if(showMemoryUsage) new Timer(10000, timerAction).start(); } private boolean showMemoryUsage = true; private static class DialogResult { public boolean cancelled = false; } void loadRCM(){ ComponentConfigurationManagerWindow2.load(); } void chooseComponent() { if (acceptors == null) { // Get all appropriate acceptors acceptors = new HashSet<Class<?>>(); } // 1) Get all visual components ComponentRegistry registry = ComponentRegistry.getRegistry(); VisualPlugin[] plugins = registry.getModules(VisualPlugin.class); ArrayList<String> availablePlugins = new ArrayList<String>(); for (int i = 0; i < plugins.length; i++) { String name = registry.getDescriptorForPlugin(plugins[i]).getLabel(); for (Class<?> type: acceptors) { if (registry.getDescriptorForPluginClass(type).getLabel().equals(name)) { availablePlugins.add(name); break; } } } final String[] names = availablePlugins.toArray(new String[0]); // 2) Sort alphabetically Arrays.sort(names); // 3) Create dialog with JAutoText (prefix mode) DefaultListModel model = new DefaultListModel(); for (int i = 0; i < names.length; i++) { model.addElement(names[i]); } final JDialog dialog = new JDialog(); final DialogResult dialogResult = new DialogResult(); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dialogResult.cancelled = true; } }); final JAutoList autoList = new JAutoList(model) { private static final long serialVersionUID = -5117126504179347748L; protected void keyPressed(KeyEvent event) { if (event.getKeyChar() == '\n') { if (getHighlightedIndex() == -1 ){ return; } dialogResult.cancelled = false; dialog.dispose(); } else if (event.getKeyChar() == 0x1b) { dialogResult.cancelled = true; dialog.dispose(); } else { super.keyPressed(event); } } protected void elementDoubleClicked(int index, MouseEvent e) { dialogResult.cancelled = false; dialog.dispose(); } }; autoList.setPrefixMode(true); dialog.setTitle("Component"); dialog.getContentPane().add(autoList); dialog.setModal(true); dialog.pack(); dialog.setSize(200, 300); Dimension size = dialog.getSize(); Dimension frameSize = getSize(); int x = getLocationOnScreen().x + (frameSize.width - size.width) / 2; int y = getLocationOnScreen().y + (frameSize.height - size.height) / 2; // 5) Display and get result dialog.setBounds(x, y, size.width, size.height); dialog.setVisible(true); if (!dialogResult.cancelled) { int index = autoList.getHighlightedIndex(); boolean found = false; for (String key : areas.keySet()) { if (areas.get(key) instanceof DefaultDockingPort) { DefaultDockingPort port = (DefaultDockingPort) areas.get(key); if (port.getDockedComponent() instanceof JTabbedPane) { JTabbedPane pane = (JTabbedPane) port.getDockedComponent(); int n = pane.getTabCount(); for (int i = 0; i < n; i++) { String title = pane.getTitleAt(i); if (title.equals(names[index])) { pane.setSelectedIndex(i); pane.getComponentAt(i).requestFocus(); found = true; break; } } if (found) { break; } } } } } } /** * Associates Visual Areas with Component Holders */ protected void registerAreas() { areas.put(VISUAL_AREA, visualPanel); areas.put(SELECTION_AREA, selectionPanel); areas.put(PROJECT_AREA, projectPanel); } /** * Removes the designated <code>visualPlugin</code> from the GUI. * * @param visualPlugin component to be removed */ public void remove(Component visualPluginComponent) { mainComponentClass.remove(visualPluginComponent); visualRegistry.remove(visualPluginComponent); } public String getVisualArea(Component visualPlugin) { return (String) visualRegistry.get(visualPlugin); } @SuppressWarnings("rawtypes") @Override public void addToContainer(String areaName, Component visualPlugin, String pluginName, Class mainPluginClass) { visualPlugin.setName(pluginName); DockableImpl wrapper = new DockableImpl(visualPlugin, pluginName); DockingManager.registerDockable(wrapper); if ( !areaName.equals(GUIFramework.VISUAL_AREA) ) { DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName); port.dock(wrapper, DockingPort.CENTER_REGION); } else { log.debug("Plugin wanting to go to visual or command area: " + pluginName); } visualRegistry.put(visualPlugin, areaName); mainComponentClass.put(visualPlugin, mainPluginClass); } private class DockableImpl extends DockableAdapter { private JPanel wrapper = null; private JLabel initiator = null; private String description = null; private Component plugin = null; private JPanel buttons = new JPanel(); private JPanel topBar = new JPanel(); private JButton docker = new JButton(); private boolean docked = true; private ImageIcon dock_grey = new ImageIcon(Skin.class.getResource("dock_grey.gif")); private ImageIcon dock = new ImageIcon(Skin.class.getResource("dock.gif")); private ImageIcon dock_active = new ImageIcon(Skin.class.getResource("dock_active.gif")); private ImageIcon undock_grey = new ImageIcon(Skin.class.getResource("undock_grey.gif")); private ImageIcon undock = new ImageIcon(Skin.class.getResource("undock.gif")); private ImageIcon undock_active = new ImageIcon(Skin.class.getResource("undock_active.gif")); DockableImpl(Component plugin, String desc) { this.plugin = plugin; wrapper = new JPanel(); docker.setPreferredSize(new Dimension(16, 16)); docker.setBorderPainted(false); docker.setIcon(undock_grey); docker.setRolloverEnabled(true); docker.setRolloverIcon(undock); docker.setPressedIcon(undock_active); docker.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { docker_actionPerformed(e); } }); buttons.setLayout(new GridLayout(1, 3)); buttons.add(docker); initiator = new JLabel(" "); initiator.setForeground(Color.darkGray); initiator.setBackground(Color.getHSBColor(0.0f, 0.0f, 0.6f)); initiator.setOpaque(true); initiator.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent me) { setMoveCursor(me); } public void mouseExited(MouseEvent me) { setDefaultCursor(me); } }); topBar.setLayout(new BorderLayout()); topBar.add(initiator, BorderLayout.CENTER); topBar.add(buttons, BorderLayout.EAST); wrapper.setLayout(new BorderLayout()); wrapper.add(topBar, BorderLayout.NORTH); wrapper.add(plugin, BorderLayout.CENTER); description = desc; } private JFrame frame = null; private void docker_actionPerformed(ActionEvent e) { log.debug("Action performed."); String areaName = getVisualArea(this.getPlugin()); DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName); if (docked) { undock(port); return; } else { redock(port); } } public void undock(final DefaultDockingPort port) { log.debug("Undocking."); port.undock(wrapper); port.reevaluateContainerTree(); port.revalidate(); port.repaint(); docker.setIcon(dock_grey); docker.setRolloverIcon(dock); docker.setPressedIcon(dock_active); docker.setSelected(false); docker.repaint(); frame = new JFrame(description); frame.setUndecorated(false); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { redock(port); } }); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(wrapper, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); frame.repaint(); docked = false; return; } public void redock(DefaultDockingPort port) { if (frame != null) { log.debug("Redocking " + plugin); docker.setIcon(undock_grey); docker.setRolloverIcon(undock); docker.setPressedIcon(undock_active); docker.setSelected(false); port.dock(this, DockingPort.CENTER_REGION); port.reevaluateContainerTree(); port.revalidate(); docked = true; frame.getContentPane().remove(wrapper); frame.dispose(); } } private void setMoveCursor(MouseEvent me) { initiator.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } private void setDefaultCursor(MouseEvent me) { initiator.setCursor(Cursor.getDefaultCursor()); } public Component getDockable() { return wrapper; } public String getDockableDesc() { return description; } public Component getInitiator() { return initiator; } public Component getPlugin() { return plugin; } public void dockingCompleted() { // no-op } } private class ComponentProvider extends ComponentProviderAdapter { private String area; public ComponentProvider(String area) { this.area = area; } // Add change listeners to appropriate areas so public JTabbedPane createTabbedPane() { final JTabbedPane pane = new JTabbedPane(); if (area.equals(VISUAL_AREA)) { pane.addChangeListener(new TabChangeListener(pane, visualLastSelected)); } else if (area.equals(SELECTION_AREA)) { pane.addChangeListener(new TabChangeListener(pane, selectionLastSelected)); } return pane; } } private class TabChangeListener implements ChangeListener { private final JTabbedPane pane; private final ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected; public TabChangeListener(JTabbedPane pane, ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected) { this.pane = pane; this.lastSelected = lastSelected; } public void stateChanged(ChangeEvent e) { if ((currentDataSet != null) && !tabSwappingMode) { int index = pane.getSelectedIndex(); if(index>=0) { lastSelected.put(currentDataSet, pane.getTitleAt(index)); } } } } @SuppressWarnings({ "unchecked", "rawtypes" }) public void setVisualizationType(DSDataSet type) { currentDataSet = type; // These are default acceptors acceptors = ComponentRegistry.getRegistry().getAcceptors(null); if (type != null) { acceptors.addAll(ComponentRegistry.getRegistry().getAcceptors(type.getClass())); } if (type == null) { log.trace("Default acceptors found:"); } else { log.trace("Found the following acceptors for type " + type.getClass()); } // Set up Visual Area tabSwappingMode = true; addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables); selectLastComponent(GUIFramework.VISUAL_AREA, visualLastSelected.get(type)); addAppropriateComponents(acceptors, GUIFramework.SELECTION_AREA, selectorDockables); selectLastComponent(GUIFramework.SELECTION_AREA, selectionLastSelected.get(type)); tabSwappingMode = false; contentPane.revalidate(); contentPane.repaint(); } public void setStatusBarText(String text) { statusBar.setText(text); } private void addAppropriateComponents(Set<Class<?>> acceptors, String screenRegion, ArrayList<DockableImpl> dockables) { DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion); for (DockableImpl dockable : dockables) { dockable.redock(port); } dockables.clear(); port.removeAll(); SortedMap<Integer, Component> tabsToAdd = new TreeMap<Integer, Component>(); for (Component component : visualRegistry.keySet()) { if (visualRegistry.get(component).equals(screenRegion)) { Class<?> mainclass = mainComponentClass.get(component); if (acceptors.contains(mainclass)) { log.trace("Found component in "+screenRegion+" to show: " + mainclass.toString()); PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainclass); - tabsToAdd.put(desc.getPreferredOrder(), component); + int order = desc.getPreferredOrder(); + if(desc.getID().equals("informationPanel")) { + order = 100; // force information panel to behind + } + tabsToAdd.put(order, component); } } } for (Integer tabIndex : tabsToAdd.keySet()) { PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainComponentClass.get(tabsToAdd.get(tabIndex))); Component component = tabsToAdd.get(tabIndex); DockableImpl dockable = new DockableImpl(component, desc.getLabel()); dockables.add(dockable); port.dock(dockable, DockingPort.CENTER_REGION); } port.invalidate(); } private void selectLastComponent(String screenRegion, String selected) { DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion); if (selected != null) { Component docked = port.getDockedComponent(); if (docked instanceof JTabbedPane) { JTabbedPane pane = (JTabbedPane) docked; int n = pane.getTabCount(); for (int i = 0; i < n; i++) { if (selected.equals(pane.getTitleAt(i))) { pane.setSelectedIndex(i); return; } } } } // if no match found selectFirstTab(screenRegion); } // select the first tab private void selectFirstTab(String screenRegion) { DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion); Component docked = port.getDockedComponent(); if (docked instanceof JTabbedPane) { // this is always true JTabbedPane pane = (JTabbedPane) docked; pane.setSelectedIndex(0); } } public void initWelcomeScreen() { PropertiesManager pm = PropertiesManager.getInstance(); try { String showWelcomeScreen = pm.getProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, YES); if(showWelcomeScreen.equalsIgnoreCase(YES)) { showWelcomeScreen(); } else { hideWelcomeScreen(); } } catch (IOException e1) { e1.printStackTrace(); } } static private final String welcomeScreenClassName = "org.geworkbench.engine.WelcomeScreen"; public void showWelcomeScreen() { Class<?> welcomeScreenClass = org.geworkbench.engine.WelcomeScreen.class; ComponentRegistry.getRegistry().addAcceptor(null, org.geworkbench.engine.WelcomeScreen.class); if(acceptors==null) acceptors = ComponentRegistry.getRegistry().getAcceptors(null); acceptors.add(welcomeScreenClass); addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables); PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(welcomeScreenClass); selectLastComponent(GUIFramework.VISUAL_AREA, desc.getLabel()); contentPane.revalidate(); PropertiesManager pm = PropertiesManager.getInstance(); try { pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, YES); } catch (IOException e) { e.printStackTrace(); } GeawConfigObject.enableWelcomeScreenMenu(false); } public void hideWelcomeScreen() { if(acceptors==null) acceptors = ComponentRegistry.getRegistry().getAcceptors(null); for (Class<?> componentClass : ComponentRegistry.getRegistry().getAcceptors(null)) { if ( componentClass.getName().equals(welcomeScreenClassName) ) { acceptors.remove(componentClass); break; } } ComponentRegistry.getRegistry().removeAcceptor(null, welcomeScreenClassName); addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables); contentPane.revalidate(); contentPane.repaint(); PropertiesManager pm = PropertiesManager.getInstance(); try { pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, NO); } catch (IOException e) { e.printStackTrace(); } GeawConfigObject.enableWelcomeScreenMenu(true); } private static final String WELCOME_SCREEN_KEY = "Welcome Screen "; public static final String VERSION = System.getProperty("application.version"); }
true
true
private void jbInit() throws Exception { contentPane = (JPanel) this.getContentPane(); this.setIconImage(Icons.MICROARRAYS_ICON.getImage()); contentPane.setLayout(borderLayout1); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int guiHeight = 0; int guiWidth = 0; boolean foundSize = false; File sizeFile = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE); if (sizeFile.exists()) { try { BufferedReader in = new BufferedReader(new FileReader(sizeFile)); guiWidth = Integer.parseInt(in.readLine()); guiHeight = Integer.parseInt(in.readLine()); int guiX = Integer.parseInt(in.readLine()); int guiY = Integer.parseInt(in.readLine()); setLocation(guiX, guiY); foundSize = true; } catch (Exception ex) { ex.printStackTrace(); } } if (!foundSize) { guiWidth = (int) (dim.getWidth() * 0.9); guiHeight = (int) (dim.getHeight() * 0.9); this.setLocation((dim.width - guiWidth) / 2, (dim.height - guiHeight) / 2); } setSize(new Dimension(guiWidth, guiHeight)); setApplicationTitle(); statusBar.setBorder(BorderFactory.createEmptyBorder(3, 10, 3, 10)); statusBar.setText(" "); jSplitPane1.setBorder(BorderFactory.createLineBorder(Color.black)); jSplitPane1.setDoubleBuffered(true); jSplitPane1.setContinuousLayout(true); jSplitPane1.setBackground(Color.black); jSplitPane1.setDividerSize(8); jSplitPane1.setOneTouchExpandable(true); jSplitPane1.setResizeWeight(0); jSplitPane3.setOrientation(JSplitPane.VERTICAL_SPLIT); jSplitPane3.setBorder(BorderFactory.createLineBorder(Color.black)); jSplitPane3.setDoubleBuffered(true); jSplitPane3.setContinuousLayout(true); jSplitPane3.setDividerSize(8); jSplitPane3.setOneTouchExpandable(true); jSplitPane3.setResizeWeight(0.1); jSplitPane3.setMinimumSize(new Dimension(0, 0)); JPanel statusBarPanel = new JPanel(); statusBarPanel.setLayout(new BorderLayout() ); statusBarPanel.add(statusBar, BorderLayout.EAST); contentPane.add(statusBarPanel, BorderLayout.SOUTH); contentPane.add(jSplitPane1, BorderLayout.CENTER); jSplitPane1.add(visualPanel, JSplitPane.RIGHT); jSplitPane1.add(jSplitPane3, JSplitPane.LEFT); jSplitPane3.add(selectionPanel, JSplitPane.BOTTOM); jSplitPane3.add(projectPanel, JSplitPane.LEFT); contentPane.add(jToolBar, BorderLayout.NORTH); jSplitPane1.setDividerLocation(230); jSplitPane3.setDividerLocation((int) (guiHeight * 0.35)); visualPanel.setComponentProvider(new ComponentProvider(VISUAL_AREA)); selectionPanel.setComponentProvider(new ComponentProvider(SELECTION_AREA)); projectPanel.setComponentProvider(new ComponentProvider(PROJECT_AREA)); final String CANCEL_DIALOG = "cancel-dialog"; contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), CANCEL_DIALOG); contentPane.getActionMap().put(CANCEL_DIALOG, new AbstractAction() { private static final long serialVersionUID = 6732252343409902879L; public void actionPerformed(ActionEvent event) { chooseComponent(); } });// contentPane.addKeyListener(new KeyAdapter() { final String RCM_DIALOG = "rcm-dialog"; contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0), RCM_DIALOG); contentPane.getActionMap().put(RCM_DIALOG, new AbstractAction() { private static final long serialVersionUID = 3053589598512384113L; public void actionPerformed(ActionEvent event) { loadRCM(); } }); ActionListener timerAction = new ActionListener() { final private static long MEGABYTE = 1024*1024; public void actionPerformed(ActionEvent evt) { Runtime runtime = Runtime.getRuntime(); long total = runtime.totalMemory(); long free = runtime.freeMemory(); long used = total-free; setStatusBarText("Memory: "+used/MEGABYTE+"M Used, "+free/MEGABYTE+"M Free, "+total/MEGABYTE+"M Total."); } }; if(showMemoryUsage) new Timer(10000, timerAction).start(); } private boolean showMemoryUsage = true; private static class DialogResult { public boolean cancelled = false; } void loadRCM(){ ComponentConfigurationManagerWindow2.load(); } void chooseComponent() { if (acceptors == null) { // Get all appropriate acceptors acceptors = new HashSet<Class<?>>(); } // 1) Get all visual components ComponentRegistry registry = ComponentRegistry.getRegistry(); VisualPlugin[] plugins = registry.getModules(VisualPlugin.class); ArrayList<String> availablePlugins = new ArrayList<String>(); for (int i = 0; i < plugins.length; i++) { String name = registry.getDescriptorForPlugin(plugins[i]).getLabel(); for (Class<?> type: acceptors) { if (registry.getDescriptorForPluginClass(type).getLabel().equals(name)) { availablePlugins.add(name); break; } } } final String[] names = availablePlugins.toArray(new String[0]); // 2) Sort alphabetically Arrays.sort(names); // 3) Create dialog with JAutoText (prefix mode) DefaultListModel model = new DefaultListModel(); for (int i = 0; i < names.length; i++) { model.addElement(names[i]); } final JDialog dialog = new JDialog(); final DialogResult dialogResult = new DialogResult(); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dialogResult.cancelled = true; } }); final JAutoList autoList = new JAutoList(model) { private static final long serialVersionUID = -5117126504179347748L; protected void keyPressed(KeyEvent event) { if (event.getKeyChar() == '\n') { if (getHighlightedIndex() == -1 ){ return; } dialogResult.cancelled = false; dialog.dispose(); } else if (event.getKeyChar() == 0x1b) { dialogResult.cancelled = true; dialog.dispose(); } else { super.keyPressed(event); } } protected void elementDoubleClicked(int index, MouseEvent e) { dialogResult.cancelled = false; dialog.dispose(); } }; autoList.setPrefixMode(true); dialog.setTitle("Component"); dialog.getContentPane().add(autoList); dialog.setModal(true); dialog.pack(); dialog.setSize(200, 300); Dimension size = dialog.getSize(); Dimension frameSize = getSize(); int x = getLocationOnScreen().x + (frameSize.width - size.width) / 2; int y = getLocationOnScreen().y + (frameSize.height - size.height) / 2; // 5) Display and get result dialog.setBounds(x, y, size.width, size.height); dialog.setVisible(true); if (!dialogResult.cancelled) { int index = autoList.getHighlightedIndex(); boolean found = false; for (String key : areas.keySet()) { if (areas.get(key) instanceof DefaultDockingPort) { DefaultDockingPort port = (DefaultDockingPort) areas.get(key); if (port.getDockedComponent() instanceof JTabbedPane) { JTabbedPane pane = (JTabbedPane) port.getDockedComponent(); int n = pane.getTabCount(); for (int i = 0; i < n; i++) { String title = pane.getTitleAt(i); if (title.equals(names[index])) { pane.setSelectedIndex(i); pane.getComponentAt(i).requestFocus(); found = true; break; } } if (found) { break; } } } } } } /** * Associates Visual Areas with Component Holders */ protected void registerAreas() { areas.put(VISUAL_AREA, visualPanel); areas.put(SELECTION_AREA, selectionPanel); areas.put(PROJECT_AREA, projectPanel); } /** * Removes the designated <code>visualPlugin</code> from the GUI. * * @param visualPlugin component to be removed */ public void remove(Component visualPluginComponent) { mainComponentClass.remove(visualPluginComponent); visualRegistry.remove(visualPluginComponent); } public String getVisualArea(Component visualPlugin) { return (String) visualRegistry.get(visualPlugin); } @SuppressWarnings("rawtypes") @Override public void addToContainer(String areaName, Component visualPlugin, String pluginName, Class mainPluginClass) { visualPlugin.setName(pluginName); DockableImpl wrapper = new DockableImpl(visualPlugin, pluginName); DockingManager.registerDockable(wrapper); if ( !areaName.equals(GUIFramework.VISUAL_AREA) ) { DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName); port.dock(wrapper, DockingPort.CENTER_REGION); } else { log.debug("Plugin wanting to go to visual or command area: " + pluginName); } visualRegistry.put(visualPlugin, areaName); mainComponentClass.put(visualPlugin, mainPluginClass); } private class DockableImpl extends DockableAdapter { private JPanel wrapper = null; private JLabel initiator = null; private String description = null; private Component plugin = null; private JPanel buttons = new JPanel(); private JPanel topBar = new JPanel(); private JButton docker = new JButton(); private boolean docked = true; private ImageIcon dock_grey = new ImageIcon(Skin.class.getResource("dock_grey.gif")); private ImageIcon dock = new ImageIcon(Skin.class.getResource("dock.gif")); private ImageIcon dock_active = new ImageIcon(Skin.class.getResource("dock_active.gif")); private ImageIcon undock_grey = new ImageIcon(Skin.class.getResource("undock_grey.gif")); private ImageIcon undock = new ImageIcon(Skin.class.getResource("undock.gif")); private ImageIcon undock_active = new ImageIcon(Skin.class.getResource("undock_active.gif")); DockableImpl(Component plugin, String desc) { this.plugin = plugin; wrapper = new JPanel(); docker.setPreferredSize(new Dimension(16, 16)); docker.setBorderPainted(false); docker.setIcon(undock_grey); docker.setRolloverEnabled(true); docker.setRolloverIcon(undock); docker.setPressedIcon(undock_active); docker.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { docker_actionPerformed(e); } }); buttons.setLayout(new GridLayout(1, 3)); buttons.add(docker); initiator = new JLabel(" "); initiator.setForeground(Color.darkGray); initiator.setBackground(Color.getHSBColor(0.0f, 0.0f, 0.6f)); initiator.setOpaque(true); initiator.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent me) { setMoveCursor(me); } public void mouseExited(MouseEvent me) { setDefaultCursor(me); } }); topBar.setLayout(new BorderLayout()); topBar.add(initiator, BorderLayout.CENTER); topBar.add(buttons, BorderLayout.EAST); wrapper.setLayout(new BorderLayout()); wrapper.add(topBar, BorderLayout.NORTH); wrapper.add(plugin, BorderLayout.CENTER); description = desc; } private JFrame frame = null; private void docker_actionPerformed(ActionEvent e) { log.debug("Action performed."); String areaName = getVisualArea(this.getPlugin()); DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName); if (docked) { undock(port); return; } else { redock(port); } } public void undock(final DefaultDockingPort port) { log.debug("Undocking."); port.undock(wrapper); port.reevaluateContainerTree(); port.revalidate(); port.repaint(); docker.setIcon(dock_grey); docker.setRolloverIcon(dock); docker.setPressedIcon(dock_active); docker.setSelected(false); docker.repaint(); frame = new JFrame(description); frame.setUndecorated(false); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { redock(port); } }); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(wrapper, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); frame.repaint(); docked = false; return; } public void redock(DefaultDockingPort port) { if (frame != null) { log.debug("Redocking " + plugin); docker.setIcon(undock_grey); docker.setRolloverIcon(undock); docker.setPressedIcon(undock_active); docker.setSelected(false); port.dock(this, DockingPort.CENTER_REGION); port.reevaluateContainerTree(); port.revalidate(); docked = true; frame.getContentPane().remove(wrapper); frame.dispose(); } } private void setMoveCursor(MouseEvent me) { initiator.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } private void setDefaultCursor(MouseEvent me) { initiator.setCursor(Cursor.getDefaultCursor()); } public Component getDockable() { return wrapper; } public String getDockableDesc() { return description; } public Component getInitiator() { return initiator; } public Component getPlugin() { return plugin; } public void dockingCompleted() { // no-op } } private class ComponentProvider extends ComponentProviderAdapter { private String area; public ComponentProvider(String area) { this.area = area; } // Add change listeners to appropriate areas so public JTabbedPane createTabbedPane() { final JTabbedPane pane = new JTabbedPane(); if (area.equals(VISUAL_AREA)) { pane.addChangeListener(new TabChangeListener(pane, visualLastSelected)); } else if (area.equals(SELECTION_AREA)) { pane.addChangeListener(new TabChangeListener(pane, selectionLastSelected)); } return pane; } } private class TabChangeListener implements ChangeListener { private final JTabbedPane pane; private final ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected; public TabChangeListener(JTabbedPane pane, ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected) { this.pane = pane; this.lastSelected = lastSelected; } public void stateChanged(ChangeEvent e) { if ((currentDataSet != null) && !tabSwappingMode) { int index = pane.getSelectedIndex(); if(index>=0) { lastSelected.put(currentDataSet, pane.getTitleAt(index)); } } } } @SuppressWarnings({ "unchecked", "rawtypes" }) public void setVisualizationType(DSDataSet type) { currentDataSet = type; // These are default acceptors acceptors = ComponentRegistry.getRegistry().getAcceptors(null); if (type != null) { acceptors.addAll(ComponentRegistry.getRegistry().getAcceptors(type.getClass())); } if (type == null) { log.trace("Default acceptors found:"); } else { log.trace("Found the following acceptors for type " + type.getClass()); } // Set up Visual Area tabSwappingMode = true; addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables); selectLastComponent(GUIFramework.VISUAL_AREA, visualLastSelected.get(type)); addAppropriateComponents(acceptors, GUIFramework.SELECTION_AREA, selectorDockables); selectLastComponent(GUIFramework.SELECTION_AREA, selectionLastSelected.get(type)); tabSwappingMode = false; contentPane.revalidate(); contentPane.repaint(); } public void setStatusBarText(String text) { statusBar.setText(text); } private void addAppropriateComponents(Set<Class<?>> acceptors, String screenRegion, ArrayList<DockableImpl> dockables) { DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion); for (DockableImpl dockable : dockables) { dockable.redock(port); } dockables.clear(); port.removeAll(); SortedMap<Integer, Component> tabsToAdd = new TreeMap<Integer, Component>(); for (Component component : visualRegistry.keySet()) { if (visualRegistry.get(component).equals(screenRegion)) { Class<?> mainclass = mainComponentClass.get(component); if (acceptors.contains(mainclass)) { log.trace("Found component in "+screenRegion+" to show: " + mainclass.toString()); PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainclass); tabsToAdd.put(desc.getPreferredOrder(), component); } } } for (Integer tabIndex : tabsToAdd.keySet()) { PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainComponentClass.get(tabsToAdd.get(tabIndex))); Component component = tabsToAdd.get(tabIndex); DockableImpl dockable = new DockableImpl(component, desc.getLabel()); dockables.add(dockable); port.dock(dockable, DockingPort.CENTER_REGION); } port.invalidate(); } private void selectLastComponent(String screenRegion, String selected) { DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion); if (selected != null) { Component docked = port.getDockedComponent(); if (docked instanceof JTabbedPane) { JTabbedPane pane = (JTabbedPane) docked; int n = pane.getTabCount(); for (int i = 0; i < n; i++) { if (selected.equals(pane.getTitleAt(i))) { pane.setSelectedIndex(i); return; } } } } // if no match found selectFirstTab(screenRegion); } // select the first tab private void selectFirstTab(String screenRegion) { DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion); Component docked = port.getDockedComponent(); if (docked instanceof JTabbedPane) { // this is always true JTabbedPane pane = (JTabbedPane) docked; pane.setSelectedIndex(0); } } public void initWelcomeScreen() { PropertiesManager pm = PropertiesManager.getInstance(); try { String showWelcomeScreen = pm.getProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, YES); if(showWelcomeScreen.equalsIgnoreCase(YES)) { showWelcomeScreen(); } else { hideWelcomeScreen(); } } catch (IOException e1) { e1.printStackTrace(); } } static private final String welcomeScreenClassName = "org.geworkbench.engine.WelcomeScreen"; public void showWelcomeScreen() { Class<?> welcomeScreenClass = org.geworkbench.engine.WelcomeScreen.class; ComponentRegistry.getRegistry().addAcceptor(null, org.geworkbench.engine.WelcomeScreen.class); if(acceptors==null) acceptors = ComponentRegistry.getRegistry().getAcceptors(null); acceptors.add(welcomeScreenClass); addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables); PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(welcomeScreenClass); selectLastComponent(GUIFramework.VISUAL_AREA, desc.getLabel()); contentPane.revalidate(); PropertiesManager pm = PropertiesManager.getInstance(); try { pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, YES); } catch (IOException e) { e.printStackTrace(); } GeawConfigObject.enableWelcomeScreenMenu(false); } public void hideWelcomeScreen() { if(acceptors==null) acceptors = ComponentRegistry.getRegistry().getAcceptors(null); for (Class<?> componentClass : ComponentRegistry.getRegistry().getAcceptors(null)) { if ( componentClass.getName().equals(welcomeScreenClassName) ) { acceptors.remove(componentClass); break; } } ComponentRegistry.getRegistry().removeAcceptor(null, welcomeScreenClassName); addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables); contentPane.revalidate(); contentPane.repaint(); PropertiesManager pm = PropertiesManager.getInstance(); try { pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, NO); } catch (IOException e) { e.printStackTrace(); } GeawConfigObject.enableWelcomeScreenMenu(true); } private static final String WELCOME_SCREEN_KEY = "Welcome Screen "; public static final String VERSION = System.getProperty("application.version"); }
private void jbInit() throws Exception { contentPane = (JPanel) this.getContentPane(); this.setIconImage(Icons.MICROARRAYS_ICON.getImage()); contentPane.setLayout(borderLayout1); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int guiHeight = 0; int guiWidth = 0; boolean foundSize = false; File sizeFile = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE); if (sizeFile.exists()) { try { BufferedReader in = new BufferedReader(new FileReader(sizeFile)); guiWidth = Integer.parseInt(in.readLine()); guiHeight = Integer.parseInt(in.readLine()); int guiX = Integer.parseInt(in.readLine()); int guiY = Integer.parseInt(in.readLine()); setLocation(guiX, guiY); foundSize = true; } catch (Exception ex) { ex.printStackTrace(); } } if (!foundSize) { guiWidth = (int) (dim.getWidth() * 0.9); guiHeight = (int) (dim.getHeight() * 0.9); this.setLocation((dim.width - guiWidth) / 2, (dim.height - guiHeight) / 2); } setSize(new Dimension(guiWidth, guiHeight)); setApplicationTitle(); statusBar.setBorder(BorderFactory.createEmptyBorder(3, 10, 3, 10)); statusBar.setText(" "); jSplitPane1.setBorder(BorderFactory.createLineBorder(Color.black)); jSplitPane1.setDoubleBuffered(true); jSplitPane1.setContinuousLayout(true); jSplitPane1.setBackground(Color.black); jSplitPane1.setDividerSize(8); jSplitPane1.setOneTouchExpandable(true); jSplitPane1.setResizeWeight(0); jSplitPane3.setOrientation(JSplitPane.VERTICAL_SPLIT); jSplitPane3.setBorder(BorderFactory.createLineBorder(Color.black)); jSplitPane3.setDoubleBuffered(true); jSplitPane3.setContinuousLayout(true); jSplitPane3.setDividerSize(8); jSplitPane3.setOneTouchExpandable(true); jSplitPane3.setResizeWeight(0.1); jSplitPane3.setMinimumSize(new Dimension(0, 0)); JPanel statusBarPanel = new JPanel(); statusBarPanel.setLayout(new BorderLayout() ); statusBarPanel.add(statusBar, BorderLayout.EAST); contentPane.add(statusBarPanel, BorderLayout.SOUTH); contentPane.add(jSplitPane1, BorderLayout.CENTER); jSplitPane1.add(visualPanel, JSplitPane.RIGHT); jSplitPane1.add(jSplitPane3, JSplitPane.LEFT); jSplitPane3.add(selectionPanel, JSplitPane.BOTTOM); jSplitPane3.add(projectPanel, JSplitPane.LEFT); contentPane.add(jToolBar, BorderLayout.NORTH); jSplitPane1.setDividerLocation(230); jSplitPane3.setDividerLocation((int) (guiHeight * 0.35)); visualPanel.setComponentProvider(new ComponentProvider(VISUAL_AREA)); selectionPanel.setComponentProvider(new ComponentProvider(SELECTION_AREA)); projectPanel.setComponentProvider(new ComponentProvider(PROJECT_AREA)); final String CANCEL_DIALOG = "cancel-dialog"; contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), CANCEL_DIALOG); contentPane.getActionMap().put(CANCEL_DIALOG, new AbstractAction() { private static final long serialVersionUID = 6732252343409902879L; public void actionPerformed(ActionEvent event) { chooseComponent(); } });// contentPane.addKeyListener(new KeyAdapter() { final String RCM_DIALOG = "rcm-dialog"; contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0), RCM_DIALOG); contentPane.getActionMap().put(RCM_DIALOG, new AbstractAction() { private static final long serialVersionUID = 3053589598512384113L; public void actionPerformed(ActionEvent event) { loadRCM(); } }); ActionListener timerAction = new ActionListener() { final private static long MEGABYTE = 1024*1024; public void actionPerformed(ActionEvent evt) { Runtime runtime = Runtime.getRuntime(); long total = runtime.totalMemory(); long free = runtime.freeMemory(); long used = total-free; setStatusBarText("Memory: "+used/MEGABYTE+"M Used, "+free/MEGABYTE+"M Free, "+total/MEGABYTE+"M Total."); } }; if(showMemoryUsage) new Timer(10000, timerAction).start(); } private boolean showMemoryUsage = true; private static class DialogResult { public boolean cancelled = false; } void loadRCM(){ ComponentConfigurationManagerWindow2.load(); } void chooseComponent() { if (acceptors == null) { // Get all appropriate acceptors acceptors = new HashSet<Class<?>>(); } // 1) Get all visual components ComponentRegistry registry = ComponentRegistry.getRegistry(); VisualPlugin[] plugins = registry.getModules(VisualPlugin.class); ArrayList<String> availablePlugins = new ArrayList<String>(); for (int i = 0; i < plugins.length; i++) { String name = registry.getDescriptorForPlugin(plugins[i]).getLabel(); for (Class<?> type: acceptors) { if (registry.getDescriptorForPluginClass(type).getLabel().equals(name)) { availablePlugins.add(name); break; } } } final String[] names = availablePlugins.toArray(new String[0]); // 2) Sort alphabetically Arrays.sort(names); // 3) Create dialog with JAutoText (prefix mode) DefaultListModel model = new DefaultListModel(); for (int i = 0; i < names.length; i++) { model.addElement(names[i]); } final JDialog dialog = new JDialog(); final DialogResult dialogResult = new DialogResult(); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dialogResult.cancelled = true; } }); final JAutoList autoList = new JAutoList(model) { private static final long serialVersionUID = -5117126504179347748L; protected void keyPressed(KeyEvent event) { if (event.getKeyChar() == '\n') { if (getHighlightedIndex() == -1 ){ return; } dialogResult.cancelled = false; dialog.dispose(); } else if (event.getKeyChar() == 0x1b) { dialogResult.cancelled = true; dialog.dispose(); } else { super.keyPressed(event); } } protected void elementDoubleClicked(int index, MouseEvent e) { dialogResult.cancelled = false; dialog.dispose(); } }; autoList.setPrefixMode(true); dialog.setTitle("Component"); dialog.getContentPane().add(autoList); dialog.setModal(true); dialog.pack(); dialog.setSize(200, 300); Dimension size = dialog.getSize(); Dimension frameSize = getSize(); int x = getLocationOnScreen().x + (frameSize.width - size.width) / 2; int y = getLocationOnScreen().y + (frameSize.height - size.height) / 2; // 5) Display and get result dialog.setBounds(x, y, size.width, size.height); dialog.setVisible(true); if (!dialogResult.cancelled) { int index = autoList.getHighlightedIndex(); boolean found = false; for (String key : areas.keySet()) { if (areas.get(key) instanceof DefaultDockingPort) { DefaultDockingPort port = (DefaultDockingPort) areas.get(key); if (port.getDockedComponent() instanceof JTabbedPane) { JTabbedPane pane = (JTabbedPane) port.getDockedComponent(); int n = pane.getTabCount(); for (int i = 0; i < n; i++) { String title = pane.getTitleAt(i); if (title.equals(names[index])) { pane.setSelectedIndex(i); pane.getComponentAt(i).requestFocus(); found = true; break; } } if (found) { break; } } } } } } /** * Associates Visual Areas with Component Holders */ protected void registerAreas() { areas.put(VISUAL_AREA, visualPanel); areas.put(SELECTION_AREA, selectionPanel); areas.put(PROJECT_AREA, projectPanel); } /** * Removes the designated <code>visualPlugin</code> from the GUI. * * @param visualPlugin component to be removed */ public void remove(Component visualPluginComponent) { mainComponentClass.remove(visualPluginComponent); visualRegistry.remove(visualPluginComponent); } public String getVisualArea(Component visualPlugin) { return (String) visualRegistry.get(visualPlugin); } @SuppressWarnings("rawtypes") @Override public void addToContainer(String areaName, Component visualPlugin, String pluginName, Class mainPluginClass) { visualPlugin.setName(pluginName); DockableImpl wrapper = new DockableImpl(visualPlugin, pluginName); DockingManager.registerDockable(wrapper); if ( !areaName.equals(GUIFramework.VISUAL_AREA) ) { DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName); port.dock(wrapper, DockingPort.CENTER_REGION); } else { log.debug("Plugin wanting to go to visual or command area: " + pluginName); } visualRegistry.put(visualPlugin, areaName); mainComponentClass.put(visualPlugin, mainPluginClass); } private class DockableImpl extends DockableAdapter { private JPanel wrapper = null; private JLabel initiator = null; private String description = null; private Component plugin = null; private JPanel buttons = new JPanel(); private JPanel topBar = new JPanel(); private JButton docker = new JButton(); private boolean docked = true; private ImageIcon dock_grey = new ImageIcon(Skin.class.getResource("dock_grey.gif")); private ImageIcon dock = new ImageIcon(Skin.class.getResource("dock.gif")); private ImageIcon dock_active = new ImageIcon(Skin.class.getResource("dock_active.gif")); private ImageIcon undock_grey = new ImageIcon(Skin.class.getResource("undock_grey.gif")); private ImageIcon undock = new ImageIcon(Skin.class.getResource("undock.gif")); private ImageIcon undock_active = new ImageIcon(Skin.class.getResource("undock_active.gif")); DockableImpl(Component plugin, String desc) { this.plugin = plugin; wrapper = new JPanel(); docker.setPreferredSize(new Dimension(16, 16)); docker.setBorderPainted(false); docker.setIcon(undock_grey); docker.setRolloverEnabled(true); docker.setRolloverIcon(undock); docker.setPressedIcon(undock_active); docker.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { docker_actionPerformed(e); } }); buttons.setLayout(new GridLayout(1, 3)); buttons.add(docker); initiator = new JLabel(" "); initiator.setForeground(Color.darkGray); initiator.setBackground(Color.getHSBColor(0.0f, 0.0f, 0.6f)); initiator.setOpaque(true); initiator.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent me) { setMoveCursor(me); } public void mouseExited(MouseEvent me) { setDefaultCursor(me); } }); topBar.setLayout(new BorderLayout()); topBar.add(initiator, BorderLayout.CENTER); topBar.add(buttons, BorderLayout.EAST); wrapper.setLayout(new BorderLayout()); wrapper.add(topBar, BorderLayout.NORTH); wrapper.add(plugin, BorderLayout.CENTER); description = desc; } private JFrame frame = null; private void docker_actionPerformed(ActionEvent e) { log.debug("Action performed."); String areaName = getVisualArea(this.getPlugin()); DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName); if (docked) { undock(port); return; } else { redock(port); } } public void undock(final DefaultDockingPort port) { log.debug("Undocking."); port.undock(wrapper); port.reevaluateContainerTree(); port.revalidate(); port.repaint(); docker.setIcon(dock_grey); docker.setRolloverIcon(dock); docker.setPressedIcon(dock_active); docker.setSelected(false); docker.repaint(); frame = new JFrame(description); frame.setUndecorated(false); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { redock(port); } }); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(wrapper, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); frame.repaint(); docked = false; return; } public void redock(DefaultDockingPort port) { if (frame != null) { log.debug("Redocking " + plugin); docker.setIcon(undock_grey); docker.setRolloverIcon(undock); docker.setPressedIcon(undock_active); docker.setSelected(false); port.dock(this, DockingPort.CENTER_REGION); port.reevaluateContainerTree(); port.revalidate(); docked = true; frame.getContentPane().remove(wrapper); frame.dispose(); } } private void setMoveCursor(MouseEvent me) { initiator.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } private void setDefaultCursor(MouseEvent me) { initiator.setCursor(Cursor.getDefaultCursor()); } public Component getDockable() { return wrapper; } public String getDockableDesc() { return description; } public Component getInitiator() { return initiator; } public Component getPlugin() { return plugin; } public void dockingCompleted() { // no-op } } private class ComponentProvider extends ComponentProviderAdapter { private String area; public ComponentProvider(String area) { this.area = area; } // Add change listeners to appropriate areas so public JTabbedPane createTabbedPane() { final JTabbedPane pane = new JTabbedPane(); if (area.equals(VISUAL_AREA)) { pane.addChangeListener(new TabChangeListener(pane, visualLastSelected)); } else if (area.equals(SELECTION_AREA)) { pane.addChangeListener(new TabChangeListener(pane, selectionLastSelected)); } return pane; } } private class TabChangeListener implements ChangeListener { private final JTabbedPane pane; private final ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected; public TabChangeListener(JTabbedPane pane, ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected) { this.pane = pane; this.lastSelected = lastSelected; } public void stateChanged(ChangeEvent e) { if ((currentDataSet != null) && !tabSwappingMode) { int index = pane.getSelectedIndex(); if(index>=0) { lastSelected.put(currentDataSet, pane.getTitleAt(index)); } } } } @SuppressWarnings({ "unchecked", "rawtypes" }) public void setVisualizationType(DSDataSet type) { currentDataSet = type; // These are default acceptors acceptors = ComponentRegistry.getRegistry().getAcceptors(null); if (type != null) { acceptors.addAll(ComponentRegistry.getRegistry().getAcceptors(type.getClass())); } if (type == null) { log.trace("Default acceptors found:"); } else { log.trace("Found the following acceptors for type " + type.getClass()); } // Set up Visual Area tabSwappingMode = true; addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables); selectLastComponent(GUIFramework.VISUAL_AREA, visualLastSelected.get(type)); addAppropriateComponents(acceptors, GUIFramework.SELECTION_AREA, selectorDockables); selectLastComponent(GUIFramework.SELECTION_AREA, selectionLastSelected.get(type)); tabSwappingMode = false; contentPane.revalidate(); contentPane.repaint(); } public void setStatusBarText(String text) { statusBar.setText(text); } private void addAppropriateComponents(Set<Class<?>> acceptors, String screenRegion, ArrayList<DockableImpl> dockables) { DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion); for (DockableImpl dockable : dockables) { dockable.redock(port); } dockables.clear(); port.removeAll(); SortedMap<Integer, Component> tabsToAdd = new TreeMap<Integer, Component>(); for (Component component : visualRegistry.keySet()) { if (visualRegistry.get(component).equals(screenRegion)) { Class<?> mainclass = mainComponentClass.get(component); if (acceptors.contains(mainclass)) { log.trace("Found component in "+screenRegion+" to show: " + mainclass.toString()); PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainclass); int order = desc.getPreferredOrder(); if(desc.getID().equals("informationPanel")) { order = 100; // force information panel to behind } tabsToAdd.put(order, component); } } } for (Integer tabIndex : tabsToAdd.keySet()) { PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainComponentClass.get(tabsToAdd.get(tabIndex))); Component component = tabsToAdd.get(tabIndex); DockableImpl dockable = new DockableImpl(component, desc.getLabel()); dockables.add(dockable); port.dock(dockable, DockingPort.CENTER_REGION); } port.invalidate(); } private void selectLastComponent(String screenRegion, String selected) { DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion); if (selected != null) { Component docked = port.getDockedComponent(); if (docked instanceof JTabbedPane) { JTabbedPane pane = (JTabbedPane) docked; int n = pane.getTabCount(); for (int i = 0; i < n; i++) { if (selected.equals(pane.getTitleAt(i))) { pane.setSelectedIndex(i); return; } } } } // if no match found selectFirstTab(screenRegion); } // select the first tab private void selectFirstTab(String screenRegion) { DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion); Component docked = port.getDockedComponent(); if (docked instanceof JTabbedPane) { // this is always true JTabbedPane pane = (JTabbedPane) docked; pane.setSelectedIndex(0); } } public void initWelcomeScreen() { PropertiesManager pm = PropertiesManager.getInstance(); try { String showWelcomeScreen = pm.getProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, YES); if(showWelcomeScreen.equalsIgnoreCase(YES)) { showWelcomeScreen(); } else { hideWelcomeScreen(); } } catch (IOException e1) { e1.printStackTrace(); } } static private final String welcomeScreenClassName = "org.geworkbench.engine.WelcomeScreen"; public void showWelcomeScreen() { Class<?> welcomeScreenClass = org.geworkbench.engine.WelcomeScreen.class; ComponentRegistry.getRegistry().addAcceptor(null, org.geworkbench.engine.WelcomeScreen.class); if(acceptors==null) acceptors = ComponentRegistry.getRegistry().getAcceptors(null); acceptors.add(welcomeScreenClass); addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables); PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(welcomeScreenClass); selectLastComponent(GUIFramework.VISUAL_AREA, desc.getLabel()); contentPane.revalidate(); PropertiesManager pm = PropertiesManager.getInstance(); try { pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, YES); } catch (IOException e) { e.printStackTrace(); } GeawConfigObject.enableWelcomeScreenMenu(false); } public void hideWelcomeScreen() { if(acceptors==null) acceptors = ComponentRegistry.getRegistry().getAcceptors(null); for (Class<?> componentClass : ComponentRegistry.getRegistry().getAcceptors(null)) { if ( componentClass.getName().equals(welcomeScreenClassName) ) { acceptors.remove(componentClass); break; } } ComponentRegistry.getRegistry().removeAcceptor(null, welcomeScreenClassName); addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables); contentPane.revalidate(); contentPane.repaint(); PropertiesManager pm = PropertiesManager.getInstance(); try { pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, NO); } catch (IOException e) { e.printStackTrace(); } GeawConfigObject.enableWelcomeScreenMenu(true); } private static final String WELCOME_SCREEN_KEY = "Welcome Screen "; public static final String VERSION = System.getProperty("application.version"); }
diff --git a/src/org/apache/xerces/impl/xpath/regex/ParserForXMLSchema.java b/src/org/apache/xerces/impl/xpath/regex/ParserForXMLSchema.java index 22d747020..84c993847 100644 --- a/src/org/apache/xerces/impl/xpath/regex/ParserForXMLSchema.java +++ b/src/org/apache/xerces/impl/xpath/regex/ParserForXMLSchema.java @@ -1,509 +1,509 @@ /* * 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.xpath.regex; import java.util.Hashtable; import java.util.Locale; /** * A regular expression parser for the XML Schema. * * @xerces.internal * * @author TAMURA Kent &lt;[email protected]&gt; * @version $Id$ */ class ParserForXMLSchema extends RegexParser { public ParserForXMLSchema() { //this.setLocale(Locale.getDefault()); } public ParserForXMLSchema(Locale locale) { super(locale); } Token processCaret() throws ParseException { this.next(); return Token.createChar('^'); } Token processDollar() throws ParseException { this.next(); return Token.createChar('$'); } Token processLookahead() throws ParseException { throw ex("parser.process.1", this.offset); } Token processNegativelookahead() throws ParseException { throw ex("parser.process.1", this.offset); } Token processLookbehind() throws ParseException { throw ex("parser.process.1", this.offset); } Token processNegativelookbehind() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_A() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_Z() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_z() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_b() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_B() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_lt() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_gt() throws ParseException { throw ex("parser.process.1", this.offset); } Token processStar(Token tok) throws ParseException { this.next(); return Token.createClosure(tok); } Token processPlus(Token tok) throws ParseException { // X+ -> XX* this.next(); return Token.createConcat(tok, Token.createClosure(tok)); } Token processQuestion(Token tok) throws ParseException { // X? -> X| this.next(); Token par = Token.createUnion(); par.addChild(tok); par.addChild(Token.createEmpty()); return par; } boolean checkQuestion(int off) { return false; } Token processParen() throws ParseException { this.next(); Token tok = Token.createParen(this.parseRegex(), 0); if (this.read() != T_RPAREN) throw ex("parser.factor.1", this.offset-1); this.next(); // Skips ')' return tok; } Token processParen2() throws ParseException { throw ex("parser.process.1", this.offset); } Token processCondition() throws ParseException { throw ex("parser.process.1", this.offset); } Token processModifiers() throws ParseException { throw ex("parser.process.1", this.offset); } Token processIndependent() throws ParseException { throw ex("parser.process.1", this.offset); } Token processBacksolidus_c() throws ParseException { this.next(); return this.getTokenForShorthand('c'); } Token processBacksolidus_C() throws ParseException { this.next(); return this.getTokenForShorthand('C'); } Token processBacksolidus_i() throws ParseException { this.next(); return this.getTokenForShorthand('i'); } Token processBacksolidus_I() throws ParseException { this.next(); return this.getTokenForShorthand('I'); } Token processBacksolidus_g() throws ParseException { throw this.ex("parser.process.1", this.offset-2); } Token processBacksolidus_X() throws ParseException { throw ex("parser.process.1", this.offset-2); } Token processBackreference() throws ParseException { throw ex("parser.process.1", this.offset-4); } int processCIinCharacterClass(RangeToken tok, int c) { tok.mergeRanges(this.getTokenForShorthand(c)); return -1; } /** * Parses a character-class-expression, not a character-class-escape. * * c-c-expression ::= '[' c-group ']' * c-group ::= positive-c-group | negative-c-group | c-c-subtraction * positive-c-group ::= (c-range | c-c-escape)+ * negative-c-group ::= '^' positive-c-group * c-c-subtraction ::= (positive-c-group | negative-c-group) subtraction * subtraction ::= '-' c-c-expression * c-range ::= single-range | from-to-range * single-range ::= multi-c-escape | category-c-escape | block-c-escape | &lt;any XML char&gt; * cc-normal-c ::= &lt;any character except [, ], \&gt; * from-to-range ::= cc-normal-c '-' cc-normal-c * * @param useNrage Ignored. * @return This returns no NrageToken. */ protected RangeToken parseCharacterClass(boolean useNrange) throws ParseException { this.setContext(S_INBRACKETS); this.next(); // '[' boolean nrange = false; boolean wasDecoded = false; // used to detect if the last - was escaped. RangeToken base = null; RangeToken tok; if (this.read() == T_CHAR && this.chardata == '^') { nrange = true; this.next(); // '^' base = Token.createRange(); base.addRange(0, Token.UTF16_MAX); tok = Token.createRange(); } else { tok = Token.createRange(); } int type; boolean firstloop = true; while ((type = this.read()) != T_EOF) { // Don't use 'cotinue' for this loop. wasDecoded = false; // single-range | from-to-range | subtraction if (type == T_CHAR && this.chardata == ']' && !firstloop) { if (nrange) { base.subtractRanges(tok); tok = base; } break; } int c = this.chardata; boolean end = false; if (type == T_BACKSOLIDUS) { switch (c) { case 'd': case 'D': case 'w': case 'W': case 's': case 'S': tok.mergeRanges(this.getTokenForShorthand(c)); end = true; break; case 'i': case 'I': case 'c': case 'C': c = this.processCIinCharacterClass(tok, c); if (c < 0) end = true; break; case 'p': case 'P': int pstart = this.offset; RangeToken tok2 = this.processBacksolidus_pP(c); if (tok2 == null) throw this.ex("parser.atom.5", pstart); tok.mergeRanges(tok2); end = true; break; case '-': c = this.decodeEscaped(); wasDecoded = true; break; default: c = this.decodeEscaped(); } // \ + c } // backsolidus else if (type == T_XMLSCHEMA_CC_SUBTRACTION && !firstloop) { // Subraction if (nrange) { base.subtractRanges(tok); tok = base; } RangeToken range2 = this.parseCharacterClass(false); tok.subtractRanges(range2); if (this.read() != T_CHAR || this.chardata != ']') throw this.ex("parser.cc.5", this.offset); break; // Exit this loop } this.next(); if (!end) { // if not shorthands... if (type == T_CHAR) { if (c == '[') throw this.ex("parser.cc.6", this.offset-2); if (c == ']') throw this.ex("parser.cc.7", this.offset-2); if (c == '-' && this.chardata != ']' && !firstloop) throw this.ex("parser.cc.8", this.offset-2); // if regex = '[-]' then invalid } - if (this.read() != T_CHAR || this.chardata != '-' || c == '-' && firstloop) { // Here is no '-'. + if (this.read() != T_CHAR || this.chardata != '-' || c == '-' && !wasDecoded && firstloop) { // Here is no '-'. if (!this.isSet(RegularExpression.IGNORE_CASE) || c > 0xffff) { tok.addRange(c, c); } else { addCaseInsensitiveChar(tok, c); } } else { // Found '-' // Is this '-' is a from-to token?? this.next(); // Skips '-' if ((type = this.read()) == T_EOF) throw this.ex("parser.cc.2", this.offset); // c '-' ']' -> '-' is a single-range. if(type == T_CHAR && this.chardata == ']') { // if - is at the last position of the group if (!this.isSet(RegularExpression.IGNORE_CASE) || c > 0xffff) { tok.addRange(c, c); } else { addCaseInsensitiveChar(tok, c); } tok.addRange('-', '-'); } else if (type == T_XMLSCHEMA_CC_SUBTRACTION) { throw this.ex("parser.cc.8", this.offset-1); } else { int rangeend = this.chardata; if (type == T_CHAR) { if (rangeend == '[') throw this.ex("parser.cc.6", this.offset-1); if (rangeend == ']') throw this.ex("parser.cc.7", this.offset-1); if (rangeend == '-') throw this.ex("parser.cc.8", this.offset-2); } else if (type == T_BACKSOLIDUS) rangeend = this.decodeEscaped(); this.next(); if (c > rangeend) throw this.ex("parser.ope.3", this.offset-1); if (!this.isSet(RegularExpression.IGNORE_CASE) || (c > 0xffff && rangeend > 0xffff)) { tok.addRange(c, rangeend); } else { addCaseInsensitiveCharRange(tok, c, rangeend); } } } } firstloop = false; } if (this.read() == T_EOF) throw this.ex("parser.cc.2", this.offset); tok.sortRanges(); tok.compactRanges(); //tok.dumpRanges(); this.setContext(S_NORMAL); this.next(); // Skips ']' return tok; } protected RangeToken parseSetOperations() throws ParseException { throw this.ex("parser.process.1", this.offset); } Token getTokenForShorthand(int ch) { switch (ch) { case 'd': return ParserForXMLSchema.getRange("xml:isDigit", true); case 'D': return ParserForXMLSchema.getRange("xml:isDigit", false); case 'w': return ParserForXMLSchema.getRange("xml:isWord", true); case 'W': return ParserForXMLSchema.getRange("xml:isWord", false); case 's': return ParserForXMLSchema.getRange("xml:isSpace", true); case 'S': return ParserForXMLSchema.getRange("xml:isSpace", false); case 'c': return ParserForXMLSchema.getRange("xml:isNameChar", true); case 'C': return ParserForXMLSchema.getRange("xml:isNameChar", false); case 'i': return ParserForXMLSchema.getRange("xml:isInitialNameChar", true); case 'I': return ParserForXMLSchema.getRange("xml:isInitialNameChar", false); default: throw new RuntimeException("Internal Error: shorthands: \\u"+Integer.toString(ch, 16)); } } int decodeEscaped() throws ParseException { if (this.read() != T_BACKSOLIDUS) throw ex("parser.next.1", this.offset-1); int c = this.chardata; switch (c) { case 'n': c = '\n'; break; // LINE FEED U+000A case 'r': c = '\r'; break; // CRRIAGE RETURN U+000D case 't': c = '\t'; break; // HORIZONTAL TABULATION U+0009 case '\\': case '|': case '.': case '^': case '-': case '?': case '*': case '+': case '{': case '}': case '(': case ')': case '[': case ']': break; // return actucal char default: throw ex("parser.process.1", this.offset-2); } return c; } static private Hashtable ranges = null; static private Hashtable ranges2 = null; static synchronized protected RangeToken getRange(String name, boolean positive) { if (ranges == null) { ranges = new Hashtable(); ranges2 = new Hashtable(); Token tok = Token.createRange(); setupRange(tok, SPACES); ranges.put("xml:isSpace", tok); ranges2.put("xml:isSpace", Token.complementRanges(tok)); tok = Token.createRange(); // setupRange(tok, DIGITS); setupRange(tok, DIGITS_INTS); ranges.put("xml:isDigit", tok); ranges2.put("xml:isDigit", Token.complementRanges(tok)); tok = Token.createRange(); setupRange(tok, LETTERS); tok.mergeRanges((Token)ranges.get("xml:isDigit")); ranges.put("xml:isWord", tok); ranges2.put("xml:isWord", Token.complementRanges(tok)); tok = Token.createRange(); setupRange(tok, NAMECHARS); ranges.put("xml:isNameChar", tok); ranges2.put("xml:isNameChar", Token.complementRanges(tok)); tok = Token.createRange(); setupRange(tok, LETTERS); tok.addRange('_', '_'); tok.addRange(':', ':'); ranges.put("xml:isInitialNameChar", tok); ranges2.put("xml:isInitialNameChar", Token.complementRanges(tok)); } RangeToken tok = positive ? (RangeToken)ranges.get(name) : (RangeToken)ranges2.get(name); return tok; } static void setupRange(Token range, String src) { int len = src.length(); for (int i = 0; i < len; i += 2) range.addRange(src.charAt(i), src.charAt(i+1)); } static void setupRange(Token range, int[] src) { int len = src.length; for (int i = 0; i < len; i += 2) range.addRange(src[i], src[i+1]); } private static final String SPACES = "\t\n\r\r "; private static final String NAMECHARS = "\u002d\u002e\u0030\u003a\u0041\u005a\u005f\u005f\u0061\u007a\u00b7\u00b7\u00c0\u00d6" +"\u00d8\u00f6\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e\u0180\u01c3\u01cd\u01f0" +"\u01f4\u01f5\u01fa\u0217\u0250\u02a8\u02bb\u02c1\u02d0\u02d1\u0300\u0345\u0360\u0361" +"\u0386\u038a\u038c\u038c\u038e\u03a1\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" +"\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c\u040e\u044f\u0451\u045c\u045e\u0481" +"\u0483\u0486\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb\u04ee\u04f5\u04f8\u04f9" +"\u0531\u0556\u0559\u0559\u0561\u0586\u0591\u05a1\u05a3\u05b9\u05bb\u05bd\u05bf\u05bf" +"\u05c1\u05c2\u05c4\u05c4\u05d0\u05ea\u05f0\u05f2\u0621\u063a\u0640\u0652\u0660\u0669" +"\u0670\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3\u06d5\u06e8\u06ea\u06ed\u06f0\u06f9" +"\u0901\u0903\u0905\u0939\u093c\u094d\u0951\u0954\u0958\u0963\u0966\u096f\u0981\u0983" +"\u0985\u098c\u098f\u0990\u0993\u09a8\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9\u09bc\u09bc" +"\u09be\u09c4\u09c7\u09c8\u09cb\u09cd\u09d7\u09d7\u09dc\u09dd\u09df\u09e3\u09e6\u09f1" +"\u0a02\u0a02\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36" +"\u0a38\u0a39\u0a3c\u0a3c\u0a3e\u0a42\u0a47\u0a48\u0a4b\u0a4d\u0a59\u0a5c\u0a5e\u0a5e" +"\u0a66\u0a74\u0a81\u0a83\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8\u0aaa\u0ab0" +"\u0ab2\u0ab3\u0ab5\u0ab9\u0abc\u0ac5\u0ac7\u0ac9\u0acb\u0acd\u0ae0\u0ae0\u0ae6\u0aef" +"\u0b01\u0b03\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39" +"\u0b3c\u0b43\u0b47\u0b48\u0b4b\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f\u0b61\u0b66\u0b6f" +"\u0b82\u0b83\u0b85\u0b8a\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c\u0b9e\u0b9f" +"\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5\u0bb7\u0bb9\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd" +"\u0bd7\u0bd7\u0be7\u0bef\u0c01\u0c03\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33" +"\u0c35\u0c39\u0c3e\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56\u0c60\u0c61\u0c66\u0c6f" +"\u0c82\u0c83\u0c85\u0c8c\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9\u0cbe\u0cc4" +"\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6\u0cde\u0cde\u0ce0\u0ce1\u0ce6\u0cef\u0d02\u0d03" +"\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39\u0d3e\u0d43\u0d46\u0d48\u0d4a\u0d4d" +"\u0d57\u0d57\u0d60\u0d61\u0d66\u0d6f\u0e01\u0e2e\u0e30\u0e3a\u0e40\u0e4e\u0e50\u0e59" +"\u0e81\u0e82\u0e84\u0e84\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97\u0e99\u0e9f" +"\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb9\u0ebb\u0ebd" +"\u0ec0\u0ec4\u0ec6\u0ec6\u0ec8\u0ecd\u0ed0\u0ed9\u0f18\u0f19\u0f20\u0f29\u0f35\u0f35" +"\u0f37\u0f37\u0f39\u0f39\u0f3e\u0f47\u0f49\u0f69\u0f71\u0f84\u0f86\u0f8b\u0f90\u0f95" +"\u0f97\u0f97\u0f99\u0fad\u0fb1\u0fb7\u0fb9\u0fb9\u10a0\u10c5\u10d0\u10f6\u1100\u1100" +"\u1102\u1103\u1105\u1107\u1109\u1109\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" +"\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150\u1154\u1155\u1159\u1159\u115f\u1161" +"\u1163\u1163\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e\u1172\u1173\u1175\u1175" +"\u119e\u119e\u11a8\u11a8\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba\u11bc\u11c2" +"\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" +"\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d" +"\u1f80\u1fb4\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc\u1fd0\u1fd3\u1fd6\u1fdb" +"\u1fe0\u1fec\u1ff2\u1ff4\u1ff6\u1ffc\u20d0\u20dc\u20e1\u20e1\u2126\u2126\u212a\u212b" +"\u212e\u212e\u2180\u2182\u3005\u3005\u3007\u3007\u3021\u302f\u3031\u3035\u3041\u3094" +"\u3099\u309a\u309d\u309e\u30a1\u30fa\u30fc\u30fe\u3105\u312c\u4e00\u9fa5\uac00\ud7a3" +""; private static final String LETTERS = "\u0041\u005a\u0061\u007a\u00c0\u00d6\u00d8\u00f6\u00f8\u0131\u0134\u013e\u0141\u0148" +"\u014a\u017e\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217\u0250\u02a8\u02bb\u02c1" +"\u0386\u0386\u0388\u038a\u038c\u038c\u038e\u03a1\u03a3\u03ce\u03d0\u03d6\u03da\u03da" +"\u03dc\u03dc\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c\u040e\u044f\u0451\u045c" +"\u045e\u0481\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb\u04ee\u04f5\u04f8\u04f9" +"\u0531\u0556\u0559\u0559\u0561\u0586\u05d0\u05ea\u05f0\u05f2\u0621\u063a\u0641\u064a" +"\u0671\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3\u06d5\u06d5\u06e5\u06e6\u0905\u0939" +"\u093d\u093d\u0958\u0961\u0985\u098c\u098f\u0990\u0993\u09a8\u09aa\u09b0\u09b2\u09b2" +"\u09b6\u09b9\u09dc\u09dd\u09df\u09e1\u09f0\u09f1\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28" +"\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59\u0a5c\u0a5e\u0a5e\u0a72\u0a74" +"\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9" +"\u0abd\u0abd\u0ae0\u0ae0\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28\u0b2a\u0b30\u0b32\u0b33" +"\u0b36\u0b39\u0b3d\u0b3d\u0b5c\u0b5d\u0b5f\u0b61\u0b85\u0b8a\u0b8e\u0b90\u0b92\u0b95" +"\u0b99\u0b9a\u0b9c\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5\u0bb7\u0bb9" +"\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39\u0c60\u0c61\u0c85\u0c8c" +"\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9\u0cde\u0cde\u0ce0\u0ce1\u0d05\u0d0c" +"\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39\u0d60\u0d61\u0e01\u0e2e\u0e30\u0e30\u0e32\u0e33" +"\u0e40\u0e45\u0e81\u0e82\u0e84\u0e84\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" +"\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb0" +"\u0eb2\u0eb3\u0ebd\u0ebd\u0ec0\u0ec4\u0f40\u0f47\u0f49\u0f69\u10a0\u10c5\u10d0\u10f6" +"\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109\u110b\u110c\u110e\u1112\u113c\u113c" +"\u113e\u113e\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150\u1154\u1155\u1159\u1159" +"\u115f\u1161\u1163\u1163\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e\u1172\u1173" +"\u1175\u1175\u119e\u119e\u11a8\u11a8\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" +"\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15" +"\u1f18\u1f1d\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59\u1f5b\u1f5b\u1f5d\u1f5d" +"\u1f5f\u1f7d\u1f80\u1fb4\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc\u1fd0\u1fd3" +"\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4\u1ff6\u1ffc\u2126\u2126\u212a\u212b\u212e\u212e" +"\u2180\u2182\u3007\u3007\u3021\u3029\u3041\u3094\u30a1\u30fa\u3105\u312c\u4e00\u9fa5" +"\uac00\ud7a3"; private static final String DIGITS = "\u0030\u0039\u0660\u0669\u06F0\u06F9\u0966\u096F\u09E6\u09EF\u0A66\u0A6F\u0AE6\u0AEF" +"\u0B66\u0B6F\u0BE7\u0BEF\u0C66\u0C6F\u0CE6\u0CEF\u0D66\u0D6F\u0E50\u0E59\u0ED0\u0ED9" +"\u0F20\u0F29"; private static final int[] DIGITS_INTS = { 0x0030, 0x0039, 0x0660, 0x0669, 0x06F0, 0x06F9, 0x0966, 0x096F, 0x09E6, 0x09EF, 0x0A66, 0x0A6F, 0x0AE6, 0x0AEF, 0x0B66, 0x0B6F, 0x0BE7, 0x0BEF, 0x0C66, 0x0C6F, 0x0CE6, 0x0CEF, 0x0D66, 0x0D6F, 0x0E50, 0x0E59, 0x0ED0, 0x0ED9, 0x0F20, 0x0F29, 0x1040, 0x1049, 0x1369, 0x1371, 0x17E0, 0x17E9, 0x1810, 0x1819, 0xFF10, 0xFF19, 0x1D7CE, 0x1D7FF }; }
true
true
protected RangeToken parseCharacterClass(boolean useNrange) throws ParseException { this.setContext(S_INBRACKETS); this.next(); // '[' boolean nrange = false; boolean wasDecoded = false; // used to detect if the last - was escaped. RangeToken base = null; RangeToken tok; if (this.read() == T_CHAR && this.chardata == '^') { nrange = true; this.next(); // '^' base = Token.createRange(); base.addRange(0, Token.UTF16_MAX); tok = Token.createRange(); } else { tok = Token.createRange(); } int type; boolean firstloop = true; while ((type = this.read()) != T_EOF) { // Don't use 'cotinue' for this loop. wasDecoded = false; // single-range | from-to-range | subtraction if (type == T_CHAR && this.chardata == ']' && !firstloop) { if (nrange) { base.subtractRanges(tok); tok = base; } break; } int c = this.chardata; boolean end = false; if (type == T_BACKSOLIDUS) { switch (c) { case 'd': case 'D': case 'w': case 'W': case 's': case 'S': tok.mergeRanges(this.getTokenForShorthand(c)); end = true; break; case 'i': case 'I': case 'c': case 'C': c = this.processCIinCharacterClass(tok, c); if (c < 0) end = true; break; case 'p': case 'P': int pstart = this.offset; RangeToken tok2 = this.processBacksolidus_pP(c); if (tok2 == null) throw this.ex("parser.atom.5", pstart); tok.mergeRanges(tok2); end = true; break; case '-': c = this.decodeEscaped(); wasDecoded = true; break; default: c = this.decodeEscaped(); } // \ + c } // backsolidus else if (type == T_XMLSCHEMA_CC_SUBTRACTION && !firstloop) { // Subraction if (nrange) { base.subtractRanges(tok); tok = base; } RangeToken range2 = this.parseCharacterClass(false); tok.subtractRanges(range2); if (this.read() != T_CHAR || this.chardata != ']') throw this.ex("parser.cc.5", this.offset); break; // Exit this loop } this.next(); if (!end) { // if not shorthands... if (type == T_CHAR) { if (c == '[') throw this.ex("parser.cc.6", this.offset-2); if (c == ']') throw this.ex("parser.cc.7", this.offset-2); if (c == '-' && this.chardata != ']' && !firstloop) throw this.ex("parser.cc.8", this.offset-2); // if regex = '[-]' then invalid } if (this.read() != T_CHAR || this.chardata != '-' || c == '-' && firstloop) { // Here is no '-'. if (!this.isSet(RegularExpression.IGNORE_CASE) || c > 0xffff) { tok.addRange(c, c); } else { addCaseInsensitiveChar(tok, c); } } else { // Found '-' // Is this '-' is a from-to token?? this.next(); // Skips '-' if ((type = this.read()) == T_EOF) throw this.ex("parser.cc.2", this.offset); // c '-' ']' -> '-' is a single-range. if(type == T_CHAR && this.chardata == ']') { // if - is at the last position of the group if (!this.isSet(RegularExpression.IGNORE_CASE) || c > 0xffff) { tok.addRange(c, c); } else { addCaseInsensitiveChar(tok, c); } tok.addRange('-', '-'); } else if (type == T_XMLSCHEMA_CC_SUBTRACTION) { throw this.ex("parser.cc.8", this.offset-1); } else { int rangeend = this.chardata; if (type == T_CHAR) { if (rangeend == '[') throw this.ex("parser.cc.6", this.offset-1); if (rangeend == ']') throw this.ex("parser.cc.7", this.offset-1); if (rangeend == '-') throw this.ex("parser.cc.8", this.offset-2); } else if (type == T_BACKSOLIDUS) rangeend = this.decodeEscaped(); this.next(); if (c > rangeend) throw this.ex("parser.ope.3", this.offset-1); if (!this.isSet(RegularExpression.IGNORE_CASE) || (c > 0xffff && rangeend > 0xffff)) { tok.addRange(c, rangeend); } else { addCaseInsensitiveCharRange(tok, c, rangeend); } } } } firstloop = false; }
protected RangeToken parseCharacterClass(boolean useNrange) throws ParseException { this.setContext(S_INBRACKETS); this.next(); // '[' boolean nrange = false; boolean wasDecoded = false; // used to detect if the last - was escaped. RangeToken base = null; RangeToken tok; if (this.read() == T_CHAR && this.chardata == '^') { nrange = true; this.next(); // '^' base = Token.createRange(); base.addRange(0, Token.UTF16_MAX); tok = Token.createRange(); } else { tok = Token.createRange(); } int type; boolean firstloop = true; while ((type = this.read()) != T_EOF) { // Don't use 'cotinue' for this loop. wasDecoded = false; // single-range | from-to-range | subtraction if (type == T_CHAR && this.chardata == ']' && !firstloop) { if (nrange) { base.subtractRanges(tok); tok = base; } break; } int c = this.chardata; boolean end = false; if (type == T_BACKSOLIDUS) { switch (c) { case 'd': case 'D': case 'w': case 'W': case 's': case 'S': tok.mergeRanges(this.getTokenForShorthand(c)); end = true; break; case 'i': case 'I': case 'c': case 'C': c = this.processCIinCharacterClass(tok, c); if (c < 0) end = true; break; case 'p': case 'P': int pstart = this.offset; RangeToken tok2 = this.processBacksolidus_pP(c); if (tok2 == null) throw this.ex("parser.atom.5", pstart); tok.mergeRanges(tok2); end = true; break; case '-': c = this.decodeEscaped(); wasDecoded = true; break; default: c = this.decodeEscaped(); } // \ + c } // backsolidus else if (type == T_XMLSCHEMA_CC_SUBTRACTION && !firstloop) { // Subraction if (nrange) { base.subtractRanges(tok); tok = base; } RangeToken range2 = this.parseCharacterClass(false); tok.subtractRanges(range2); if (this.read() != T_CHAR || this.chardata != ']') throw this.ex("parser.cc.5", this.offset); break; // Exit this loop } this.next(); if (!end) { // if not shorthands... if (type == T_CHAR) { if (c == '[') throw this.ex("parser.cc.6", this.offset-2); if (c == ']') throw this.ex("parser.cc.7", this.offset-2); if (c == '-' && this.chardata != ']' && !firstloop) throw this.ex("parser.cc.8", this.offset-2); // if regex = '[-]' then invalid } if (this.read() != T_CHAR || this.chardata != '-' || c == '-' && !wasDecoded && firstloop) { // Here is no '-'. if (!this.isSet(RegularExpression.IGNORE_CASE) || c > 0xffff) { tok.addRange(c, c); } else { addCaseInsensitiveChar(tok, c); } } else { // Found '-' // Is this '-' is a from-to token?? this.next(); // Skips '-' if ((type = this.read()) == T_EOF) throw this.ex("parser.cc.2", this.offset); // c '-' ']' -> '-' is a single-range. if(type == T_CHAR && this.chardata == ']') { // if - is at the last position of the group if (!this.isSet(RegularExpression.IGNORE_CASE) || c > 0xffff) { tok.addRange(c, c); } else { addCaseInsensitiveChar(tok, c); } tok.addRange('-', '-'); } else if (type == T_XMLSCHEMA_CC_SUBTRACTION) { throw this.ex("parser.cc.8", this.offset-1); } else { int rangeend = this.chardata; if (type == T_CHAR) { if (rangeend == '[') throw this.ex("parser.cc.6", this.offset-1); if (rangeend == ']') throw this.ex("parser.cc.7", this.offset-1); if (rangeend == '-') throw this.ex("parser.cc.8", this.offset-2); } else if (type == T_BACKSOLIDUS) rangeend = this.decodeEscaped(); this.next(); if (c > rangeend) throw this.ex("parser.ope.3", this.offset-1); if (!this.isSet(RegularExpression.IGNORE_CASE) || (c > 0xffff && rangeend > 0xffff)) { tok.addRange(c, rangeend); } else { addCaseInsensitiveCharRange(tok, c, rangeend); } } } } firstloop = false; }
diff --git a/plugins/org.eclipse.graphiti/src/org/eclipse/graphiti/PropertyBag.java b/plugins/org.eclipse.graphiti/src/org/eclipse/graphiti/PropertyBag.java index 667a9d1a..e39eb947 100644 --- a/plugins/org.eclipse.graphiti/src/org/eclipse/graphiti/PropertyBag.java +++ b/plugins/org.eclipse.graphiti/src/org/eclipse/graphiti/PropertyBag.java @@ -1,59 +1,61 @@ /******************************************************************************* * <copyright> * * Copyright (c) 2005, 2012 SAP AG. * 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: * SAP AG - initial API, implementation and documentation * mwenz - Bug 394801 - AddGraphicalRepresentation doesn't carry properties * </copyright> * *******************************************************************************/ package org.eclipse.graphiti; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; /** * The class PropertyBag. */ public class PropertyBag implements IPropertyBag { private HashMap<Object, Object> propertyMap; public Object getProperty(Object key) { return getPropertyMap().get(key); } public Object putProperty(Object key, Object value) { return getPropertyMap().put(key, value); } /** * @since 0.10 */ public List<Object> getPropertyKeys() { List<Object> result = new ArrayList<Object>(); - Iterator<Object> iterator = propertyMap.keySet().iterator(); - while (iterator.hasNext()) { - Object key = (Object) iterator.next(); - result.add(key); + if (propertyMap != null) { + Iterator<Object> iterator = propertyMap.keySet().iterator(); + while (iterator.hasNext()) { + Object key = (Object) iterator.next(); + result.add(key); + } } return result; } private HashMap<Object, Object> getPropertyMap() { if (this.propertyMap == null) { this.propertyMap = new HashMap<Object, Object>(); } return this.propertyMap; } }
true
true
public List<Object> getPropertyKeys() { List<Object> result = new ArrayList<Object>(); Iterator<Object> iterator = propertyMap.keySet().iterator(); while (iterator.hasNext()) { Object key = (Object) iterator.next(); result.add(key); } return result; }
public List<Object> getPropertyKeys() { List<Object> result = new ArrayList<Object>(); if (propertyMap != null) { Iterator<Object> iterator = propertyMap.keySet().iterator(); while (iterator.hasNext()) { Object key = (Object) iterator.next(); result.add(key); } } return result; }
diff --git a/edu.illinois.compositerefactorings.extractsuperclass/src/edu/illinois/compositerefactorings/extractsuperclass/CreateNewSuperclassQuickAssistProcessor.java b/edu.illinois.compositerefactorings.extractsuperclass/src/edu/illinois/compositerefactorings/extractsuperclass/CreateNewSuperclassQuickAssistProcessor.java index 25201e4..3fddd05 100644 --- a/edu.illinois.compositerefactorings.extractsuperclass/src/edu/illinois/compositerefactorings/extractsuperclass/CreateNewSuperclassQuickAssistProcessor.java +++ b/edu.illinois.compositerefactorings.extractsuperclass/src/edu/illinois/compositerefactorings/extractsuperclass/CreateNewSuperclassQuickAssistProcessor.java @@ -1,75 +1,74 @@ package edu.illinois.compositerefactorings.extractsuperclass; import java.util.ArrayList; import java.util.Collection; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.ui.text.java.IQuickAssistProcessor; import org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal; import org.eclipse.jdt.ui.text.java.correction.ICommandAccess; import org.eclipse.swt.graphics.Image; @SuppressWarnings("restriction") public class CreateNewSuperclassQuickAssistProcessor implements IQuickAssistProcessor { @Override public boolean hasAssists(IInvocationContext context) throws CoreException { ASTNode coveringNode= context.getCoveringNode(); if (coveringNode != null) { return getCreateNewSuperclassProposal(context, coveringNode, false, null); } return false; } @Override public IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblemLocation[] locations) throws CoreException { ASTNode coveringNode= context.getCoveringNode(); if (coveringNode != null) { ArrayList<ICommandAccess> resultingCollections= new ArrayList<ICommandAccess>(); getCreateNewSuperclassProposal(context, coveringNode, false, resultingCollections); return resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]); } return null; } private static boolean getCreateNewSuperclassProposal(IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Collection<ICommandAccess> proposals) throws CoreException { if (!(coveringNode instanceof TypeDeclaration)) { return false; } if (proposals == null) { return true; } final ICompilationUnit cu= context.getCompilationUnit(); ASTNode coveringTypeDeclarationASTNode= context.getCoveringNode(); - AST coveringTypeDeclarationAST= coveringTypeDeclarationASTNode.getAST(); ASTNode node= coveringTypeDeclarationASTNode.getParent(); AST ast= node.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); String label= "Create new superclass in file"; Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 0, image); TypeDeclaration newSuperclass= ast.newTypeDeclaration(); newSuperclass.setName(ast.newSimpleName("NewSuperclass")); ListRewrite listRewrite= rewrite.getListRewrite(node, CompilationUnit.TYPES_PROPERTY); listRewrite.insertLast(newSuperclass, null); rewrite.set(newSuperclass, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, coveringTypeDeclarationASTNode.getStructuralProperty(TypeDeclaration.SUPERCLASS_TYPE_PROPERTY), null); rewrite.set(coveringTypeDeclarationASTNode, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, newSuperclass.getName(), null); proposals.add(proposal); return true; } }
true
true
private static boolean getCreateNewSuperclassProposal(IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Collection<ICommandAccess> proposals) throws CoreException { if (!(coveringNode instanceof TypeDeclaration)) { return false; } if (proposals == null) { return true; } final ICompilationUnit cu= context.getCompilationUnit(); ASTNode coveringTypeDeclarationASTNode= context.getCoveringNode(); AST coveringTypeDeclarationAST= coveringTypeDeclarationASTNode.getAST(); ASTNode node= coveringTypeDeclarationASTNode.getParent(); AST ast= node.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); String label= "Create new superclass in file"; Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 0, image); TypeDeclaration newSuperclass= ast.newTypeDeclaration(); newSuperclass.setName(ast.newSimpleName("NewSuperclass")); ListRewrite listRewrite= rewrite.getListRewrite(node, CompilationUnit.TYPES_PROPERTY); listRewrite.insertLast(newSuperclass, null); rewrite.set(newSuperclass, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, coveringTypeDeclarationASTNode.getStructuralProperty(TypeDeclaration.SUPERCLASS_TYPE_PROPERTY), null); rewrite.set(coveringTypeDeclarationASTNode, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, newSuperclass.getName(), null); proposals.add(proposal); return true; }
private static boolean getCreateNewSuperclassProposal(IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Collection<ICommandAccess> proposals) throws CoreException { if (!(coveringNode instanceof TypeDeclaration)) { return false; } if (proposals == null) { return true; } final ICompilationUnit cu= context.getCompilationUnit(); ASTNode coveringTypeDeclarationASTNode= context.getCoveringNode(); ASTNode node= coveringTypeDeclarationASTNode.getParent(); AST ast= node.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); String label= "Create new superclass in file"; Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 0, image); TypeDeclaration newSuperclass= ast.newTypeDeclaration(); newSuperclass.setName(ast.newSimpleName("NewSuperclass")); ListRewrite listRewrite= rewrite.getListRewrite(node, CompilationUnit.TYPES_PROPERTY); listRewrite.insertLast(newSuperclass, null); rewrite.set(newSuperclass, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, coveringTypeDeclarationASTNode.getStructuralProperty(TypeDeclaration.SUPERCLASS_TYPE_PROPERTY), null); rewrite.set(coveringTypeDeclarationASTNode, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, newSuperclass.getName(), null); proposals.add(proposal); return true; }
diff --git a/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevSyncProvider.java b/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevSyncProvider.java index eac03b9d0..81a61860f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevSyncProvider.java +++ b/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevSyncProvider.java @@ -1,782 +1,782 @@ /** * See the file "LICENSE" for the full license governing this code. */ package com.todoroo.astrid.producteev.sync; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import com.timsu.astrid.R; import com.todoroo.andlib.data.Property; import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.service.ExceptionService; import com.todoroo.andlib.service.NotificationManager; import com.todoroo.andlib.utility.AndroidUtilities; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.activity.ShortcutActivity; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.data.Metadata; import com.todoroo.astrid.data.StoreObject; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.producteev.ProducteevBackgroundService; import com.todoroo.astrid.producteev.ProducteevFilterExposer; import com.todoroo.astrid.producteev.ProducteevLoginActivity; import com.todoroo.astrid.producteev.ProducteevPreferences; import com.todoroo.astrid.producteev.ProducteevUtilities; import com.todoroo.astrid.producteev.api.ApiResponseParseException; import com.todoroo.astrid.producteev.api.ApiServiceException; import com.todoroo.astrid.producteev.api.ApiUtilities; import com.todoroo.astrid.producteev.api.ProducteevInvoker; import com.todoroo.astrid.service.AstridDependencyInjector; import com.todoroo.astrid.service.StatisticsService; import com.todoroo.astrid.sync.SyncContainer; import com.todoroo.astrid.sync.SyncProvider; import com.todoroo.astrid.tags.TagService; import com.todoroo.astrid.utility.Constants; import com.todoroo.astrid.utility.Flags; @SuppressWarnings("nls") public class ProducteevSyncProvider extends SyncProvider<ProducteevTaskContainer> { private static final long TASK_ID_UNSYNCED = 1L; private ProducteevDataService dataService = null; private ProducteevInvoker invoker = null; private final ProducteevUtilities preferences = ProducteevUtilities.INSTANCE; /** producteev user id. set during sync */ private long userId; /** map of producteev dashboard id + label name to id's */ private final HashMap<String, Long> labelMap = new HashMap<String, Long>(); static { AstridDependencyInjector.initialize(); } @Autowired protected ExceptionService exceptionService; public ProducteevSyncProvider() { super(); DependencyInjectionService.getInstance().inject(this); } // ---------------------------------------------------------------------- // ------------------------------------------------------ utility methods // ---------------------------------------------------------------------- /** * Sign out of service, deleting all synchronization metadata */ public void signOut() { preferences.setToken(null); Preferences.setString(R.string.producteev_PPr_email, null); Preferences.setString(R.string.producteev_PPr_password, null); Preferences.setString(ProducteevUtilities.PREF_SERVER_LAST_SYNC, null); Preferences.setStringFromInteger(R.string.producteev_PPr_defaultdash_key, ProducteevUtilities.DASHBOARD_DEFAULT); preferences.clearLastSyncDate(); dataService = ProducteevDataService.getInstance(); dataService.clearMetadata(); } /** * Deal with a synchronization exception. If requested, will show an error * to the user (unless synchronization is happening in background) * * @param context * @param tag * error tag * @param e * exception * @param showError * whether to display a dialog */ @Override protected void handleException(String tag, Exception e, boolean displayError) { final Context context = ContextManager.getContext(); preferences.setLastError(e.toString()); String message = null; // occurs when application was closed if(e instanceof IllegalStateException) { exceptionService.reportError(tag + "-caught", e); //$NON-NLS-1$ // occurs when network error } else if(!(e instanceof ApiServiceException) && e instanceof IOException) { message = context.getString(R.string.producteev_ioerror); } else { message = context.getString(R.string.DLG_error, e.toString()); exceptionService.reportError(tag + "-unhandled", e); //$NON-NLS-1$ } if(displayError && context instanceof Activity && message != null) { DialogUtilities.okDialog((Activity)context, message, null); } } // ---------------------------------------------------------------------- // ------------------------------------------------------ initiating sync // ---------------------------------------------------------------------- /** * initiate sync in background */ @Override protected void initiateBackground() { dataService = ProducteevDataService.getInstance(); try { String authToken = preferences.getToken(); invoker = getInvoker(); String email = Preferences.getStringValue(R.string.producteev_PPr_email); String password = Preferences.getStringValue(R.string.producteev_PPr_password); // check if we have a token & it works if(authToken != null) { invoker.setCredentials(authToken, email, password); performSync(); } else { if (email == null && password == null) { // we can't do anything, user is not logged in } else { invoker.authenticate(email, password); preferences.setToken(invoker.getToken()); performSync(); } } } catch (IllegalStateException e) { // occurs when application was closed } catch (Exception e) { handleException("pdv-authenticate", e, true); } finally { preferences.stopOngoing(); } } /** * If user isn't already signed in, show sign in dialog. Else perform sync. */ @Override protected void initiateManual(Activity activity) { String authToken = preferences.getToken(); ProducteevUtilities.INSTANCE.stopOngoing(); // check if we have a token & it works if(authToken == null) { // display login-activity Intent intent = new Intent(activity, ProducteevLoginActivity.class); activity.startActivityForResult(intent, 0); } else { activity.startService(new Intent(null, null, activity, ProducteevBackgroundService.class)); } } public static ProducteevInvoker getInvoker() { String z = stripslashes(0, "71o3346pr40o5o4nt4n7t6n287t4op28","2"); String v = stripslashes(2, "9641n76n9s1736q1578q1o1337q19233","4ae"); return new ProducteevInvoker(z, v); } // ---------------------------------------------------------------------- // ----------------------------------------------------- synchronization! // ---------------------------------------------------------------------- protected void performSync() { StatisticsService.reportEvent("producteev-started"); preferences.recordSyncStart(); try { // load user information JSONObject user = invoker.usersView(null).getJSONObject("user"); saveUserData(user); String lastServerSync = Preferences.getStringValue(ProducteevUtilities.PREF_SERVER_LAST_SYNC); String lastNotificationId = Preferences.getStringValue(ProducteevUtilities.PREF_SERVER_LAST_NOTIFICATION); String lastActivityId = Preferences.getStringValue(ProducteevUtilities.PREF_SERVER_LAST_ACTIVITY); // read dashboards JSONArray dashboards = invoker.dashboardsShowList(lastServerSync); dataService.updateDashboards(dashboards); // read labels and tasks for each dashboard ArrayList<ProducteevTaskContainer> remoteTasks = new ArrayList<ProducteevTaskContainer>(); for(StoreObject dashboard : dataService.getDashboards()) { long dashboardId = dashboard.getValue(ProducteevDashboard.REMOTE_ID); - JSONArray labels = invoker.labelsShowList(dashboardId, lastServerSync); + JSONArray labels = invoker.labelsShowList(dashboardId, null); readLabels(labels); try { // This invocation throws ApiServiceException for workspaces that need to be upgraded JSONArray tasks = invoker.tasksShowList(dashboardId, lastServerSync); for(int i = 0; i < tasks.length(); i++) { ProducteevTaskContainer remote = parseRemoteTask(tasks.getJSONObject(i)); if(remote.pdvTask.getValue(ProducteevTask.CREATOR_ID) != userId && remote.pdvTask.getValue(ProducteevTask.RESPONSIBLE_ID) != userId) remote.task.setFlag(Task.FLAGS, Task.FLAG_IS_READONLY, true); else remote.task.setFlag(Task.FLAGS, Task.FLAG_IS_READONLY, false); // update reminder flags for incoming remote tasks to prevent annoying if(remote.task.hasDueDate() && remote.task.getValue(Task.DUE_DATE) < DateUtilities.now()) remote.task.setFlag(Task.REMINDER_FLAGS, Task.NOTIFY_AFTER_DEADLINE, false); dataService.findLocalMatch(remote); remoteTasks.add(remote); } } catch (ApiServiceException ase) { // catch it here, so that other dashboards can still be synchronized handleException("pdv-sync", ase, true); //$NON-NLS-1$ } } SyncData<ProducteevTaskContainer> syncData = populateSyncData(remoteTasks); try { synchronizeTasks(syncData); } finally { syncData.localCreated.close(); syncData.localUpdated.close(); } Preferences.setString(ProducteevUtilities.PREF_SERVER_LAST_SYNC, invoker.time()); preferences.recordSuccessfulSync(); Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH); ContextManager.getContext().sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ); // notification/activities stuff JSONArray notifications = invoker.activitiesShowNotifications(null, (lastNotificationId == null ? null : new Long(lastNotificationId))); String[] notificationsList = parseActivities(notifications); // update lastIds if (notifications.length() > 0) { lastNotificationId = ""+notifications.getJSONObject(0).getJSONObject("activity").getLong("id_activity"); } // display notifications from producteev-log Context context = ContextManager.getContext(); final NotificationManager nm = new NotificationManager.AndroidNotificationManager(context); for (int i = 0; i< notificationsList.length; i++) { long id_dashboard = notifications.getJSONObject(i).getJSONObject("activity").getLong("id_dashboard"); String dashboardName = null; StoreObject[] dashboardsData = ProducteevDataService.getInstance().getDashboards(); ProducteevDashboard dashboard = null; if (dashboardsData != null) { for (int j=0; i<dashboardsData.length;i++) { long id = dashboardsData[j].getValue(ProducteevDashboard.REMOTE_ID); if (id == id_dashboard) { dashboardName = dashboardsData[j].getValue(ProducteevDashboard.NAME); dashboard = new ProducteevDashboard(id, dashboardName, null); break; } } } // it seems dashboard is null if we get a notification about an unknown dashboard, just filter it. if (dashboard != null) { // initialize notification int icon = R.drawable.ic_producteev_notification; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, null, when); CharSequence contentTitle = context.getString(R.string.producteev_notification_title)+": "+dashboard.getName(); Filter filter = ProducteevFilterExposer.filterFromList(context, dashboard, userId); Intent notificationIntent = ShortcutActivity.createIntent(filter); // filter the tags from the message String message = notificationsList[i].replaceAll("<[^>]+>", ""); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, message, contentIntent); nm.notify(Constants.NOTIFICATION_PRODUCTEEV_NOTIFICATIONS-i, notification); } } // store lastIds in Preferences Preferences.setString(ProducteevUtilities.PREF_SERVER_LAST_NOTIFICATION, lastNotificationId); Preferences.setString(ProducteevUtilities.PREF_SERVER_LAST_ACTIVITY, lastActivityId); StatisticsService.reportEvent("pdv-sync-finished"); //$NON-NLS-1$ Flags.set(Flags.REFRESH); } catch (IllegalStateException e) { // occurs when application was closed } catch (Exception e) { handleException("pdv-sync", e, true); //$NON-NLS-1$ } } /** * @param activities * @return * @throws JSONException */ private String[] parseActivities(JSONArray activities) throws JSONException { int count = (activities == null ? 0 : activities.length()); String[] activitiesList = new String[count]; if(activities == null) return activitiesList; for(int i = 0; i < activities.length(); i++) { String message = activities.getJSONObject(i).getJSONObject("activity").getString("message"); activitiesList[i] = ApiUtilities.decode(message); } return activitiesList; } // ---------------------------------------------------------------------- // ------------------------------------------------------------ sync data // ---------------------------------------------------------------------- private void saveUserData(JSONObject user) throws JSONException { long defaultDashboard = user.getLong("default_dashboard"); userId = user.getLong("id_user"); Preferences.setLong(ProducteevUtilities.PREF_DEFAULT_DASHBOARD, defaultDashboard); Preferences.setLong(ProducteevUtilities.PREF_USER_ID, userId); // save the default dashboard preference if unset int defaultDashSetting = Preferences.getIntegerFromString(R.string.producteev_PPr_defaultdash_key, ProducteevUtilities.DASHBOARD_DEFAULT); if(defaultDashSetting == ProducteevUtilities.DASHBOARD_DEFAULT) Preferences.setStringFromInteger(R.string.producteev_PPr_defaultdash_key, (int) defaultDashboard); } // all synchronized properties private static final Property<?>[] PROPERTIES = new Property<?>[] { Task.ID, Task.TITLE, Task.IMPORTANCE, Task.DUE_DATE, Task.CREATION_DATE, Task.COMPLETION_DATE, Task.DELETION_DATE, Task.REMINDER_FLAGS, Task.NOTES, Task.RECURRENCE }; /** * Populate SyncData data structure * @throws JSONException */ private SyncData<ProducteevTaskContainer> populateSyncData(ArrayList<ProducteevTaskContainer> remoteTasks) throws JSONException { // fetch locally created tasks TodorooCursor<Task> localCreated = dataService.getLocallyCreated(PROPERTIES); // fetch locally updated tasks TodorooCursor<Task> localUpdated = dataService.getLocallyUpdated(PROPERTIES); return new SyncData<ProducteevTaskContainer>(remoteTasks, localCreated, localUpdated); } // ---------------------------------------------------------------------- // ------------------------------------------------- create / push / pull // ---------------------------------------------------------------------- @Override protected ProducteevTaskContainer create(ProducteevTaskContainer local) throws IOException { Task localTask = local.task; long dashboard = ProducteevUtilities.INSTANCE.getDefaultDashboard(); if(local.pdvTask.containsNonNullValue(ProducteevTask.DASHBOARD_ID)) dashboard = local.pdvTask.getValue(ProducteevTask.DASHBOARD_ID); long responsibleId = local.pdvTask.getValue(ProducteevTask.RESPONSIBLE_ID); if(dashboard == ProducteevUtilities.DASHBOARD_NO_SYNC) { // set a bogus task id, then return without creating local.pdvTask.setValue(ProducteevTask.ID, TASK_ID_UNSYNCED); return local; } JSONObject response = invoker.tasksCreate(localTask.getValue(Task.TITLE), responsibleId, dashboard, createDeadline(localTask), createReminder(localTask), localTask.isCompleted() ? 2 : 1, createStars(localTask)); ProducteevTaskContainer newRemoteTask; try { newRemoteTask = parseRemoteTask(response); } catch (JSONException e) { throw new ApiResponseParseException(e); } transferIdentifiers(newRemoteTask, local); push(local, newRemoteTask); return newRemoteTask; } /** Create a task container for the given RtmTaskSeries * @throws JSONException */ private ProducteevTaskContainer parseRemoteTask(JSONObject remoteTask) throws JSONException { Task task = new Task(); ArrayList<Metadata> metadata = new ArrayList<Metadata>(); if(remoteTask.has("task")) remoteTask = remoteTask.getJSONObject("task"); task.setValue(Task.TITLE, ApiUtilities.decode(remoteTask.getString("title"))); task.setValue(Task.CREATION_DATE, ApiUtilities.producteevToUnixTime(remoteTask.getString("time_created"), 0)); task.setValue(Task.COMPLETION_DATE, remoteTask.getInt("status") == 2 ? DateUtilities.now() : 0); task.setValue(Task.DELETION_DATE, remoteTask.getInt("deleted") == 1 ? DateUtilities.now() : 0); long dueDate = ApiUtilities.producteevToUnixTime(remoteTask.getString("deadline"), 0); if(remoteTask.optInt("all_day", 0) == 1) task.setValue(Task.DUE_DATE, task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate)); else task.setValue(Task.DUE_DATE, task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, dueDate)); task.setValue(Task.IMPORTANCE, 5 - remoteTask.getInt("star")); JSONArray labels = remoteTask.getJSONArray("labels"); for(int i = 0; i < labels.length(); i++) { JSONObject label = labels.getJSONObject(i).getJSONObject("label"); if(label.getInt("deleted") != 0) continue; Metadata tagData = new Metadata(); tagData.setValue(Metadata.KEY, TagService.KEY); tagData.setValue(TagService.TAG, ApiUtilities.decode(label.getString("title"))); metadata.add(tagData); } JSONArray notes = remoteTask.getJSONArray("notes"); for(int i = notes.length() - 1; i >= 0; i--) { JSONObject note = notes.getJSONObject(i).getJSONObject("note"); metadata.add(ApiUtilities.createNoteMetadata(note)); } ProducteevTaskContainer container = new ProducteevTaskContainer(task, metadata, remoteTask); return container; } @Override protected ProducteevTaskContainer pull(ProducteevTaskContainer task) throws IOException { if(!task.pdvTask.containsNonNullValue(ProducteevTask.ID)) throw new ApiServiceException("Tried to read an invalid task"); //$NON-NLS-1$ JSONObject remote = invoker.tasksView(task.pdvTask.getValue(ProducteevTask.ID)); try { return parseRemoteTask(remote); } catch (JSONException e) { throw new ApiResponseParseException(e); } } /** * Send changes for the given Task across the wire. If a remoteTask is * supplied, we attempt to intelligently only transmit the values that * have changed. */ @Override protected void push(ProducteevTaskContainer local, ProducteevTaskContainer remote) throws IOException { boolean remerge = false; long idTask = local.pdvTask.getValue(ProducteevTask.ID); long idDashboard = local.pdvTask.getValue(ProducteevTask.DASHBOARD_ID); long idResponsible = local.pdvTask.getValue(ProducteevTask.RESPONSIBLE_ID); // if local is marked do not sync, handle accordingly if(idDashboard == ProducteevUtilities.DASHBOARD_NO_SYNC) { return; } // fetch remote task for comparison if(remote == null) remote = pull(local); // either delete or re-create if necessary if(shouldTransmit(local, Task.DELETION_DATE, remote)) { if(local.task.getValue(Task.DELETION_DATE) > 0) invoker.tasksDelete(idTask); else { // if we create, we transfer identifiers to old remote // in case it is used by caller for other purposes ProducteevTaskContainer newRemote = create(local); transferIdentifiers(newRemote, remote); remote = newRemote; } } // dashboard if(remote != null && idDashboard != remote.pdvTask.getValue(ProducteevTask.DASHBOARD_ID)) { invoker.tasksSetWorkspace(idTask, idDashboard); remote = pull(local); } else if(remote == null && idTask == TASK_ID_UNSYNCED) { // was un-synced, create remote remote = create(local); } // responsible if(remote != null && idResponsible != remote.pdvTask.getValue(ProducteevTask.RESPONSIBLE_ID)) { invoker.tasksSetResponsible(idTask, idResponsible); } // core properties if(shouldTransmit(local, Task.TITLE, remote)) invoker.tasksSetTitle(idTask, local.task.getValue(Task.TITLE)); if(shouldTransmit(local, Task.IMPORTANCE, remote)) invoker.tasksSetStar(idTask, createStars(local.task)); if(shouldTransmit(local, Task.DUE_DATE, remote)) { if(local.task.hasDueDate()) invoker.tasksSetDeadline(idTask, createDeadline(local.task), local.task.hasDueTime() ? 0 : 1); else invoker.tasksUnsetDeadline(idTask); } boolean isPDVRepeating = ((local.pdvTask.containsNonNullValue(ProducteevTask.REPEATING_SETTING) && local.pdvTask.getValue(ProducteevTask.REPEATING_SETTING).length()>0) || (remote != null && remote.pdvTask.containsNonNullValue(ProducteevTask.REPEATING_SETTING) && remote.pdvTask.getValue(ProducteevTask.REPEATING_SETTING).length()>0)); boolean isAstridRepeating = local.task.containsNonNullValue(Task.RECURRENCE) && local.task.getValue(Task.RECURRENCE).length() > 0; if (isAstridRepeating && isPDVRepeating) { // Astrid-repeat overrides PDV-repeat invoker.tasksUnsetRepeating(idTask); } if(shouldTransmit(local, Task.COMPLETION_DATE, remote)) { invoker.tasksSetStatus(idTask, local.task.isCompleted() ? 2 : 1); if (local.task.isCompleted() && !isAstridRepeating && isPDVRepeating) { local.task.setValue(Task.COMPLETION_DATE, 0L); remerge = true; } } try { // tags transmitTags(local, remote, idTask, idDashboard); // notes if(!TextUtils.isEmpty(local.task.getValue(Task.NOTES))) { String note = local.task.getValue(Task.NOTES); JSONObject result = invoker.tasksNoteCreate(idTask, note); local.metadata.add(ApiUtilities.createNoteMetadata(result.getJSONObject("note"))); local.task.setValue(Task.NOTES, ""); } if(remerge) { remote = pull(local); remote.task.setId(local.task.getId()); // transform local into remote local.task = remote.task; local.pdvTask.setValue(ProducteevTask.ID, remote.pdvTask.getValue(ProducteevTask.ID)); local.pdvTask.setValue(ProducteevTask.DASHBOARD_ID, remote.pdvTask.getValue(ProducteevTask.DASHBOARD_ID)); local.pdvTask.setValue(ProducteevTask.CREATOR_ID, remote.pdvTask.getValue(ProducteevTask.CREATOR_ID)); local.pdvTask.setValue(ProducteevTask.RESPONSIBLE_ID, remote.pdvTask.getValue(ProducteevTask.RESPONSIBLE_ID)); if(remote.pdvTask.containsNonNullValue(ProducteevTask.REPEATING_SETTING)) local.pdvTask.setValue(ProducteevTask.REPEATING_SETTING, remote.pdvTask.getValue(ProducteevTask.REPEATING_SETTING)); } } catch (JSONException e) { throw new ApiResponseParseException(e); } } /** * Transmit tags * * @param local * @param remote * @param idTask * @param idDashboard * @throws ApiServiceException * @throws JSONException * @throws IOException */ private void transmitTags(ProducteevTaskContainer local, ProducteevTaskContainer remote, long idTask, long idDashboard) throws ApiServiceException, JSONException, IOException { HashSet<String> localTags = new HashSet<String>(); HashSet<String> remoteTags = new HashSet<String>(); for(Metadata item : local.metadata) if(TagService.KEY.equals(item.getValue(Metadata.KEY))) localTags.add(item.getValue(TagService.TAG)); if(remote != null && remote.metadata != null) { for(Metadata item : remote.metadata) if(TagService.KEY.equals(item.getValue(Metadata.KEY))) remoteTags.add(item.getValue(TagService.TAG)); } if(!localTags.equals(remoteTags)) { long[] labels = new long[localTags.size()]; int index = 0; for(String label : localTags) { String pdvLabel = idDashboard + label; final long id; if(!labelMap.containsKey(pdvLabel)) { JSONObject result = invoker.labelsCreate(idDashboard, label).getJSONObject("label"); id = putLabelIntoCache(result); } else id = labelMap.get(pdvLabel); labels[index++] = id; } invoker.tasksChangeLabel(idTask, labels); } } // ---------------------------------------------------------------------- // --------------------------------------------------------- read / write // ---------------------------------------------------------------------- @Override protected ProducteevTaskContainer read(TodorooCursor<Task> cursor) throws IOException { return dataService.readTaskAndMetadata(cursor); } @Override protected void write(ProducteevTaskContainer task) throws IOException { dataService.saveTaskAndMetadata(task); } // ---------------------------------------------------------------------- // --------------------------------------------------------- misc helpers // ---------------------------------------------------------------------- @Override protected int matchTask(ArrayList<ProducteevTaskContainer> tasks, ProducteevTaskContainer target) { int length = tasks.size(); for(int i = 0; i < length; i++) { ProducteevTaskContainer task = tasks.get(i); if (target.pdvTask.containsNonNullValue(ProducteevTask.ID) && task.pdvTask.getValue(ProducteevTask.ID).equals(target.pdvTask.getValue(ProducteevTask.ID))) return i; } return -1; } /** * get stars in producteev format * @param local * @return */ private Integer createStars(Task local) { return 5 - local.getValue(Task.IMPORTANCE); } /** * get reminder in producteev format * @param local * @return */ private Integer createReminder(Task local) { if(local.getFlag(Task.REMINDER_FLAGS, Task.NOTIFY_AT_DEADLINE)) return 8; return null; } /** * get deadline in producteev format * @param task * @return */ private String createDeadline(Task task) { if(!task.hasDueDate()) return ""; return ApiUtilities.unixTimeToProducteev(task.getValue(Task.DUE_DATE)); } /** * Determine whether this task's property should be transmitted * @param task task to consider * @param property property to consider * @param remoteTask remote task proxy * @return */ private boolean shouldTransmit(SyncContainer task, Property<?> property, SyncContainer remoteTask) { if(!task.task.containsValue(property)) return false; if(remoteTask == null) return true; if(!remoteTask.task.containsValue(property)) return true; // special cases - match if they're zero or nonzero if(property == Task.COMPLETION_DATE || property == Task.DELETION_DATE) return !AndroidUtilities.equals((Long)task.task.getValue(property) == 0, (Long)remoteTask.task.getValue(property) == 0); return !AndroidUtilities.equals(task.task.getValue(property), remoteTask.task.getValue(property)); } @Override protected int updateNotification(Context context, Notification notification) { String notificationTitle = context.getString(R.string.producteev_notification_title); Intent intent = new Intent(context, ProducteevPreferences.class); PendingIntent notificationIntent = PendingIntent.getActivity(context, 0, intent, 0); notification.setLatestEventInfo(context, notificationTitle, context.getString(R.string.SyP_progress), notificationIntent); return Constants.NOTIFICATION_SYNC; } @Override protected void transferIdentifiers(ProducteevTaskContainer source, ProducteevTaskContainer destination) { destination.pdvTask = source.pdvTask; } /** * Read labels into label map * @param dashboardId * @throws JSONException * @throws ApiServiceException * @throws IOException */ private void readLabels(JSONArray labels) throws JSONException, ApiServiceException, IOException { for(int i = 0; i < labels.length(); i++) { JSONObject label = labels.getJSONObject(i).getJSONObject("label"); putLabelIntoCache(label); } } /** * Puts a single label into the cache * @param dashboardId * @param label * @throws JSONException */ private long putLabelIntoCache(JSONObject label) throws JSONException { String name = ApiUtilities.decode(label.getString("title")); long dashboard = label.getLong("id_dashboard"); labelMap.put(dashboard + name, label.getLong("id_label")); return label.getLong("id_label"); } // ---------------------------------------------------------------------- // ------------------------------------------------------- helper methods // ---------------------------------------------------------------------- private static final String stripslashes(int ____,String __,String ___) { int _=__.charAt(____/92);_=_==116?_-1:_;_=((_>=97)&&(_<=123)? ((_-83)%27+97):_);return TextUtils.htmlEncode(____==31?___: stripslashes(____+1,__.substring(1),___+((char)_))); } }
true
true
protected void performSync() { StatisticsService.reportEvent("producteev-started"); preferences.recordSyncStart(); try { // load user information JSONObject user = invoker.usersView(null).getJSONObject("user"); saveUserData(user); String lastServerSync = Preferences.getStringValue(ProducteevUtilities.PREF_SERVER_LAST_SYNC); String lastNotificationId = Preferences.getStringValue(ProducteevUtilities.PREF_SERVER_LAST_NOTIFICATION); String lastActivityId = Preferences.getStringValue(ProducteevUtilities.PREF_SERVER_LAST_ACTIVITY); // read dashboards JSONArray dashboards = invoker.dashboardsShowList(lastServerSync); dataService.updateDashboards(dashboards); // read labels and tasks for each dashboard ArrayList<ProducteevTaskContainer> remoteTasks = new ArrayList<ProducteevTaskContainer>(); for(StoreObject dashboard : dataService.getDashboards()) { long dashboardId = dashboard.getValue(ProducteevDashboard.REMOTE_ID); JSONArray labels = invoker.labelsShowList(dashboardId, lastServerSync); readLabels(labels); try { // This invocation throws ApiServiceException for workspaces that need to be upgraded JSONArray tasks = invoker.tasksShowList(dashboardId, lastServerSync); for(int i = 0; i < tasks.length(); i++) { ProducteevTaskContainer remote = parseRemoteTask(tasks.getJSONObject(i)); if(remote.pdvTask.getValue(ProducteevTask.CREATOR_ID) != userId && remote.pdvTask.getValue(ProducteevTask.RESPONSIBLE_ID) != userId) remote.task.setFlag(Task.FLAGS, Task.FLAG_IS_READONLY, true); else remote.task.setFlag(Task.FLAGS, Task.FLAG_IS_READONLY, false); // update reminder flags for incoming remote tasks to prevent annoying if(remote.task.hasDueDate() && remote.task.getValue(Task.DUE_DATE) < DateUtilities.now()) remote.task.setFlag(Task.REMINDER_FLAGS, Task.NOTIFY_AFTER_DEADLINE, false); dataService.findLocalMatch(remote); remoteTasks.add(remote); } } catch (ApiServiceException ase) { // catch it here, so that other dashboards can still be synchronized handleException("pdv-sync", ase, true); //$NON-NLS-1$ } } SyncData<ProducteevTaskContainer> syncData = populateSyncData(remoteTasks); try { synchronizeTasks(syncData); } finally { syncData.localCreated.close(); syncData.localUpdated.close(); } Preferences.setString(ProducteevUtilities.PREF_SERVER_LAST_SYNC, invoker.time()); preferences.recordSuccessfulSync(); Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH); ContextManager.getContext().sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ); // notification/activities stuff JSONArray notifications = invoker.activitiesShowNotifications(null, (lastNotificationId == null ? null : new Long(lastNotificationId))); String[] notificationsList = parseActivities(notifications); // update lastIds if (notifications.length() > 0) { lastNotificationId = ""+notifications.getJSONObject(0).getJSONObject("activity").getLong("id_activity"); } // display notifications from producteev-log Context context = ContextManager.getContext(); final NotificationManager nm = new NotificationManager.AndroidNotificationManager(context); for (int i = 0; i< notificationsList.length; i++) { long id_dashboard = notifications.getJSONObject(i).getJSONObject("activity").getLong("id_dashboard"); String dashboardName = null; StoreObject[] dashboardsData = ProducteevDataService.getInstance().getDashboards(); ProducteevDashboard dashboard = null; if (dashboardsData != null) { for (int j=0; i<dashboardsData.length;i++) { long id = dashboardsData[j].getValue(ProducteevDashboard.REMOTE_ID); if (id == id_dashboard) { dashboardName = dashboardsData[j].getValue(ProducteevDashboard.NAME); dashboard = new ProducteevDashboard(id, dashboardName, null); break; } } } // it seems dashboard is null if we get a notification about an unknown dashboard, just filter it. if (dashboard != null) { // initialize notification int icon = R.drawable.ic_producteev_notification; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, null, when); CharSequence contentTitle = context.getString(R.string.producteev_notification_title)+": "+dashboard.getName(); Filter filter = ProducteevFilterExposer.filterFromList(context, dashboard, userId); Intent notificationIntent = ShortcutActivity.createIntent(filter); // filter the tags from the message String message = notificationsList[i].replaceAll("<[^>]+>", ""); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, message, contentIntent); nm.notify(Constants.NOTIFICATION_PRODUCTEEV_NOTIFICATIONS-i, notification); } } // store lastIds in Preferences Preferences.setString(ProducteevUtilities.PREF_SERVER_LAST_NOTIFICATION, lastNotificationId); Preferences.setString(ProducteevUtilities.PREF_SERVER_LAST_ACTIVITY, lastActivityId); StatisticsService.reportEvent("pdv-sync-finished"); //$NON-NLS-1$ Flags.set(Flags.REFRESH); } catch (IllegalStateException e) { // occurs when application was closed } catch (Exception e) { handleException("pdv-sync", e, true); //$NON-NLS-1$ } }
protected void performSync() { StatisticsService.reportEvent("producteev-started"); preferences.recordSyncStart(); try { // load user information JSONObject user = invoker.usersView(null).getJSONObject("user"); saveUserData(user); String lastServerSync = Preferences.getStringValue(ProducteevUtilities.PREF_SERVER_LAST_SYNC); String lastNotificationId = Preferences.getStringValue(ProducteevUtilities.PREF_SERVER_LAST_NOTIFICATION); String lastActivityId = Preferences.getStringValue(ProducteevUtilities.PREF_SERVER_LAST_ACTIVITY); // read dashboards JSONArray dashboards = invoker.dashboardsShowList(lastServerSync); dataService.updateDashboards(dashboards); // read labels and tasks for each dashboard ArrayList<ProducteevTaskContainer> remoteTasks = new ArrayList<ProducteevTaskContainer>(); for(StoreObject dashboard : dataService.getDashboards()) { long dashboardId = dashboard.getValue(ProducteevDashboard.REMOTE_ID); JSONArray labels = invoker.labelsShowList(dashboardId, null); readLabels(labels); try { // This invocation throws ApiServiceException for workspaces that need to be upgraded JSONArray tasks = invoker.tasksShowList(dashboardId, lastServerSync); for(int i = 0; i < tasks.length(); i++) { ProducteevTaskContainer remote = parseRemoteTask(tasks.getJSONObject(i)); if(remote.pdvTask.getValue(ProducteevTask.CREATOR_ID) != userId && remote.pdvTask.getValue(ProducteevTask.RESPONSIBLE_ID) != userId) remote.task.setFlag(Task.FLAGS, Task.FLAG_IS_READONLY, true); else remote.task.setFlag(Task.FLAGS, Task.FLAG_IS_READONLY, false); // update reminder flags for incoming remote tasks to prevent annoying if(remote.task.hasDueDate() && remote.task.getValue(Task.DUE_DATE) < DateUtilities.now()) remote.task.setFlag(Task.REMINDER_FLAGS, Task.NOTIFY_AFTER_DEADLINE, false); dataService.findLocalMatch(remote); remoteTasks.add(remote); } } catch (ApiServiceException ase) { // catch it here, so that other dashboards can still be synchronized handleException("pdv-sync", ase, true); //$NON-NLS-1$ } } SyncData<ProducteevTaskContainer> syncData = populateSyncData(remoteTasks); try { synchronizeTasks(syncData); } finally { syncData.localCreated.close(); syncData.localUpdated.close(); } Preferences.setString(ProducteevUtilities.PREF_SERVER_LAST_SYNC, invoker.time()); preferences.recordSuccessfulSync(); Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH); ContextManager.getContext().sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ); // notification/activities stuff JSONArray notifications = invoker.activitiesShowNotifications(null, (lastNotificationId == null ? null : new Long(lastNotificationId))); String[] notificationsList = parseActivities(notifications); // update lastIds if (notifications.length() > 0) { lastNotificationId = ""+notifications.getJSONObject(0).getJSONObject("activity").getLong("id_activity"); } // display notifications from producteev-log Context context = ContextManager.getContext(); final NotificationManager nm = new NotificationManager.AndroidNotificationManager(context); for (int i = 0; i< notificationsList.length; i++) { long id_dashboard = notifications.getJSONObject(i).getJSONObject("activity").getLong("id_dashboard"); String dashboardName = null; StoreObject[] dashboardsData = ProducteevDataService.getInstance().getDashboards(); ProducteevDashboard dashboard = null; if (dashboardsData != null) { for (int j=0; i<dashboardsData.length;i++) { long id = dashboardsData[j].getValue(ProducteevDashboard.REMOTE_ID); if (id == id_dashboard) { dashboardName = dashboardsData[j].getValue(ProducteevDashboard.NAME); dashboard = new ProducteevDashboard(id, dashboardName, null); break; } } } // it seems dashboard is null if we get a notification about an unknown dashboard, just filter it. if (dashboard != null) { // initialize notification int icon = R.drawable.ic_producteev_notification; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, null, when); CharSequence contentTitle = context.getString(R.string.producteev_notification_title)+": "+dashboard.getName(); Filter filter = ProducteevFilterExposer.filterFromList(context, dashboard, userId); Intent notificationIntent = ShortcutActivity.createIntent(filter); // filter the tags from the message String message = notificationsList[i].replaceAll("<[^>]+>", ""); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, message, contentIntent); nm.notify(Constants.NOTIFICATION_PRODUCTEEV_NOTIFICATIONS-i, notification); } } // store lastIds in Preferences Preferences.setString(ProducteevUtilities.PREF_SERVER_LAST_NOTIFICATION, lastNotificationId); Preferences.setString(ProducteevUtilities.PREF_SERVER_LAST_ACTIVITY, lastActivityId); StatisticsService.reportEvent("pdv-sync-finished"); //$NON-NLS-1$ Flags.set(Flags.REFRESH); } catch (IllegalStateException e) { // occurs when application was closed } catch (Exception e) { handleException("pdv-sync", e, true); //$NON-NLS-1$ } }
diff --git a/src/main/java/org/apache/maven/artifact/ant/DependenciesTask.java b/src/main/java/org/apache/maven/artifact/ant/DependenciesTask.java index de17787..28b9991 100644 --- a/src/main/java/org/apache/maven/artifact/ant/DependenciesTask.java +++ b/src/main/java/org/apache/maven/artifact/ant/DependenciesTask.java @@ -1,623 +1,631 @@ package org.apache.maven.artifact.ant; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ant.util.AntBuildWriter; import org.apache.maven.artifact.ant.util.AntTaskModified; import org.apache.maven.artifact.ant.util.AntUtil; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.resolver.ArtifactResolutionResult; import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.artifact.resolver.filter.AndArtifactFilter; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; import org.apache.maven.model.Dependency; import org.apache.maven.project.artifact.InvalidDependencyVersionException; import org.apache.maven.project.artifact.MavenMetadataSource; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Path; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * Dependencies task, using maven-artifact. * * @author <a href="mailto:[email protected]">Brett Porter</a> * @author <a href="mailto:[email protected]">Herve Boutemy</a> * @version $Id$ */ public class DependenciesTask extends AbstractArtifactWithRepositoryTask { private static final String[] SCOPES = { Artifact.SCOPE_COMPILE, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_RUNTIME, Artifact.SCOPE_TEST, Artifact.SCOPE_SYSTEM }; private static final Set<String> SCOPES_SET; static { SCOPES_SET = new HashSet<String>( Arrays.asList( SCOPES ) ); } public static final String DEFAULT_ANT_BUILD_FILE = "target/build-dependencies.xml"; private List<Dependency> dependencies = new ArrayList<Dependency>(); /** * The id of the path object containing a list of all dependencies. */ private String pathId; /** * The id of the fileset object containing a list of all dependencies. */ private String filesetId; /** * The id of the fileset object containing all resolved source jars for the list of dependencies. */ private String sourcesFilesetId; /** * The id of the fileset object containing all resolved javadoc jars for the list of dependencies. */ private String javadocFilesetId; /** * The id of the object containing a list of all artifact versions. * This is used for things like removing the version from the dependency filenames. */ private String versionsId; /** * A specific Maven scope used to determine which dependencies are resolved. * This takes only a single scope and uses the standard Maven ScopeArtifactFilter. */ private String useScope; /** * A comma separated list of dependency scopes to include, in the resulting path and fileset. */ private String scopes; /** * A comma separated list of dependency types to include in the resulting set of artifacts. */ private String type; /** * The file name to use for the generated Ant build that contains dependency properties and references. */ private String dependencyRefsBuildFile; /** * Whether to use a generated Ant build file to cache the list of dependency properties and references. */ private boolean cacheDependencyRefs; /** * Main task execution. Called by parent execute(). */ protected void doExecute() { if ( useScope != null && scopes != null ) { throw new BuildException( "You cannot specify both useScope and scopes in the dependencies task." ); } if ( getPom() != null && !this.dependencies.isEmpty() ) { throw new BuildException( "You cannot specify both dependencies and a pom in the dependencies task" ); } // Try to load dependency refs from an existing Ant cache file if ( isCacheDependencyRefs() ) { if ( getDependencyRefsBuildFile() == null ) { setDependencyRefsBuildFile( DEFAULT_ANT_BUILD_FILE ); } if ( checkCachedDependencies() ) { log( "Dependency refs loaded from file: " + getDependencyRefsBuildFile(), Project.MSG_VERBOSE ); return; } } doExecuteResolution(); } protected ArtifactResolutionResult doExecuteResolution() { ArtifactRepository localRepo = createLocalArtifactRepository(); log( "Using local repository: " + localRepo.getBasedir(), Project.MSG_VERBOSE ); // Look up required resources from the plexus container ArtifactResolver resolver = (ArtifactResolver) lookup( ArtifactResolver.ROLE ); ArtifactFactory artifactFactory = (ArtifactFactory) lookup( ArtifactFactory.ROLE ); MavenMetadataSource metadataSource = (MavenMetadataSource) lookup( ArtifactMetadataSource.ROLE ); Pom pom = initializePom( localRepo ); if ( pom != null ) { dependencies = pom.getDependencies(); } else { // we have to have some sort of Pom object in order to satisfy the requirements for building the // originating Artifact below... pom = createDummyPom( localRepo ); } if ( dependencies.isEmpty() ) { log( "There were no dependencies specified", Project.MSG_WARN ); } else { // check scopes for ( Dependency dependency : dependencies ) { String scope = dependency.getScope(); - if ( ( scope != null ) && !SCOPES_SET.contains( scope ) ) + if ( Artifact.SCOPE_SYSTEM.equals( scope ) ) + { + if ( StringUtils.isBlank( dependency.getSystemPath() ) ) + { + throw new BuildException( dependency.toString() + + " is defined with scope='system': systemPath attribute is required." ); + } + } + else if ( ( scope != null ) && !SCOPES_SET.contains( scope ) ) { // see MANTTASKS-190 log( "Unknown scope='" + scope + "' for " + dependency + ", supported scopes are: " + SCOPES_SET, Project.MSG_WARN ); } } } log( "Resolving dependencies...", Project.MSG_VERBOSE ); ArtifactResolutionResult result; List<ArtifactRepository> remoteArtifactRepositories = createRemoteArtifactRepositories( pom.getRepositories() ); try { Set<Artifact> artifacts = MavenMetadataSource.createArtifacts( artifactFactory, dependencies, null, null, null ); Artifact pomArtifact = artifactFactory.createBuildArtifact( pom.getGroupId(), pom.getArtifactId(), pom.getVersion(), pom.getPackaging() ); List<AntResolutionListener> listeners = Collections.singletonList( new AntResolutionListener( getProject() ) ); Map<String,Artifact> managedDependencies = pom.getMavenProject().getManagedVersionMap(); ArtifactFilter filter = null; if ( useScope != null ) { filter = new ScopeArtifactFilter( useScope ); } if ( scopes != null ) { filter = new SpecificScopesArtifactFilter( scopes ); } if ( type != null ) { ArtifactFilter typeArtifactFilter = new TypesArtifactFilter( type ); if ( filter != null ) { AndArtifactFilter andFilter = new AndArtifactFilter(); andFilter.add( filter ); andFilter.add( typeArtifactFilter ); filter = andFilter; } else { filter = typeArtifactFilter; } } result = resolver.resolveTransitively( artifacts, pomArtifact, managedDependencies, localRepo, remoteArtifactRepositories, metadataSource, filter, listeners ); } catch ( ArtifactResolutionException e ) { throw new BuildException( "Unable to resolve artifact: " + e.getMessage(), e ); } catch ( ArtifactNotFoundException e ) { throw new BuildException( "Dependency not found: " + e.getMessage(), e ); } catch ( InvalidDependencyVersionException e ) { throw new BuildException( "Invalid dependency version: " + e.getMessage(), e ); } FileSet dependencyFileSet = createFileSet(); FileSet sourcesFileSet = createFileSet(); FileSet javadocsFileSet = createFileSet(); Path dependencyPath = new Path( getProject() ); Set<String> versions = new HashSet<String>(); for ( Iterator<Artifact> i = result.getArtifacts().iterator(); i.hasNext(); ) { Artifact artifact = (Artifact) i.next(); addArtifactToResult( localRepo, artifact, dependencyFileSet, dependencyPath ); versions.add( artifact.getVersion() ); if ( sourcesFilesetId != null ) { resolveSource( artifactFactory, resolver, remoteArtifactRepositories, localRepo, artifact, "sources", sourcesFileSet ); } if ( javadocFilesetId != null ) { resolveSource( artifactFactory, resolver, remoteArtifactRepositories, localRepo, artifact, "javadoc", javadocsFileSet ); } } defineFilesetReference( filesetId, dependencyFileSet ); defineFilesetReference( sourcesFilesetId, sourcesFileSet ); defineFilesetReference( javadocFilesetId, javadocsFileSet ); if ( pathId != null ) { getProject().addReference( pathId, dependencyPath ); } if ( versionsId != null ) { String versionsValue = StringUtils.join( versions.iterator(), File.pathSeparator ); getProject().setNewProperty( versionsId, versionsValue ); } // Write the dependency information to an Ant build file. if ( getDependencyRefsBuildFile() != null || this.isCacheDependencyRefs() ) { if ( getDependencyRefsBuildFile() == null || getDependencyRefsBuildFile().equals( "default" ) ) { setDependencyRefsBuildFile( DEFAULT_ANT_BUILD_FILE ); } log( "Building ant file: " + getDependencyRefsBuildFile()); AntBuildWriter antBuildWriter = new AntBuildWriter(); File antBuildFile = new File( getProject().getBaseDir(), getDependencyRefsBuildFile() ); try { antBuildWriter.openAntBuild( antBuildFile, "maven-dependencies", "init-dependencies" ); antBuildWriter.openTarget( "init-dependencies" ); antBuildWriter.writeEcho( "Loading dependency paths from file: " + antBuildFile.getAbsolutePath() ); for ( Iterator<Artifact> i = result.getArtifacts().iterator(); i.hasNext(); ) { Artifact artifact = (Artifact) i.next(); String conflictId = artifact.getDependencyConflictId(); antBuildWriter.writeProperty( conflictId, artifact.getFile().getAbsolutePath() ); FileSet singleArtifactFileSet = (FileSet)getProject().getReference( conflictId ); antBuildWriter.writeFileSet( singleArtifactFileSet, conflictId ); } if ( pathId != null ) { Path thePath = (Path)getProject().getReference( pathId ); antBuildWriter.writePath( thePath, pathId ); } if ( filesetId != null ) { antBuildWriter.writeFileSet( dependencyFileSet, filesetId ); } if ( sourcesFilesetId != null ) { antBuildWriter.writeFileSet( sourcesFileSet, sourcesFilesetId ); } if ( javadocFilesetId != null ) { antBuildWriter.writeFileSet( sourcesFileSet, javadocFilesetId ); } String versionsList = getProject().getProperty( versionsId ); antBuildWriter.writeProperty( versionsId, versionsList ); antBuildWriter.closeTarget(); antBuildWriter.closeAntBuild(); } catch ( IOException e ) { throw new BuildException ( "Unable to write ant build: " + e); } } return result; } /** * Check if the cache needs to be updated. * * @return true if the dependency refs were successfully loaded, false otherwise */ private boolean checkCachedDependencies() { File cacheBuildFile = new File( getProject().getBaseDir(), getDependencyRefsBuildFile() ); if ( ! cacheBuildFile.exists() ) { return false; } File antBuildFile = new File( getProject().getProperty( "ant.file" ) ); if ( antBuildFile.lastModified() > cacheBuildFile.lastModified() ) { return false; } Pom pom = getPom(); if ( pom != null ) { File pomFile = pom.getFile(); if ( pomFile == null || ( pomFile.lastModified() > cacheBuildFile.lastModified() ) ) { return false; } } return loadDependenciesFromAntBuildFile(); } /** * Load the dependency references from the generated ant build file. * * @return True if the dependency refs were successfully loaded. */ private boolean loadDependenciesFromAntBuildFile() { Project currentAntProject = getProject(); // Run the ant build with the dependency refs AntTaskModified dependenciesAntBuild = new AntTaskModified(); dependenciesAntBuild.setAntfile( getDependencyRefsBuildFile() ); dependenciesAntBuild.setProject( currentAntProject ); dependenciesAntBuild.execute(); // Copy the properties and refs to the current project Project cachedDepsProject = dependenciesAntBuild.getSavedNewProject(); AntUtil.copyProperties( cachedDepsProject, currentAntProject ); AntUtil.copyReferences( cachedDepsProject, currentAntProject ); return true; } private FileSet createFileSet() { FileSet fileSet = new FileSet(); fileSet.setProject( getProject() ); fileSet.setDir( getLocalRepository().getPath() ); return fileSet; } private void defineFilesetReference( String id, FileSet fileSet ) { if ( id != null ) { if ( !fileSet.hasPatterns() ) { fileSet.createExclude().setName( "**/**" ); } getProject().addReference( id, fileSet ); } } private void addArtifactToResult( ArtifactRepository localRepo, Artifact artifact, FileSet toFileSet ) { addArtifactToResult( localRepo, artifact, toFileSet, null ); } private void addArtifactToResult( ArtifactRepository localRepo, Artifact artifact, FileSet toFileSet, Path path ) { String filename = localRepo.pathOf( artifact ); toFileSet.createInclude().setName( filename ); getProject().setProperty( artifact.getDependencyConflictId(), artifact.getFile().getAbsolutePath() ); FileSet artifactFileSet = new FileSet(); artifactFileSet.setProject( getProject() ); artifactFileSet.setFile( artifact.getFile() ); getProject().addReference( artifact.getDependencyConflictId(), artifactFileSet ); if ( path != null ) { path.addFileset( artifactFileSet ); } } private void resolveSource( ArtifactFactory artifactFactory, ArtifactResolver resolver, List<ArtifactRepository> remoteArtifactRepositories, ArtifactRepository localRepo, Artifact artifact, String classifier, FileSet sourcesFileSet ) { Artifact sourceArtifact = artifactFactory.createArtifactWithClassifier( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), "java-source", classifier ); try { resolver.resolve( sourceArtifact, remoteArtifactRepositories, localRepo ); addArtifactToResult( localRepo, sourceArtifact, sourcesFileSet ); } catch ( ArtifactResolutionException e ) { throw new BuildException( "Unable to resolve artifact: " + e.getMessage(), e ); } catch ( ArtifactNotFoundException e ) { // no source available: no problem, it's optional } } public List<Dependency> getDependencies() { return dependencies; } public void addDependency( Dependency dependency ) { dependencies.add( dependency ); } public String getPathId() { return pathId; } public void setPathId( String pathId ) { this.pathId = pathId; } public String getFilesetId() { return filesetId; } public void setSourcesFilesetId( String filesetId ) { this.sourcesFilesetId = filesetId; } public String getSourcesFilesetId() { return sourcesFilesetId; } public void setJavadocFilesetId( String filesetId ) { this.javadocFilesetId = filesetId; } public String getJavadocFilesetId() { return javadocFilesetId; } public void setFilesetId( String filesetId ) { this.filesetId = filesetId; } public String getVersionsId() { return versionsId; } public void setVersionsId( String versionsId ) { this.versionsId = versionsId; } public void setVerbose( boolean verbose ) { getProject().log( "Option \"verbose\" is deprecated. Please use the standard Ant -v option.", Project.MSG_WARN ); } /** * Use the Maven artifact filtering for a particular scope. This * uses the standard Maven ScopeArtifactFilter. * * @param useScope */ public void setUseScope( String useScope ) { this.useScope = useScope; } public void setType( String type ) { this.type = type; } public String getScopes() { return scopes; } /** * Only include artifacts that fall under one of the specified scopes. * * @return */ public void setScopes( String scopes ) { this.scopes = scopes; } /** * @deprecated * @param addArtifactFileSetRefs */ public void setAddArtifactFileSetRefs( boolean addArtifactFileSetRefs ) { this.log( "Parameter addArtifactFileSetRefs is deprecated. A fileset ref is always created " + "for each dependency.", Project.MSG_WARN ); } public String getDependencyRefsBuildFile() { return dependencyRefsBuildFile; } public void setDependencyRefsBuildFile( String dependencyRefsBuildFile ) { this.dependencyRefsBuildFile = dependencyRefsBuildFile; } public boolean isCacheDependencyRefs() { return cacheDependencyRefs; } public void setCacheDependencyRefs( boolean cacheDependencyRefs ) { this.cacheDependencyRefs = cacheDependencyRefs; } }
true
true
protected ArtifactResolutionResult doExecuteResolution() { ArtifactRepository localRepo = createLocalArtifactRepository(); log( "Using local repository: " + localRepo.getBasedir(), Project.MSG_VERBOSE ); // Look up required resources from the plexus container ArtifactResolver resolver = (ArtifactResolver) lookup( ArtifactResolver.ROLE ); ArtifactFactory artifactFactory = (ArtifactFactory) lookup( ArtifactFactory.ROLE ); MavenMetadataSource metadataSource = (MavenMetadataSource) lookup( ArtifactMetadataSource.ROLE ); Pom pom = initializePom( localRepo ); if ( pom != null ) { dependencies = pom.getDependencies(); } else { // we have to have some sort of Pom object in order to satisfy the requirements for building the // originating Artifact below... pom = createDummyPom( localRepo ); } if ( dependencies.isEmpty() ) { log( "There were no dependencies specified", Project.MSG_WARN ); } else { // check scopes for ( Dependency dependency : dependencies ) { String scope = dependency.getScope(); if ( ( scope != null ) && !SCOPES_SET.contains( scope ) ) { // see MANTTASKS-190 log( "Unknown scope='" + scope + "' for " + dependency + ", supported scopes are: " + SCOPES_SET, Project.MSG_WARN ); } } } log( "Resolving dependencies...", Project.MSG_VERBOSE ); ArtifactResolutionResult result; List<ArtifactRepository> remoteArtifactRepositories = createRemoteArtifactRepositories( pom.getRepositories() ); try { Set<Artifact> artifacts = MavenMetadataSource.createArtifacts( artifactFactory, dependencies, null, null, null ); Artifact pomArtifact = artifactFactory.createBuildArtifact( pom.getGroupId(), pom.getArtifactId(), pom.getVersion(), pom.getPackaging() ); List<AntResolutionListener> listeners = Collections.singletonList( new AntResolutionListener( getProject() ) ); Map<String,Artifact> managedDependencies = pom.getMavenProject().getManagedVersionMap(); ArtifactFilter filter = null; if ( useScope != null ) { filter = new ScopeArtifactFilter( useScope ); } if ( scopes != null ) { filter = new SpecificScopesArtifactFilter( scopes ); } if ( type != null ) { ArtifactFilter typeArtifactFilter = new TypesArtifactFilter( type ); if ( filter != null ) { AndArtifactFilter andFilter = new AndArtifactFilter(); andFilter.add( filter ); andFilter.add( typeArtifactFilter ); filter = andFilter; } else { filter = typeArtifactFilter; } } result = resolver.resolveTransitively( artifacts, pomArtifact, managedDependencies, localRepo, remoteArtifactRepositories, metadataSource, filter, listeners ); } catch ( ArtifactResolutionException e ) { throw new BuildException( "Unable to resolve artifact: " + e.getMessage(), e ); } catch ( ArtifactNotFoundException e ) { throw new BuildException( "Dependency not found: " + e.getMessage(), e ); } catch ( InvalidDependencyVersionException e ) { throw new BuildException( "Invalid dependency version: " + e.getMessage(), e ); } FileSet dependencyFileSet = createFileSet(); FileSet sourcesFileSet = createFileSet(); FileSet javadocsFileSet = createFileSet(); Path dependencyPath = new Path( getProject() ); Set<String> versions = new HashSet<String>(); for ( Iterator<Artifact> i = result.getArtifacts().iterator(); i.hasNext(); ) { Artifact artifact = (Artifact) i.next(); addArtifactToResult( localRepo, artifact, dependencyFileSet, dependencyPath ); versions.add( artifact.getVersion() ); if ( sourcesFilesetId != null ) { resolveSource( artifactFactory, resolver, remoteArtifactRepositories, localRepo, artifact, "sources", sourcesFileSet ); } if ( javadocFilesetId != null ) { resolveSource( artifactFactory, resolver, remoteArtifactRepositories, localRepo, artifact, "javadoc", javadocsFileSet ); } } defineFilesetReference( filesetId, dependencyFileSet ); defineFilesetReference( sourcesFilesetId, sourcesFileSet ); defineFilesetReference( javadocFilesetId, javadocsFileSet ); if ( pathId != null ) { getProject().addReference( pathId, dependencyPath ); } if ( versionsId != null ) { String versionsValue = StringUtils.join( versions.iterator(), File.pathSeparator ); getProject().setNewProperty( versionsId, versionsValue ); } // Write the dependency information to an Ant build file. if ( getDependencyRefsBuildFile() != null || this.isCacheDependencyRefs() ) { if ( getDependencyRefsBuildFile() == null || getDependencyRefsBuildFile().equals( "default" ) ) { setDependencyRefsBuildFile( DEFAULT_ANT_BUILD_FILE ); } log( "Building ant file: " + getDependencyRefsBuildFile()); AntBuildWriter antBuildWriter = new AntBuildWriter(); File antBuildFile = new File( getProject().getBaseDir(), getDependencyRefsBuildFile() ); try { antBuildWriter.openAntBuild( antBuildFile, "maven-dependencies", "init-dependencies" ); antBuildWriter.openTarget( "init-dependencies" ); antBuildWriter.writeEcho( "Loading dependency paths from file: " + antBuildFile.getAbsolutePath() ); for ( Iterator<Artifact> i = result.getArtifacts().iterator(); i.hasNext(); ) { Artifact artifact = (Artifact) i.next(); String conflictId = artifact.getDependencyConflictId(); antBuildWriter.writeProperty( conflictId, artifact.getFile().getAbsolutePath() ); FileSet singleArtifactFileSet = (FileSet)getProject().getReference( conflictId ); antBuildWriter.writeFileSet( singleArtifactFileSet, conflictId ); } if ( pathId != null ) { Path thePath = (Path)getProject().getReference( pathId ); antBuildWriter.writePath( thePath, pathId ); } if ( filesetId != null ) { antBuildWriter.writeFileSet( dependencyFileSet, filesetId ); } if ( sourcesFilesetId != null ) { antBuildWriter.writeFileSet( sourcesFileSet, sourcesFilesetId ); } if ( javadocFilesetId != null ) { antBuildWriter.writeFileSet( sourcesFileSet, javadocFilesetId ); } String versionsList = getProject().getProperty( versionsId ); antBuildWriter.writeProperty( versionsId, versionsList ); antBuildWriter.closeTarget(); antBuildWriter.closeAntBuild(); } catch ( IOException e ) { throw new BuildException ( "Unable to write ant build: " + e); } } return result; }
protected ArtifactResolutionResult doExecuteResolution() { ArtifactRepository localRepo = createLocalArtifactRepository(); log( "Using local repository: " + localRepo.getBasedir(), Project.MSG_VERBOSE ); // Look up required resources from the plexus container ArtifactResolver resolver = (ArtifactResolver) lookup( ArtifactResolver.ROLE ); ArtifactFactory artifactFactory = (ArtifactFactory) lookup( ArtifactFactory.ROLE ); MavenMetadataSource metadataSource = (MavenMetadataSource) lookup( ArtifactMetadataSource.ROLE ); Pom pom = initializePom( localRepo ); if ( pom != null ) { dependencies = pom.getDependencies(); } else { // we have to have some sort of Pom object in order to satisfy the requirements for building the // originating Artifact below... pom = createDummyPom( localRepo ); } if ( dependencies.isEmpty() ) { log( "There were no dependencies specified", Project.MSG_WARN ); } else { // check scopes for ( Dependency dependency : dependencies ) { String scope = dependency.getScope(); if ( Artifact.SCOPE_SYSTEM.equals( scope ) ) { if ( StringUtils.isBlank( dependency.getSystemPath() ) ) { throw new BuildException( dependency.toString() + " is defined with scope='system': systemPath attribute is required." ); } } else if ( ( scope != null ) && !SCOPES_SET.contains( scope ) ) { // see MANTTASKS-190 log( "Unknown scope='" + scope + "' for " + dependency + ", supported scopes are: " + SCOPES_SET, Project.MSG_WARN ); } } } log( "Resolving dependencies...", Project.MSG_VERBOSE ); ArtifactResolutionResult result; List<ArtifactRepository> remoteArtifactRepositories = createRemoteArtifactRepositories( pom.getRepositories() ); try { Set<Artifact> artifacts = MavenMetadataSource.createArtifacts( artifactFactory, dependencies, null, null, null ); Artifact pomArtifact = artifactFactory.createBuildArtifact( pom.getGroupId(), pom.getArtifactId(), pom.getVersion(), pom.getPackaging() ); List<AntResolutionListener> listeners = Collections.singletonList( new AntResolutionListener( getProject() ) ); Map<String,Artifact> managedDependencies = pom.getMavenProject().getManagedVersionMap(); ArtifactFilter filter = null; if ( useScope != null ) { filter = new ScopeArtifactFilter( useScope ); } if ( scopes != null ) { filter = new SpecificScopesArtifactFilter( scopes ); } if ( type != null ) { ArtifactFilter typeArtifactFilter = new TypesArtifactFilter( type ); if ( filter != null ) { AndArtifactFilter andFilter = new AndArtifactFilter(); andFilter.add( filter ); andFilter.add( typeArtifactFilter ); filter = andFilter; } else { filter = typeArtifactFilter; } } result = resolver.resolveTransitively( artifacts, pomArtifact, managedDependencies, localRepo, remoteArtifactRepositories, metadataSource, filter, listeners ); } catch ( ArtifactResolutionException e ) { throw new BuildException( "Unable to resolve artifact: " + e.getMessage(), e ); } catch ( ArtifactNotFoundException e ) { throw new BuildException( "Dependency not found: " + e.getMessage(), e ); } catch ( InvalidDependencyVersionException e ) { throw new BuildException( "Invalid dependency version: " + e.getMessage(), e ); } FileSet dependencyFileSet = createFileSet(); FileSet sourcesFileSet = createFileSet(); FileSet javadocsFileSet = createFileSet(); Path dependencyPath = new Path( getProject() ); Set<String> versions = new HashSet<String>(); for ( Iterator<Artifact> i = result.getArtifacts().iterator(); i.hasNext(); ) { Artifact artifact = (Artifact) i.next(); addArtifactToResult( localRepo, artifact, dependencyFileSet, dependencyPath ); versions.add( artifact.getVersion() ); if ( sourcesFilesetId != null ) { resolveSource( artifactFactory, resolver, remoteArtifactRepositories, localRepo, artifact, "sources", sourcesFileSet ); } if ( javadocFilesetId != null ) { resolveSource( artifactFactory, resolver, remoteArtifactRepositories, localRepo, artifact, "javadoc", javadocsFileSet ); } } defineFilesetReference( filesetId, dependencyFileSet ); defineFilesetReference( sourcesFilesetId, sourcesFileSet ); defineFilesetReference( javadocFilesetId, javadocsFileSet ); if ( pathId != null ) { getProject().addReference( pathId, dependencyPath ); } if ( versionsId != null ) { String versionsValue = StringUtils.join( versions.iterator(), File.pathSeparator ); getProject().setNewProperty( versionsId, versionsValue ); } // Write the dependency information to an Ant build file. if ( getDependencyRefsBuildFile() != null || this.isCacheDependencyRefs() ) { if ( getDependencyRefsBuildFile() == null || getDependencyRefsBuildFile().equals( "default" ) ) { setDependencyRefsBuildFile( DEFAULT_ANT_BUILD_FILE ); } log( "Building ant file: " + getDependencyRefsBuildFile()); AntBuildWriter antBuildWriter = new AntBuildWriter(); File antBuildFile = new File( getProject().getBaseDir(), getDependencyRefsBuildFile() ); try { antBuildWriter.openAntBuild( antBuildFile, "maven-dependencies", "init-dependencies" ); antBuildWriter.openTarget( "init-dependencies" ); antBuildWriter.writeEcho( "Loading dependency paths from file: " + antBuildFile.getAbsolutePath() ); for ( Iterator<Artifact> i = result.getArtifacts().iterator(); i.hasNext(); ) { Artifact artifact = (Artifact) i.next(); String conflictId = artifact.getDependencyConflictId(); antBuildWriter.writeProperty( conflictId, artifact.getFile().getAbsolutePath() ); FileSet singleArtifactFileSet = (FileSet)getProject().getReference( conflictId ); antBuildWriter.writeFileSet( singleArtifactFileSet, conflictId ); } if ( pathId != null ) { Path thePath = (Path)getProject().getReference( pathId ); antBuildWriter.writePath( thePath, pathId ); } if ( filesetId != null ) { antBuildWriter.writeFileSet( dependencyFileSet, filesetId ); } if ( sourcesFilesetId != null ) { antBuildWriter.writeFileSet( sourcesFileSet, sourcesFilesetId ); } if ( javadocFilesetId != null ) { antBuildWriter.writeFileSet( sourcesFileSet, javadocFilesetId ); } String versionsList = getProject().getProperty( versionsId ); antBuildWriter.writeProperty( versionsId, versionsList ); antBuildWriter.closeTarget(); antBuildWriter.closeAntBuild(); } catch ( IOException e ) { throw new BuildException ( "Unable to write ant build: " + e); } } return result; }
diff --git a/src/com/android/browser/ComboViewActivity.java b/src/com/android/browser/ComboViewActivity.java index ae49898b..2d382cb3 100644 --- a/src/com/android/browser/ComboViewActivity.java +++ b/src/com/android/browser/ComboViewActivity.java @@ -1,248 +1,249 @@ /* * Copyright (C) 2011 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.browser; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v13.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuItem; import com.android.browser.UI.ComboViews; import java.util.ArrayList; public class ComboViewActivity extends Activity implements CombinedBookmarksCallbacks { private static final String STATE_SELECTED_TAB = "tab"; public static final String EXTRA_COMBO_ARGS = "combo_args"; public static final String EXTRA_INITIAL_VIEW = "initial_view"; public static final String EXTRA_OPEN_SNAPSHOT = "snapshot_id"; public static final String EXTRA_OPEN_ALL = "open_all"; public static final String EXTRA_CURRENT_URL = "url"; private ViewPager mViewPager; private TabsAdapter mTabsAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setResult(RESULT_CANCELED); Bundle extras = getIntent().getExtras(); Bundle args = extras.getBundle(EXTRA_COMBO_ARGS); String svStr = extras.getString(EXTRA_INITIAL_VIEW, null); ComboViews startingView = svStr != null ? ComboViews.valueOf(svStr) : ComboViews.Bookmarks; mViewPager = new ViewPager(this); mViewPager.setId(R.id.tab_view); setContentView(mViewPager); final ActionBar bar = getActionBar(); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); if (BrowserActivity.isTablet(this)) { bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_USE_LOGO); + bar.setHomeButtonEnabled(true); } else { bar.setDisplayOptions(0); } mTabsAdapter = new TabsAdapter(this, mViewPager); mTabsAdapter.addTab(bar.newTab().setText(R.string.tab_bookmarks), BrowserBookmarksPage.class, args); mTabsAdapter.addTab(bar.newTab().setText(R.string.tab_history), BrowserHistoryPage.class, args); mTabsAdapter.addTab(bar.newTab().setText(R.string.tab_snapshots), BrowserSnapshotPage.class, args); if (savedInstanceState != null) { bar.setSelectedNavigationItem( savedInstanceState.getInt(STATE_SELECTED_TAB, 0)); } else { switch (startingView) { case Bookmarks: mViewPager.setCurrentItem(0); break; case History: mViewPager.setCurrentItem(1); break; case Snapshots: mViewPager.setCurrentItem(2); break; } } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_SELECTED_TAB, getActionBar().getSelectedNavigationIndex()); } @Override public void openUrl(String url) { Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); setResult(RESULT_OK, i); finish(); } @Override public void openInNewTab(String... urls) { Intent i = new Intent(); i.putExtra(EXTRA_OPEN_ALL, urls); setResult(RESULT_OK, i); finish(); } @Override public void close() { finish(); } @Override public void openSnapshot(long id) { Intent i = new Intent(); i.putExtra(EXTRA_OPEN_SNAPSHOT, id); setResult(RESULT_OK, i); finish(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.combined, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); return true; } else if (item.getItemId() == R.id.preferences_menu_id) { String url = getIntent().getStringExtra(EXTRA_CURRENT_URL); Intent intent = new Intent(this, BrowserPreferencesPage.class); intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE, url); startActivityForResult(intent, Controller.PREFERENCES_PAGE); return true; } return super.onOptionsItemSelected(item); } /** * This is a helper class that implements the management of tabs and all * details of connecting a ViewPager with associated TabHost. It relies on a * trick. Normally a tab host has a simple API for supplying a View or * Intent that each tab will show. This is not sufficient for switching * between pages. So instead we make the content part of the tab host * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy * view to show as the tab content. It listens to changes in tabs, and takes * care of switch to the correct page in the ViewPager whenever the selected * tab changes. */ public static class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener { private final Context mContext; private final ActionBar mActionBar; private final ViewPager mViewPager; private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>(); static final class TabInfo { private final Class<?> clss; private final Bundle args; TabInfo(Class<?> _class, Bundle _args) { clss = _class; args = _args; } } public TabsAdapter(Activity activity, ViewPager pager) { super(activity.getFragmentManager()); mContext = activity; mActionBar = activity.getActionBar(); mViewPager = pager; mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); } public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) { TabInfo info = new TabInfo(clss, args); tab.setTag(info); tab.setTabListener(this); mTabs.add(info); mActionBar.addTab(tab); notifyDataSetChanged(); } @Override public int getCount() { return mTabs.size(); } @Override public Fragment getItem(int position) { TabInfo info = mTabs.get(position); return Fragment.instantiate(mContext, info.clss.getName(), info.args); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mActionBar.setSelectedNavigationItem(position); } @Override public void onPageScrollStateChanged(int state) { } @Override public void onTabSelected(android.app.ActionBar.Tab tab, FragmentTransaction ft) { Object tag = tab.getTag(); for (int i=0; i<mTabs.size(); i++) { if (mTabs.get(i) == tag) { mViewPager.setCurrentItem(i); } } } @Override public void onTabUnselected(android.app.ActionBar.Tab tab, FragmentTransaction ft) { } @Override public void onTabReselected(android.app.ActionBar.Tab tab, FragmentTransaction ft) { } } private static String makeFragmentName(int viewId, int index) { return "android:switcher:" + viewId + ":" + index; } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setResult(RESULT_CANCELED); Bundle extras = getIntent().getExtras(); Bundle args = extras.getBundle(EXTRA_COMBO_ARGS); String svStr = extras.getString(EXTRA_INITIAL_VIEW, null); ComboViews startingView = svStr != null ? ComboViews.valueOf(svStr) : ComboViews.Bookmarks; mViewPager = new ViewPager(this); mViewPager.setId(R.id.tab_view); setContentView(mViewPager); final ActionBar bar = getActionBar(); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); if (BrowserActivity.isTablet(this)) { bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_USE_LOGO); } else { bar.setDisplayOptions(0); } mTabsAdapter = new TabsAdapter(this, mViewPager); mTabsAdapter.addTab(bar.newTab().setText(R.string.tab_bookmarks), BrowserBookmarksPage.class, args); mTabsAdapter.addTab(bar.newTab().setText(R.string.tab_history), BrowserHistoryPage.class, args); mTabsAdapter.addTab(bar.newTab().setText(R.string.tab_snapshots), BrowserSnapshotPage.class, args); if (savedInstanceState != null) { bar.setSelectedNavigationItem( savedInstanceState.getInt(STATE_SELECTED_TAB, 0)); } else { switch (startingView) { case Bookmarks: mViewPager.setCurrentItem(0); break; case History: mViewPager.setCurrentItem(1); break; case Snapshots: mViewPager.setCurrentItem(2); break; } } }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setResult(RESULT_CANCELED); Bundle extras = getIntent().getExtras(); Bundle args = extras.getBundle(EXTRA_COMBO_ARGS); String svStr = extras.getString(EXTRA_INITIAL_VIEW, null); ComboViews startingView = svStr != null ? ComboViews.valueOf(svStr) : ComboViews.Bookmarks; mViewPager = new ViewPager(this); mViewPager.setId(R.id.tab_view); setContentView(mViewPager); final ActionBar bar = getActionBar(); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); if (BrowserActivity.isTablet(this)) { bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_USE_LOGO); bar.setHomeButtonEnabled(true); } else { bar.setDisplayOptions(0); } mTabsAdapter = new TabsAdapter(this, mViewPager); mTabsAdapter.addTab(bar.newTab().setText(R.string.tab_bookmarks), BrowserBookmarksPage.class, args); mTabsAdapter.addTab(bar.newTab().setText(R.string.tab_history), BrowserHistoryPage.class, args); mTabsAdapter.addTab(bar.newTab().setText(R.string.tab_snapshots), BrowserSnapshotPage.class, args); if (savedInstanceState != null) { bar.setSelectedNavigationItem( savedInstanceState.getInt(STATE_SELECTED_TAB, 0)); } else { switch (startingView) { case Bookmarks: mViewPager.setCurrentItem(0); break; case History: mViewPager.setCurrentItem(1); break; case Snapshots: mViewPager.setCurrentItem(2); break; } } }
diff --git a/PureJava/org.eclipse.nebula.visualization.xygraph/src/org/eclipse/nebula/visualization/xygraph/linearscale/LinearScaleTicks2.java b/PureJava/org.eclipse.nebula.visualization.xygraph/src/org/eclipse/nebula/visualization/xygraph/linearscale/LinearScaleTicks2.java index 405193e..c8bac3c 100644 --- a/PureJava/org.eclipse.nebula.visualization.xygraph/src/org/eclipse/nebula/visualization/xygraph/linearscale/LinearScaleTicks2.java +++ b/PureJava/org.eclipse.nebula.visualization.xygraph/src/org/eclipse/nebula/visualization/xygraph/linearscale/LinearScaleTicks2.java @@ -1,453 +1,455 @@ /* * Copyright 2012 Diamond Light Source Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.eclipse.nebula.visualization.xygraph.linearscale; import java.util.ArrayList; import java.util.List; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.nebula.visualization.xygraph.linearscale.TickFactory.TickFormatting; /** * Class to represent a major tick */ class Tick { private String text; private double value; private double position; private int tPosition; /** * @param tickText */ public void setText(String tickText) { text = tickText; } /** * @return the tick text */ public String getText() { return text; } /** * @param tickValue */ public void setValue(double tickValue) { value = tickValue; } /** * @return the tick value */ public double getValue() { return value; } /** * @param tickPosition in pixels */ public void setPosition(double tickPosition) { position = tickPosition; } /** * @return the tick position in pixels */ public double getPosition() { return position; } /** * @param textPosition in pixels */ public void setTextPosition(int textPosition) { tPosition = textPosition; } /** * @return the text position in pixels */ public int getTextPosition() { return tPosition; } @Override public String toString() { return text + " (" + value + ", " + position + ", " + tPosition + ")"; } } public class LinearScaleTicks2 implements ITicksProvider { protected List<Tick> ticks; /** the maximum width of tick labels */ private int maxWidth; /** the maximum height of tick labels */ private int maxHeight; /** the array of minor tick positions in pixels */ protected ArrayList<Integer> minorPositions; protected IScaleProvider scale; private boolean ticksIndexBased; public LinearScaleTicks2(IScaleProvider scale) { this.scale = scale; minorPositions = new ArrayList<Integer>(); } @Override public List<Integer> getPositions() { List<Integer> positions = new ArrayList<Integer>(); for (Tick t : ticks) positions.add((int) Math.round(t.getPosition())); return positions; } @Override public int getPosition(int index) { return (int) Math.round(ticks.get(index).getPosition()); } @Override public int getLabelPosition(int index) { return ticks.get(index).getTextPosition(); } @Override public double getValue(int index) { return ticks.get(index).getValue(); } @Override public String getLabel(int index) { return ticks.get(index).getText(); } @Override public boolean isVisible(int index) { return true; } @Override public int getMajorCount() { return ticks == null ? 0 : ticks.size(); } @Override public int getMinorCount() { return minorPositions.size(); } @Override public int getMinorPosition(int index) { return minorPositions.get(index); } @Override public int getMaxWidth() { return maxWidth; } @Override public int getMaxHeight() { return maxHeight; } private final static int TICKMINDIST_IN_PIXELS_X = 40; private final static int TICKMINDIST_IN_PIXELS_Y = 30; private final static int MIN_TICKS = 3; @Override public Range update(final double min, final double max, final int length) { if (scale.isLogScaleEnabled() && (min <= 0 || max <= 0)) throw new IllegalArgumentException("Range for log scale must be in positive range"); final int maximumNumTicks = scale.isHorizontal() ? Math.min(8, length / TICKMINDIST_IN_PIXELS_X) : Math.min(8, length / TICKMINDIST_IN_PIXELS_Y); int numTicks = Math.max(3, maximumNumTicks); final TickFactory tf; if (scale instanceof AbstractScale) { AbstractScale aScale = (AbstractScale) scale; if (aScale.hasUserDefinedFormat()) { tf = new TickFactory(scale); } else if (aScale.isAutoFormat()) { tf = new TickFactory(TickFormatting.autoMode, scale); } else { String format = aScale.getFormatPattern(); if (format.contains("E")) { tf = new TickFactory(TickFormatting.useExponent, scale); } else { tf = new TickFactory(TickFormatting.autoMode, scale); } } } else { tf = new TickFactory(TickFormatting.autoMode, scale); } final int hMargin = getHeadMargin(); final int tMargin = getTailMargin(); // loop until labels fit do { if (ticksIndexBased) { ticks = tf.generateIndexBasedTicks(min, max, numTicks, !scale.hasTicksAtEnds()); } else if (scale.isLogScaleEnabled()) { ticks = tf.generateLogTicks(min, max, numTicks, true, !scale.hasTicksAtEnds()); } else { ticks = tf.generateTicks(min, max, numTicks, true, !scale.hasTicksAtEnds()); } } while (!updateLabelPositionsAndCheckGaps(length, hMargin, tMargin, min > max) && numTicks-- > MIN_TICKS); updateMinorTicks(hMargin+length); if (scale.hasTicksAtEnds() && ticks.size() > 1) return new Range(ticks.get(0).getValue(), ticks.get(ticks.size() - 1).getValue()); return null; } @Override public String getDefaultFormatPattern(double min, double max) { String format = null; // calculate the default decimal format double mantissa = Math.abs(max - min); if (mantissa > 0.1) format = "############.##"; else { format = "##.##"; while (mantissa < 1 && mantissa > 0) { mantissa *= 10.0; format += "#"; } } return format; } @Override public int getHeadMargin() { if (ticks == null || ticks.size() == 0 || maxWidth == 0 || maxHeight == 0) { // System.err.println("No ticks yet!"); final Dimension l = scale.calculateDimension(scale.getScaleRange().getLower()); if (scale.isHorizontal()) { // System.err.println("calculate X margin with " + r); return l.width; } // System.err.println("calculate Y margin with " + r); return l.height; } return scale.isHorizontal() ? (maxWidth + 1) / 2 : (maxHeight + 1) / 2; } @Override public int getTailMargin() { if (ticks == null || ticks.size() == 0 || maxWidth == 0 || maxHeight == 0) { // System.err.println("No ticks yet!"); final Dimension h = scale.calculateDimension(scale.getScaleRange().getUpper()); if (scale.isHorizontal()) { // System.err.println("calculate X margin with " + r); return h.width; } // System.err.println("calculate Y margin with " + r); return h.height; } return scale.isHorizontal() ? (maxWidth + 1) / 2 : (maxHeight + 1) / 2; } private static final String MINUS = "-"; /** * Update positions and max dimensions of tick labels * * @return true if there is no overlaps */ private boolean updateLabelPositionsAndCheckGaps(int length, final int hMargin, final int tMargin, final boolean isReversed) { final int imax = ticks.size(); if (imax == 0) { return true; } maxWidth = 0; maxHeight = 0; final boolean hasNegative = ticks.get(0).getText().startsWith(MINUS); final int minus = scale.calculateDimension(MINUS).width; for (Tick t : ticks) { final String l = t.getText(); final Dimension d = scale.calculateDimension(l); if (hasNegative && !l.startsWith(MINUS)) { d.width += minus; } if (d.width > maxWidth) { maxWidth = d.width; } if (d.height > maxHeight) { maxHeight = d.height; } } if (length <= 0) return true; // sanity check // System.err.println("Max labels have w:" + maxWidth + ", h:" + maxHeight); if (isReversed) { for (Tick t : ticks) { t.setPosition(length - length * t.getPosition() + hMargin); } } else { for (Tick t : ticks) { t.setPosition(length * t.getPosition() + hMargin); } } length += hMargin + tMargin; // re-expand length (so labels can flow into margins) if (scale.isHorizontal()) { final int space = (int) (0.67 * scale.calculateDimension(" ").width); int last = 0; for (Tick t : ticks) { final Dimension d = scale.calculateDimension(t.getText()); int w = d.width; int p = (int) Math.ceil(t.getPosition() - w * 0.5); if (p < 0) { p = 0; } else if (p + w >= length) { p = length - 1 - w; } t.setTextPosition(p); if (last > p) { if (ticks.indexOf(t) == (imax - 1) || imax > MIN_TICKS) { return false; } else { t.setText(""); } } else { last = p + w + space; } } } else { for (Tick t : ticks) { final Dimension d = scale.calculateDimension(t.getText()); int h = d.height; int p = (int) Math.ceil(length - 1 - t.getPosition() - h * 0.5); if (p < 0) { p = 0; } else if (p + h >= length) { p = length - 1 - h; } t.setTextPosition(p); } } return true; } private static final double LAST_STEP_FRAC = 1 - Math.log10(9); // fraction of major tick step between 9 and 10 private void updateMinorTicks(final int end) { minorPositions.clear(); final int jmax = ticks.size(); if (jmax <= 1) return; double majorStepInPixel = (ticks.get(jmax-1).getPosition() - ticks.get(0).getPosition()) / (jmax - 1); if (majorStepInPixel == 0) return; int minorTicks; if (scale.isLogScaleEnabled()) { if (majorStepInPixel * LAST_STEP_FRAC >= scale.getMinorTickMarkStepHint()) { - minorTicks = 10 * (int) Math.abs(Math.log10(ticks.get(1).getValue() / ticks.get(0).getValue())); + minorTicks = 10 * (int) Math.round(Math.abs(Math.log10(ticks.get(1).getValue() / ticks.get(0).getValue()))); + if (minorTicks > 10) + return; // gap is greater than a decade double p = ticks.get(0).getPosition(); if (p > 0) { p -= majorStepInPixel; for (int i = 1; i < minorTicks; i++) { int q = (int) (p + majorStepInPixel * Math.log10((10. * i) / minorTicks)); if (q >= 0 && q < end) minorPositions.add(q); } } for (int j = 0; j < jmax; j++) { p = ticks.get(j).getPosition(); for (int i = 1; i < minorTicks; i++) { int q = (int) (p + majorStepInPixel * Math.log10((10. * i) / minorTicks)); if (q >= 0 && q < end) minorPositions.add(q); } } } } else { double step = Math.abs(majorStepInPixel); if (ticksIndexBased) { minorTicks = (int) Math.abs(ticks.get(1).getValue() - ticks.get(0).getValue()); if (minorTicks == 1) return; if (minorTicks > step/5) { if (step / 5 >= scale.getMinorTickMarkStepHint()) { minorTicks = 5; } else if (step / 4 >= scale.getMinorTickMarkStepHint()) { minorTicks = 4; } else { minorTicks = 2; } } else if (minorTicks > 5) minorTicks = 5; } else { if (scale.isDateEnabled()) { minorTicks = 6; } else if (step / 5 >= scale.getMinorTickMarkStepHint()) { minorTicks = 5; } else if (step / 4 >= scale.getMinorTickMarkStepHint()) { minorTicks = 4; } else { minorTicks = 2; } } double minorStepInPixel = majorStepInPixel / minorTicks; double p = ticks.get(0).getPosition(); if (p > 0) { p -= majorStepInPixel; for (int i = 1; i < minorTicks; i++) { int q = (int) Math.floor(p + i * minorStepInPixel); if (q >= 0 && q < end) minorPositions.add(q); } } for (int j = 0; j < jmax; j++) { p = ticks.get(j).getPosition(); for (int i = 1; i < minorTicks; i++) { int q = (int) Math.floor(p + i * minorStepInPixel); if (q >= 0 && q < end) minorPositions.add(q); } } } } /** * @param isTicksIndexBased if true, make ticks based on axis dataset indexes */ public void setTicksIndexBased(boolean isTicksIndexBased) { ticksIndexBased = isTicksIndexBased; } }
true
true
private void updateMinorTicks(final int end) { minorPositions.clear(); final int jmax = ticks.size(); if (jmax <= 1) return; double majorStepInPixel = (ticks.get(jmax-1).getPosition() - ticks.get(0).getPosition()) / (jmax - 1); if (majorStepInPixel == 0) return; int minorTicks; if (scale.isLogScaleEnabled()) { if (majorStepInPixel * LAST_STEP_FRAC >= scale.getMinorTickMarkStepHint()) { minorTicks = 10 * (int) Math.abs(Math.log10(ticks.get(1).getValue() / ticks.get(0).getValue())); double p = ticks.get(0).getPosition(); if (p > 0) { p -= majorStepInPixel; for (int i = 1; i < minorTicks; i++) { int q = (int) (p + majorStepInPixel * Math.log10((10. * i) / minorTicks)); if (q >= 0 && q < end) minorPositions.add(q); } } for (int j = 0; j < jmax; j++) { p = ticks.get(j).getPosition(); for (int i = 1; i < minorTicks; i++) { int q = (int) (p + majorStepInPixel * Math.log10((10. * i) / minorTicks)); if (q >= 0 && q < end) minorPositions.add(q); } } } } else { double step = Math.abs(majorStepInPixel); if (ticksIndexBased) { minorTicks = (int) Math.abs(ticks.get(1).getValue() - ticks.get(0).getValue()); if (minorTicks == 1) return; if (minorTicks > step/5) { if (step / 5 >= scale.getMinorTickMarkStepHint()) { minorTicks = 5; } else if (step / 4 >= scale.getMinorTickMarkStepHint()) { minorTicks = 4; } else { minorTicks = 2; } } else if (minorTicks > 5) minorTicks = 5; } else { if (scale.isDateEnabled()) { minorTicks = 6; } else if (step / 5 >= scale.getMinorTickMarkStepHint()) { minorTicks = 5; } else if (step / 4 >= scale.getMinorTickMarkStepHint()) { minorTicks = 4; } else { minorTicks = 2; } } double minorStepInPixel = majorStepInPixel / minorTicks; double p = ticks.get(0).getPosition(); if (p > 0) { p -= majorStepInPixel; for (int i = 1; i < minorTicks; i++) { int q = (int) Math.floor(p + i * minorStepInPixel); if (q >= 0 && q < end) minorPositions.add(q); } } for (int j = 0; j < jmax; j++) { p = ticks.get(j).getPosition(); for (int i = 1; i < minorTicks; i++) { int q = (int) Math.floor(p + i * minorStepInPixel); if (q >= 0 && q < end) minorPositions.add(q); } } } }
private void updateMinorTicks(final int end) { minorPositions.clear(); final int jmax = ticks.size(); if (jmax <= 1) return; double majorStepInPixel = (ticks.get(jmax-1).getPosition() - ticks.get(0).getPosition()) / (jmax - 1); if (majorStepInPixel == 0) return; int minorTicks; if (scale.isLogScaleEnabled()) { if (majorStepInPixel * LAST_STEP_FRAC >= scale.getMinorTickMarkStepHint()) { minorTicks = 10 * (int) Math.round(Math.abs(Math.log10(ticks.get(1).getValue() / ticks.get(0).getValue()))); if (minorTicks > 10) return; // gap is greater than a decade double p = ticks.get(0).getPosition(); if (p > 0) { p -= majorStepInPixel; for (int i = 1; i < minorTicks; i++) { int q = (int) (p + majorStepInPixel * Math.log10((10. * i) / minorTicks)); if (q >= 0 && q < end) minorPositions.add(q); } } for (int j = 0; j < jmax; j++) { p = ticks.get(j).getPosition(); for (int i = 1; i < minorTicks; i++) { int q = (int) (p + majorStepInPixel * Math.log10((10. * i) / minorTicks)); if (q >= 0 && q < end) minorPositions.add(q); } } } } else { double step = Math.abs(majorStepInPixel); if (ticksIndexBased) { minorTicks = (int) Math.abs(ticks.get(1).getValue() - ticks.get(0).getValue()); if (minorTicks == 1) return; if (minorTicks > step/5) { if (step / 5 >= scale.getMinorTickMarkStepHint()) { minorTicks = 5; } else if (step / 4 >= scale.getMinorTickMarkStepHint()) { minorTicks = 4; } else { minorTicks = 2; } } else if (minorTicks > 5) minorTicks = 5; } else { if (scale.isDateEnabled()) { minorTicks = 6; } else if (step / 5 >= scale.getMinorTickMarkStepHint()) { minorTicks = 5; } else if (step / 4 >= scale.getMinorTickMarkStepHint()) { minorTicks = 4; } else { minorTicks = 2; } } double minorStepInPixel = majorStepInPixel / minorTicks; double p = ticks.get(0).getPosition(); if (p > 0) { p -= majorStepInPixel; for (int i = 1; i < minorTicks; i++) { int q = (int) Math.floor(p + i * minorStepInPixel); if (q >= 0 && q < end) minorPositions.add(q); } } for (int j = 0; j < jmax; j++) { p = ticks.get(j).getPosition(); for (int i = 1; i < minorTicks; i++) { int q = (int) Math.floor(p + i * minorStepInPixel); if (q >= 0 && q < end) minorPositions.add(q); } } } }
diff --git a/metaobj-impl/api-impl/src/java/org/sakaiproject/metaobj/utils/xml/impl/BaseElementType.java b/metaobj-impl/api-impl/src/java/org/sakaiproject/metaobj/utils/xml/impl/BaseElementType.java index 075b4d3..cea6e11 100755 --- a/metaobj-impl/api-impl/src/java/org/sakaiproject/metaobj/utils/xml/impl/BaseElementType.java +++ b/metaobj-impl/api-impl/src/java/org/sakaiproject/metaobj/utils/xml/impl/BaseElementType.java @@ -1,351 +1,360 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2004, 2005, 2006 The Sakai Foundation. * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.metaobj.utils.xml.impl; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; import org.jdom.Attribute; import org.jdom.Element; import org.jdom.Namespace; import org.sakaiproject.metaobj.utils.xml.ElementType; import org.sakaiproject.metaobj.utils.xml.NormalizationException; import org.sakaiproject.metaobj.utils.xml.SchemaNode; import org.sakaiproject.metaobj.utils.xml.ValidatedNode; import org.sakaiproject.metaobj.utils.xml.ValidationError; import org.sakaiproject.metaobj.utils.xml.ValueRange; /** * Created by IntelliJ IDEA. * User: John Ellis * Date: Apr 15, 2004 * Time: 5:07:44 PM * To change this template use File | Settings | File Templates. */ public class BaseElementType implements ElementType { protected static final int WHITE_SPACE_TYPE_NONE = 0; protected static final int WHITE_SPACE_TYPE_PRESERVE = 1; // replace with spaces protected static final int WHITE_SPACE_TYPE_REPLACE = 2; // remove all whitespace and replace with spaces protected static final int WHITE_SPACE_TYPE_COLLAPSE = 3; protected int length = -1; protected int maxLength = -1; protected int minLength = -1; protected Pattern pattern = null; protected int whiteSpaceType = WHITE_SPACE_TYPE_NONE; protected String defaultValue = ""; protected String fixedValue = ""; protected Element schemaElement; protected SchemaNode parentNode = null; private List enumeration = null; private String baseType; public BaseElementType(String typeName, Element schemaElement, SchemaNode parentNode, Namespace xsdNamespace) { setBaseType(typeName); this.schemaElement = schemaElement; this.parentNode = parentNode; init(xsdNamespace); } protected void init(Namespace xsdNamespace) { Element simpleType = schemaElement.getChild("simpleType", xsdNamespace); if (simpleType != null) { Element restrictions = simpleType.getChild("restriction", xsdNamespace); if (restrictions != null) { // process restrictions length = processIntRestriction(restrictions, "length", xsdNamespace, length); maxLength = processIntRestriction(restrictions, "maxLength", xsdNamespace, maxLength); minLength = processIntRestriction(restrictions, "minLength", xsdNamespace, minLength); String patternValue = processStringRestriction(restrictions, "pattern", xsdNamespace); if (patternValue != null) { pattern = Pattern.compile(patternValue); } String whiteSpaceValue = processStringRestriction(restrictions, "whiteSpace", xsdNamespace); if (whiteSpaceValue != null) { if (whiteSpaceValue.equals("preserve")) { whiteSpaceType = WHITE_SPACE_TYPE_PRESERVE; } if (whiteSpaceValue.equals("replace")) { whiteSpaceType = WHITE_SPACE_TYPE_REPLACE; } if (whiteSpaceValue.equals("collapse")) { whiteSpaceType = WHITE_SPACE_TYPE_COLLAPSE; } } } } if (schemaElement.getAttribute("default") != null) { defaultValue = schemaElement.getAttributeValue("default"); } if (schemaElement.getAttribute("fixed") != null) { fixedValue = schemaElement.getAttributeValue("fixed"); defaultValue = fixedValue; } } protected void processEnumerations(Element restrictions, Namespace xsdNamespace) { List enums = restrictions.getChildren("enumeration", xsdNamespace); List temp = null; enumeration = null; if (enums.size() > 0) { temp = new ArrayList(); } for (Iterator i = enums.iterator(); i.hasNext();) { Element enumer = (Element) i.next(); String value = enumer.getAttributeValue("value"); temp.add(getActualNormalizedValue(value)); } enumeration = temp; } protected String processStringRestriction(Element restrictions, String s, Namespace xsdNamespace) { Element currentRestriction = restrictions.getChild(s, xsdNamespace); if (currentRestriction == null) { return null; } return currentRestriction.getAttributeValue("value"); } protected int processIntRestriction(Element restrictions, String s, Namespace xsdNamespace, int defaultValue) { String value = processStringRestriction(restrictions, s, xsdNamespace); if (value == null) { return defaultValue; } return Integer.parseInt(value); } /** * Validates the passed in node and all children. * Will also normalize any values. * * @param node a jdom element to validate * @return the validated Element wrapped * in a ValidatedNode class */ public ValidatedNode validateAndNormalize(Element node) { ValidatedNodeImpl validatedNode = new ValidatedNodeImpl(parentNode, node); String value = node.getText(); try { value = getSchemaNormalizedValue(value); node.setText(value); validatedNode.setNormalizedValue(getActualNormalizedValue(value)); if (value == null || value.length() == 0) { return null; } } catch (NormalizationException exp) { validatedNode.getErrors().add(new ValidationError(validatedNode, exp.getErrorCode(), exp.getErrorInfo())); } return validatedNode; } public String getSchemaNormalizedValue(Object value) throws NormalizationException { if (value == null) { return null; } return getSchemaNormalizedValue(value.toString()); } public String getSchemaNormalizedValue(String value) throws NormalizationException { if (value == null) { return defaultValue; } if (fixedValue != null && fixedValue.length() > 0) { return fixedValue; } String startingValue = handleWhiteSpace(value.toString()); int valueLength = startingValue.length(); if (length != -1 && valueLength != length) { throw new NormalizationException("Invalid string length", NormalizationException.INVALID_LENGTH_ERROR_CODE, new Object[]{startingValue, new Integer(length)}); } if (maxLength != -1 && valueLength > maxLength) { + /* + * SAK-12670 - error description is too long bc + * the field value is too long. This clips off the + * value of the field to only 100 chars + */ + String val = startingValue; + if(startingValue.length() > 100){ + val = val.substring(0, 100) + "..."; + } throw new NormalizationException("Invalid string length", NormalizationException.INVALID_LENGTH_TOO_LONG_ERROR_CODE, - new Object[]{startingValue, new Integer(maxLength)}); + new Object[]{val, new Integer(maxLength)}); } if (minLength != -1 && valueLength < minLength && minLength == 1) { throw new NormalizationException("Required field", NormalizationException.REQIRED_FIELD_ERROR_CODE, new Object[0]); } if (minLength != -1 && valueLength < minLength) { throw new NormalizationException("Invalid string length", NormalizationException.INVALID_LENGTH_TOO_SHORT_ERROR_CODE, new Object[]{startingValue, new Integer(minLength)}); } if (pattern != null && !pattern.matcher(startingValue).matches()) { throw new NormalizationException("Invalid string pattern", NormalizationException.INVALID_PATTERN_MATCH_ERROR_CODE, new Object[]{startingValue, pattern.pattern()}); } return startingValue; } private String handleWhiteSpace(String s) { if (whiteSpaceType == WHITE_SPACE_TYPE_NONE || whiteSpaceType == WHITE_SPACE_TYPE_PRESERVE) { return s; } if (whiteSpaceType == WHITE_SPACE_TYPE_REPLACE) { s = s.replaceAll("\\s", " "); } else if (whiteSpaceType == WHITE_SPACE_TYPE_COLLAPSE) { s = s.replaceAll("\\s+", " "); } return s; } public Class getObjectType() { return String.class; } public Object getActualNormalizedValue(String value) { Object returned = getSchemaNormalizedValue(value); if (enumeration != null) { if (!enumeration.contains(returned)) { throw new NormalizationException("Not enumerated", NormalizationException.NOT_IN_ENUMERATION_ERROR_CODE, new Object[]{returned}); } } return returned; } public int getLength() { return length; } public int getMaxLength() { return maxLength; } public int getMinLength() { return minLength; } public Pattern getPattern() { return pattern; } public ValueRange getRange() { return null; } public int getWhiteSpaceType() { return whiteSpaceType; } public String getDefaultValue() { return defaultValue; } public String getFixedValue() { return fixedValue; } public List getEnumeration() { return enumeration; } public BaseElementType postInit(Namespace xsdNamespace) { Element simpleType = schemaElement.getChild("simpleType", xsdNamespace); if (simpleType != null) { Element restrictions = simpleType.getChild("restriction", xsdNamespace); if (restrictions != null) { processEnumerations(restrictions, xsdNamespace); } } return this; } public ValidatedNode validateAndNormalize(Attribute node) { ValidatedNodeImpl validatedNode = new ValidatedNodeImpl(parentNode, null); String value = node.getValue(); try { value = getSchemaNormalizedValue(value); node.setValue(value); validatedNode.setNormalizedValue(getActualNormalizedValue(value)); if (value == null || value.length() == 0) { return null; } } catch (NormalizationException exp) { validatedNode.getErrors().add(new ValidationError(validatedNode, exp.getErrorCode(), exp.getErrorInfo())); } return validatedNode; } public String getBaseType() { return baseType; } public void setBaseType(String baseType) { this.baseType = baseType; } }
false
true
public String getSchemaNormalizedValue(String value) throws NormalizationException { if (value == null) { return defaultValue; } if (fixedValue != null && fixedValue.length() > 0) { return fixedValue; } String startingValue = handleWhiteSpace(value.toString()); int valueLength = startingValue.length(); if (length != -1 && valueLength != length) { throw new NormalizationException("Invalid string length", NormalizationException.INVALID_LENGTH_ERROR_CODE, new Object[]{startingValue, new Integer(length)}); } if (maxLength != -1 && valueLength > maxLength) { throw new NormalizationException("Invalid string length", NormalizationException.INVALID_LENGTH_TOO_LONG_ERROR_CODE, new Object[]{startingValue, new Integer(maxLength)}); } if (minLength != -1 && valueLength < minLength && minLength == 1) { throw new NormalizationException("Required field", NormalizationException.REQIRED_FIELD_ERROR_CODE, new Object[0]); } if (minLength != -1 && valueLength < minLength) { throw new NormalizationException("Invalid string length", NormalizationException.INVALID_LENGTH_TOO_SHORT_ERROR_CODE, new Object[]{startingValue, new Integer(minLength)}); } if (pattern != null && !pattern.matcher(startingValue).matches()) { throw new NormalizationException("Invalid string pattern", NormalizationException.INVALID_PATTERN_MATCH_ERROR_CODE, new Object[]{startingValue, pattern.pattern()}); } return startingValue; }
public String getSchemaNormalizedValue(String value) throws NormalizationException { if (value == null) { return defaultValue; } if (fixedValue != null && fixedValue.length() > 0) { return fixedValue; } String startingValue = handleWhiteSpace(value.toString()); int valueLength = startingValue.length(); if (length != -1 && valueLength != length) { throw new NormalizationException("Invalid string length", NormalizationException.INVALID_LENGTH_ERROR_CODE, new Object[]{startingValue, new Integer(length)}); } if (maxLength != -1 && valueLength > maxLength) { /* * SAK-12670 - error description is too long bc * the field value is too long. This clips off the * value of the field to only 100 chars */ String val = startingValue; if(startingValue.length() > 100){ val = val.substring(0, 100) + "..."; } throw new NormalizationException("Invalid string length", NormalizationException.INVALID_LENGTH_TOO_LONG_ERROR_CODE, new Object[]{val, new Integer(maxLength)}); } if (minLength != -1 && valueLength < minLength && minLength == 1) { throw new NormalizationException("Required field", NormalizationException.REQIRED_FIELD_ERROR_CODE, new Object[0]); } if (minLength != -1 && valueLength < minLength) { throw new NormalizationException("Invalid string length", NormalizationException.INVALID_LENGTH_TOO_SHORT_ERROR_CODE, new Object[]{startingValue, new Integer(minLength)}); } if (pattern != null && !pattern.matcher(startingValue).matches()) { throw new NormalizationException("Invalid string pattern", NormalizationException.INVALID_PATTERN_MATCH_ERROR_CODE, new Object[]{startingValue, pattern.pattern()}); } return startingValue; }
diff --git a/plugins/org.jboss.tools.jst.text.ext/src/org/jboss/tools/jst/text/ext/hyperlink/ELHyperlink.java b/plugins/org.jboss.tools.jst.text.ext/src/org/jboss/tools/jst/text/ext/hyperlink/ELHyperlink.java index 047b9524..fff4ac0e 100644 --- a/plugins/org.jboss.tools.jst.text.ext/src/org/jboss/tools/jst/text/ext/hyperlink/ELHyperlink.java +++ b/plugins/org.jboss.tools.jst.text.ext/src/org/jboss/tools/jst/text/ext/hyperlink/ELHyperlink.java @@ -1,271 +1,262 @@ /******************************************************************************* * Copyright (c) 2011 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.jst.text.ext.hyperlink; import java.text.MessageFormat; import java.util.List; import java.util.Properties; import org.eclipse.core.resources.IFile; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.PartInitException; import org.jboss.tools.common.el.core.ELReference; import org.jboss.tools.common.el.core.resolver.ELSegment; import org.jboss.tools.common.el.core.resolver.IOpenableReference; import org.jboss.tools.common.el.core.resolver.JavaMemberELSegment; import org.jboss.tools.common.el.core.resolver.MessagePropertyELSegment; import org.jboss.tools.common.model.XModel; import org.jboss.tools.common.model.XModelObject; import org.jboss.tools.common.model.project.IPromptingProvider; import org.jboss.tools.common.model.project.PromptingProviderFactory; import org.jboss.tools.common.model.util.PositionHolder; import org.jboss.tools.common.text.ext.hyperlink.AbstractHyperlink; import org.jboss.tools.common.text.ext.hyperlink.xpl.Messages; import org.jboss.tools.common.text.ext.util.StructuredModelWrapper; import org.jboss.tools.common.text.ext.util.StructuredSelectionHelper; import org.jboss.tools.common.text.ext.util.Utils; import org.jboss.tools.jst.text.ext.JSTExtensionsPlugin; import org.jboss.tools.jst.web.project.list.WebPromptingProvider; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; public class ELHyperlink extends AbstractHyperlink{ private static final String VIEW_TAGNAME = "view"; //$NON-NLS-1$ private static final String LOCALE_ATTRNAME = "locale"; //$NON-NLS-1$ private static final String PREFIX_SEPARATOR = ":"; //$NON-NLS-1$ private ELReference reference; private ELSegment segment; private XModelObject xObject; public ELHyperlink(IDocument document, ELReference reference, ELSegment segment, XModelObject xObject){ this.reference = reference; this.segment = segment; this.xObject = xObject; setDocument(document); } @Override protected IRegion doGetHyperlinkRegion(int offset) { return new IRegion(){ public int getLength() { return segment.getSourceReference().getLength(); } public int getOffset() { return reference.getStartPosition()+segment.getSourceReference().getStartPosition(); }}; } @Override protected void doHyperlink(IRegion region) { IOpenableReference[] openables = segment.getOpenable(); if(openables.length > 0) { if(!openables[0].open()) { openFileFailed(); } //If openables.length > 1 - show menu. return; } if(segment instanceof JavaMemberELSegment){ - try { - if(JavaUI.openInEditor(((JavaMemberELSegment) segment).getJavaElement()) == null){ - openFileFailed(); - } - } catch (PartInitException e) { - JSTExtensionsPlugin.getDefault().logError(e); - } catch (JavaModelException e) { - JSTExtensionsPlugin.getDefault().logError(e); - } - return; + //should not be here, Java case implements getOpenable(). }else if(segment instanceof MessagePropertyELSegment){ IFile file = ((MessagePropertyELSegment)segment).getMessageBundleResource(); if(file == null) file = (IFile)segment.getResource(); XModel xModel = getXModel(file); if (xModel == null) { openFileFailed(); return; } String bundleBasename = ((MessagePropertyELSegment)segment).getBaseName(); String property = ((MessagePropertyELSegment)segment).isBundle() ? null : trimQuotes(((MessagePropertyELSegment)segment).getToken().getText()); String locale = getPageLocale(region); Properties p = new Properties(); if (bundleBasename != null) { p.put(WebPromptingProvider.BUNDLE, bundleBasename); } if (property != null) { p.put(WebPromptingProvider.KEY, property); } if (locale != null) { p.setProperty(WebPromptingProvider.LOCALE, locale); } IPromptingProvider provider = PromptingProviderFactory.WEB; p.put(IPromptingProvider.FILE, file); List list = provider.getList(xModel, getRequestMethod(p), p.getProperty("prefix"), p); //$NON-NLS-1$ if (list != null && list.size() >= 1) { openFileInEditor((String)list.get(0)); return; } String error = p.getProperty(IPromptingProvider.ERROR); if ( error != null && error.length() > 0) { openFileFailed(); } return; }else if(xObject != null){ IRegion attrRegion = null; PositionHolder h = PositionHolder.getPosition(xObject, null); h.update(); if (h.getStart() == -1 || h.getEnd() == -1) { openFileFailed(); return; } attrRegion = new Region(h.getStart(), h.getEnd() - h.getStart()); IFile file = (IFile)xObject.getAdapter(IFile.class); if (file != null) { if (openFileInEditor(file) != null) { StructuredSelectionHelper.setSelectionAndRevealInActiveEditor(attrRegion); return; } } } openFileFailed(); } private String getPageLocale(IRegion region) { if(getDocument() == null || region == null) return null; StructuredModelWrapper smw = new StructuredModelWrapper(); try { smw.init(getDocument()); Document xmlDocument = smw.getDocument(); if (xmlDocument == null) return null; Node n = Utils.findNodeForOffset(xmlDocument, region.getOffset()); if (!(n instanceof Attr) ) return null; Element el = ((Attr)n).getOwnerElement(); Element jsfCoreViewTag = null; String nodeToFind = PREFIX_SEPARATOR + VIEW_TAGNAME; while (el != null) { if (el.getNodeName() != null && el.getNodeName().endsWith(nodeToFind)) { jsfCoreViewTag = el; break; } Node parent = el.getParentNode(); el = (parent instanceof Element ? (Element)parent : null); } if (jsfCoreViewTag == null || !jsfCoreViewTag.hasAttribute(LOCALE_ATTRNAME)) return null; String locale = Utils.trimQuotes((jsfCoreViewTag.getAttributeNode(LOCALE_ATTRNAME)).getValue()); if (locale == null || locale.length() == 0) return null; return locale; } finally { smw.dispose(); } } private String trimQuotes(String value) { if(value == null) return null; if(value.startsWith("'") || value.startsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$ value = value.substring(1); } if(value.endsWith("'") || value.endsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$ value = value.substring(0, value.length() - 1); } return value; } private String getRequestMethod(Properties prop) { return prop != null && prop.getProperty(WebPromptingProvider.KEY) == null ? WebPromptingProvider.JSF_OPEN_BUNDLE : WebPromptingProvider.JSF_OPEN_KEY; } @Override public String getHyperlinkText() { if(segment instanceof JavaMemberELSegment){ IJavaElement javaElement = ((JavaMemberELSegment) segment).getJavaElement(); String name = ""; //$NON-NLS-1$ IType type = null; if(javaElement instanceof IType){ name = javaElement.getElementName(); type = (IType)javaElement; }else if(javaElement instanceof IMethod){ type = ((IMethod) javaElement).getDeclaringType(); name = type.getElementName()+"."+javaElement.getElementName()+"()"; //$NON-NLS-1$ //$NON-NLS-2$ }else if(javaElement instanceof IField){ type = ((IField) javaElement).getDeclaringType(); name = type.getElementName()+"."+javaElement.getElementName(); //$NON-NLS-1$ } if(type != null) name += " - "+type.getPackageFragment().getElementName(); //$NON-NLS-1$ return MessageFormat.format(Messages.Open, name); }else if(segment instanceof MessagePropertyELSegment){ String baseName = ((MessagePropertyELSegment)segment).getBaseName(); String propertyName = ((MessagePropertyELSegment)segment).isBundle() ? null : trimQuotes(((MessagePropertyELSegment)segment).getToken().getText()); if (propertyName == null) return MessageFormat.format(Messages.Open, baseName); return MessageFormat.format(Messages.OpenBundleProperty, propertyName, baseName); }else if(xObject != null){ return Messages.OpenJsf2CCAttribute; } return ""; //$NON-NLS-1$ } @Override public IFile getReadyToOpenFile() { IFile file = null; if(segment instanceof JavaMemberELSegment){ try { file = (IFile)((JavaMemberELSegment) segment).getJavaElement().getUnderlyingResource(); } catch (JavaModelException e) { JSTExtensionsPlugin.getDefault().logError(e); } }else if(segment instanceof MessagePropertyELSegment){ file = (IFile)((MessagePropertyELSegment)segment).getMessageBundleResource(); } return file; } }
true
true
protected void doHyperlink(IRegion region) { IOpenableReference[] openables = segment.getOpenable(); if(openables.length > 0) { if(!openables[0].open()) { openFileFailed(); } //If openables.length > 1 - show menu. return; } if(segment instanceof JavaMemberELSegment){ try { if(JavaUI.openInEditor(((JavaMemberELSegment) segment).getJavaElement()) == null){ openFileFailed(); } } catch (PartInitException e) { JSTExtensionsPlugin.getDefault().logError(e); } catch (JavaModelException e) { JSTExtensionsPlugin.getDefault().logError(e); } return; }else if(segment instanceof MessagePropertyELSegment){ IFile file = ((MessagePropertyELSegment)segment).getMessageBundleResource(); if(file == null) file = (IFile)segment.getResource(); XModel xModel = getXModel(file); if (xModel == null) { openFileFailed(); return; } String bundleBasename = ((MessagePropertyELSegment)segment).getBaseName(); String property = ((MessagePropertyELSegment)segment).isBundle() ? null : trimQuotes(((MessagePropertyELSegment)segment).getToken().getText()); String locale = getPageLocale(region); Properties p = new Properties(); if (bundleBasename != null) { p.put(WebPromptingProvider.BUNDLE, bundleBasename); } if (property != null) { p.put(WebPromptingProvider.KEY, property); } if (locale != null) { p.setProperty(WebPromptingProvider.LOCALE, locale); } IPromptingProvider provider = PromptingProviderFactory.WEB; p.put(IPromptingProvider.FILE, file); List list = provider.getList(xModel, getRequestMethod(p), p.getProperty("prefix"), p); //$NON-NLS-1$ if (list != null && list.size() >= 1) { openFileInEditor((String)list.get(0)); return; } String error = p.getProperty(IPromptingProvider.ERROR); if ( error != null && error.length() > 0) { openFileFailed(); } return; }else if(xObject != null){ IRegion attrRegion = null; PositionHolder h = PositionHolder.getPosition(xObject, null); h.update(); if (h.getStart() == -1 || h.getEnd() == -1) { openFileFailed(); return; } attrRegion = new Region(h.getStart(), h.getEnd() - h.getStart()); IFile file = (IFile)xObject.getAdapter(IFile.class); if (file != null) { if (openFileInEditor(file) != null) { StructuredSelectionHelper.setSelectionAndRevealInActiveEditor(attrRegion); return; } } } openFileFailed(); }
protected void doHyperlink(IRegion region) { IOpenableReference[] openables = segment.getOpenable(); if(openables.length > 0) { if(!openables[0].open()) { openFileFailed(); } //If openables.length > 1 - show menu. return; } if(segment instanceof JavaMemberELSegment){ //should not be here, Java case implements getOpenable(). }else if(segment instanceof MessagePropertyELSegment){ IFile file = ((MessagePropertyELSegment)segment).getMessageBundleResource(); if(file == null) file = (IFile)segment.getResource(); XModel xModel = getXModel(file); if (xModel == null) { openFileFailed(); return; } String bundleBasename = ((MessagePropertyELSegment)segment).getBaseName(); String property = ((MessagePropertyELSegment)segment).isBundle() ? null : trimQuotes(((MessagePropertyELSegment)segment).getToken().getText()); String locale = getPageLocale(region); Properties p = new Properties(); if (bundleBasename != null) { p.put(WebPromptingProvider.BUNDLE, bundleBasename); } if (property != null) { p.put(WebPromptingProvider.KEY, property); } if (locale != null) { p.setProperty(WebPromptingProvider.LOCALE, locale); } IPromptingProvider provider = PromptingProviderFactory.WEB; p.put(IPromptingProvider.FILE, file); List list = provider.getList(xModel, getRequestMethod(p), p.getProperty("prefix"), p); //$NON-NLS-1$ if (list != null && list.size() >= 1) { openFileInEditor((String)list.get(0)); return; } String error = p.getProperty(IPromptingProvider.ERROR); if ( error != null && error.length() > 0) { openFileFailed(); } return; }else if(xObject != null){ IRegion attrRegion = null; PositionHolder h = PositionHolder.getPosition(xObject, null); h.update(); if (h.getStart() == -1 || h.getEnd() == -1) { openFileFailed(); return; } attrRegion = new Region(h.getStart(), h.getEnd() - h.getStart()); IFile file = (IFile)xObject.getAdapter(IFile.class); if (file != null) { if (openFileInEditor(file) != null) { StructuredSelectionHelper.setSelectionAndRevealInActiveEditor(attrRegion); return; } } } openFileFailed(); }
diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/SimpleTileAtlas.java b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/SimpleTileAtlas.java index e43df8658..cbf31e1d5 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/SimpleTileAtlas.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/SimpleTileAtlas.java @@ -1,77 +1,78 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.graphics.g2d.tiled; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.MathUtils; /** Contains an atlas of tiles by tile id for use with {@link TileMapRenderer} It does not need to be loaded with packed files. * Just plain textures. * @author Tomas Lazaro */ public class SimpleTileAtlas extends TileAtlas { /** Creates a TileAtlas for use with {@link TileMapRenderer}. * @param map The tiled map * @param inputDir The directory containing all needed textures in the map */ public SimpleTileAtlas (TiledMap map, FileHandle inputDir) { for (TileSet set : map.tileSets) { Pixmap pixmap = new Pixmap(inputDir.child(set.imageName)); int originalWidth = pixmap.getWidth(); int originalHeight = pixmap.getHeight(); if (!MathUtils.isPowerOfTwo(originalWidth) || !MathUtils.isPowerOfTwo(originalHeight)) { final int width = MathUtils.nextPowerOfTwo(originalWidth); final int height = MathUtils.nextPowerOfTwo(originalHeight); Pixmap potPixmap = new Pixmap(width, height, pixmap.getFormat()); potPixmap.drawPixmap(pixmap, 0, 0, 0, 0, width, height); pixmap.dispose(); pixmap = potPixmap; } Texture texture = new Texture(pixmap); pixmap.dispose(); + textures.add(texture); int idx = 0; TextureRegion[][] regions = split(texture, originalWidth, originalHeight, map.tileWidth, map.tileHeight, set.spacing, set.margin); for (int y = 0; y < regions[0].length; y++) { for (int x = 0; x < regions.length; x++) { regionsMap.put(idx++ + set.firstgid, regions[x][y]); } } } } private static TextureRegion[][] split (Texture texture, int totalWidth, int totalHeight, int width, int height, int spacing, int margin) { // TODO add padding support int xSlices = (totalWidth - margin) / (width + spacing); int ySlices = (totalHeight - margin) / (height + spacing); TextureRegion[][] res = new TextureRegion[xSlices][ySlices]; for (int x = 0; x < xSlices; x++) { for (int y = 0; y < ySlices; y++) { res[x][y] = new TextureRegion(texture, margin + x * (width + spacing), margin + y * (height + spacing), width, height); } } return res; } }
true
true
public SimpleTileAtlas (TiledMap map, FileHandle inputDir) { for (TileSet set : map.tileSets) { Pixmap pixmap = new Pixmap(inputDir.child(set.imageName)); int originalWidth = pixmap.getWidth(); int originalHeight = pixmap.getHeight(); if (!MathUtils.isPowerOfTwo(originalWidth) || !MathUtils.isPowerOfTwo(originalHeight)) { final int width = MathUtils.nextPowerOfTwo(originalWidth); final int height = MathUtils.nextPowerOfTwo(originalHeight); Pixmap potPixmap = new Pixmap(width, height, pixmap.getFormat()); potPixmap.drawPixmap(pixmap, 0, 0, 0, 0, width, height); pixmap.dispose(); pixmap = potPixmap; } Texture texture = new Texture(pixmap); pixmap.dispose(); int idx = 0; TextureRegion[][] regions = split(texture, originalWidth, originalHeight, map.tileWidth, map.tileHeight, set.spacing, set.margin); for (int y = 0; y < regions[0].length; y++) { for (int x = 0; x < regions.length; x++) { regionsMap.put(idx++ + set.firstgid, regions[x][y]); } } } }
public SimpleTileAtlas (TiledMap map, FileHandle inputDir) { for (TileSet set : map.tileSets) { Pixmap pixmap = new Pixmap(inputDir.child(set.imageName)); int originalWidth = pixmap.getWidth(); int originalHeight = pixmap.getHeight(); if (!MathUtils.isPowerOfTwo(originalWidth) || !MathUtils.isPowerOfTwo(originalHeight)) { final int width = MathUtils.nextPowerOfTwo(originalWidth); final int height = MathUtils.nextPowerOfTwo(originalHeight); Pixmap potPixmap = new Pixmap(width, height, pixmap.getFormat()); potPixmap.drawPixmap(pixmap, 0, 0, 0, 0, width, height); pixmap.dispose(); pixmap = potPixmap; } Texture texture = new Texture(pixmap); pixmap.dispose(); textures.add(texture); int idx = 0; TextureRegion[][] regions = split(texture, originalWidth, originalHeight, map.tileWidth, map.tileHeight, set.spacing, set.margin); for (int y = 0; y < regions[0].length; y++) { for (int x = 0; x < regions.length; x++) { regionsMap.put(idx++ + set.firstgid, regions[x][y]); } } } }
diff --git a/dropwizard-db/src/main/java/com/yammer/dropwizard/db/Database.java b/dropwizard-db/src/main/java/com/yammer/dropwizard/db/Database.java index b6ad68645..b9f4a3bfb 100644 --- a/dropwizard-db/src/main/java/com/yammer/dropwizard/db/Database.java +++ b/dropwizard-db/src/main/java/com/yammer/dropwizard/db/Database.java @@ -1,56 +1,56 @@ package com.yammer.dropwizard.db; import com.yammer.dropwizard.db.args.OptionalArgumentFactory; import com.yammer.dropwizard.lifecycle.Managed; import com.yammer.metrics.Metrics; import com.yammer.metrics.jdbi.InstrumentedTimingCollector; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.tomcat.dbcp.pool.ObjectPool; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.logging.Log4JLog; import org.skife.jdbi.v2.sqlobject.SqlQuery; import javax.sql.DataSource; import java.sql.SQLException; public class Database extends DBI implements Managed { public interface Ping { @SqlQuery("SELECT 1") public Integer ping(); } private static final Logger LOGGER = Logger.getLogger(Database.class); private final ObjectPool pool; private final Ping ping; public Database(DataSource dataSource, ObjectPool pool) { super(dataSource); this.pool = pool; this.ping = onDemand(Ping.class); setSQLLog(new Log4JLog(LOGGER, Level.TRACE)); - setTimingCollector(new InstrumentedTimingCollector(Metrics.defaultRegistry(), Database.class)); + setTimingCollector(new InstrumentedTimingCollector(Metrics.defaultRegistry())); setStatementRewriter(new NamePrependingStatementRewriter()); setStatementLocator(new ScopedStatementLocator()); registerArgumentFactory(new OptionalArgumentFactory()); registerContainerFactory(new ImmutableListContainerFactory()); } @Override public void start() throws Exception { // already started, man } @Override public void stop() throws Exception { pool.close(); } public void ping() throws SQLException { final Integer value = ping.ping(); if (!Integer.valueOf(1).equals(value)) { throw new SQLException("Expected 1 from 'SELECT 1', got " + value); } } }
true
true
public Database(DataSource dataSource, ObjectPool pool) { super(dataSource); this.pool = pool; this.ping = onDemand(Ping.class); setSQLLog(new Log4JLog(LOGGER, Level.TRACE)); setTimingCollector(new InstrumentedTimingCollector(Metrics.defaultRegistry(), Database.class)); setStatementRewriter(new NamePrependingStatementRewriter()); setStatementLocator(new ScopedStatementLocator()); registerArgumentFactory(new OptionalArgumentFactory()); registerContainerFactory(new ImmutableListContainerFactory()); }
public Database(DataSource dataSource, ObjectPool pool) { super(dataSource); this.pool = pool; this.ping = onDemand(Ping.class); setSQLLog(new Log4JLog(LOGGER, Level.TRACE)); setTimingCollector(new InstrumentedTimingCollector(Metrics.defaultRegistry())); setStatementRewriter(new NamePrependingStatementRewriter()); setStatementLocator(new ScopedStatementLocator()); registerArgumentFactory(new OptionalArgumentFactory()); registerContainerFactory(new ImmutableListContainerFactory()); }
diff --git a/src/net/sf/drftpd/master/command/plugins/Dir.java b/src/net/sf/drftpd/master/command/plugins/Dir.java index bf716a71..be6bf221 100644 --- a/src/net/sf/drftpd/master/command/plugins/Dir.java +++ b/src/net/sf/drftpd/master/command/plugins/Dir.java @@ -1,1044 +1,1046 @@ /* * This file is part of DrFTPD, Distributed FTP Daemon. * * DrFTPD is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * DrFTPD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DrFTPD; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package net.sf.drftpd.master.command.plugins; import java.io.FileNotFoundException; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.StringTokenizer; import net.sf.drftpd.FileExistsException; import net.sf.drftpd.NoAvailableSlaveException; import net.sf.drftpd.event.DirectoryFtpEvent; import net.sf.drftpd.master.BaseFtpConnection; import net.sf.drftpd.master.FtpRequest; import net.sf.drftpd.master.command.CommandManager; import net.sf.drftpd.master.command.CommandManagerFactory; import org.apache.log4j.Logger; import org.drftpd.Checksum; import org.drftpd.commands.CommandHandler; import org.drftpd.commands.CommandHandlerFactory; import org.drftpd.commands.Reply; import org.drftpd.commands.UnhandledCommandException; import org.drftpd.usermanager.NoSuchUserException; import org.drftpd.usermanager.User; import org.drftpd.usermanager.UserFileException; import org.drftpd.vfs.DirectoryHandle; import org.drftpd.vfs.FileHandle; import org.drftpd.vfs.InodeHandle; import org.drftpd.vfs.LinkHandle; import org.drftpd.vfs.ListUtils; import org.drftpd.vfs.ObjectNotValidException; import org.drftpd.vfs.VirtualFileSystem; /** * @author mog * @version $Id$ */ public class Dir implements CommandHandler, CommandHandlerFactory, Cloneable { private final static SimpleDateFormat DATE_FMT = new SimpleDateFormat( "yyyyMMddHHmmss.SSS"); private static final Logger logger = Logger.getLogger(Dir.class); protected InodeHandle _renameFrom = null; public Dir() { super(); } /** * <code>CDUP &lt;CRLF&gt;</code><br> * * This command is a special case of CWD, and is included to * simplify the implementation of programs for transferring * directory trees between operating systems having different * syntaxes for naming the parent directory. The reply codes * shall be identical to the reply codes of CWD. */ private Reply doCDUP(BaseFtpConnection conn) { // change directory conn.setCurrentDirectory(conn.getCurrentDirectory().getParent()); return new Reply(200, "Directory changed to " + conn.getCurrentDirectory().getPath()); } /** * <code>CWD &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * This command allows the user to work with a different * directory for file storage or retrieval without * altering his login or accounting information. Transfer * parameters are similarly unchanged. The argument is a * pathname specifying a directory. */ private Reply doCWD(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } DirectoryHandle newCurrentDirectory = null; try { newCurrentDirectory = conn.getCurrentDirectory().getDirectory(request.getArgument()); } catch (FileNotFoundException ex) { return new Reply(550, ex.getMessage()); } catch (ObjectNotValidException e) { return new Reply(550, request.getArgument() + ": is not a directory"); } if (!conn.getGlobalContext().getConfig().checkPathPermission("privpath", conn.getUserNull(), newCurrentDirectory, true)) { return new Reply(550, request.getArgument() + ": Not found"); // reply identical to FileNotFoundException.getMessage() above } conn.setCurrentDirectory(newCurrentDirectory); Reply response = new Reply(250, "Directory changed to " + newCurrentDirectory.getPath()); conn.getGlobalContext().getConfig().directoryMessage(response, conn.getUserNull(), newCurrentDirectory); // diz,mp3,racestats will all be hooked externally in the new commandhandlers // show cwd_mp3.txt if this is an mp3 release /* ResourceBundle bundle = ResourceBundle.getBundle(Dir.class.getName()); if (conn.getGlobalContext().getZsConfig().id3Enabled()) { try { ID3Tag id3tag = newCurrentDirectory.lookupFile(newCurrentDirectory.lookupMP3File()) .getID3v1Tag(); String mp3text = bundle.getString("cwd.id3info.text"); ReplacerEnvironment env = BaseFtpConnection.getReplacerEnvironment(null, conn.getUserNull()); ReplacerFormat id3format = null; try { id3format = ReplacerFormat.createFormat(mp3text); } catch (FormatterException e1) { logger.warn(e1); } env.add("artist", id3tag.getArtist().trim()); env.add("album", id3tag.getAlbum().trim()); env.add("genre", id3tag.getGenre()); env.add("year", id3tag.getYear()); try { if (id3format == null) { response.addComment("broken 1"); } else { response.addComment(SimplePrintf.jprintf(id3format, env)); } } catch (FormatterException e) { response.addComment("broken 2"); logger.warn("", e); } } catch (FileNotFoundException e) { // no mp3 found //logger.warn("",e); } catch (IOException e) { logger.warn("", e); } catch (NoAvailableSlaveException e) { logger.warn("", e); } } // diz files if (conn.getGlobalContext().getZsConfig().dizEnabled()) { if (DIZPlugin.zipFilesOnline(newCurrentDirectory) > 0) { try { DIZFile diz = new DIZFile(DIZPlugin .getZipFile(newCurrentDirectory)); ReplacerFormat format = null; ReplacerEnvironment env = BaseFtpConnection .getReplacerEnvironment(null, conn.getUserNull()); if (diz.getDiz() != null) { try { format = ReplacerFormat.createFormat(diz.getDiz()); response.addComment(SimplePrintf.jprintf(format, env)); } catch (FormatterException e) { logger.warn(e); } } } catch (FileNotFoundException e) { // do nothing, continue on } catch (NoAvailableSlaveException e) { // do nothing, continue on } } } // show race stats if (conn.getGlobalContext().getZsConfig().raceStatsEnabled()) { try { SFVFile sfvfile = newCurrentDirectory.lookupSFVFile(); Collection racers = RankUtils.userSort(sfvfile.getFiles(), "bytes", "high"); Collection groups = RankUtils.topFileGroup(sfvfile.getFiles()); String racerline = bundle.getString("cwd.racers.body"); //logger.debug("racerline = " + racerline); String groupline = bundle.getString("cwd.groups.body"); ReplacerEnvironment env = BaseFtpConnection.getReplacerEnvironment(null, conn.getUserNull()); //Start building race message String racetext = bundle.getString("cwd.racestats.header") + "\n"; racetext += bundle.getString("cwd.racers.header") + "\n"; ReplacerFormat raceformat = null; //Add racer stats int position = 1; for (Iterator iter = racers.iterator(); iter.hasNext();) { UploaderPosition stat = (UploaderPosition) iter.next(); User raceuser; try { raceuser = conn.getGlobalContext().getUserManager() .getUserByName(stat.getUsername()); } catch (NoSuchUserException e2) { continue; } catch (UserFileException e2) { logger.log(Level.FATAL, "Error reading userfile", e2); continue; } ReplacerEnvironment raceenv = new ReplacerEnvironment(); raceenv.add("speed", Bytes.formatBytes(stat.getXferspeed()) + "/s"); raceenv.add("user", stat.getUsername()); raceenv.add("group", raceuser.getGroup()); raceenv.add("files", "" + stat.getFiles()); raceenv.add("bytes", Bytes.formatBytes(stat.getBytes())); raceenv.add("position", String.valueOf(position)); raceenv.add("percent", Integer.toString( (stat.getFiles() * 100) / sfvfile.size()) + "%"); try { racetext += (SimplePrintf.jprintf(racerline, raceenv) + "\n"); position++; } catch (FormatterException e) { logger.warn(e); } } racetext += bundle.getString("cwd.racers.footer") + "\n"; racetext += bundle.getString("cwd.groups.header") + "\n"; //add groups stats position = 1; for (Iterator iter = groups.iterator(); iter.hasNext();) { GroupPosition stat = (GroupPosition) iter.next(); ReplacerEnvironment raceenv = new ReplacerEnvironment(); raceenv.add("group", stat.getGroupname()); raceenv.add("position", String.valueOf(position)); raceenv.add("bytes", Bytes.formatBytes(stat.getBytes())); raceenv.add("files", Integer.toString(stat.getFiles())); raceenv.add("percent", Integer.toString( (stat.getFiles() * 100) / sfvfile.size()) + "%"); raceenv.add("speed", Bytes.formatBytes(stat.getXferspeed()) + "/s"); try { racetext += (SimplePrintf.jprintf(groupline, raceenv) + "\n"); position++; } catch (FormatterException e) { logger.warn(e); } } racetext += bundle.getString("cwd.groups.footer") + "\n"; env.add("totalfiles", Integer.toString(sfvfile.size())); env.add("totalbytes", Bytes.formatBytes(sfvfile.getTotalBytes())); env.add("totalspeed", Bytes.formatBytes(sfvfile.getXferspeed()) + "/s"); env.add("totalpercent", Integer.toString( (sfvfile.getStatus().getPresent() * 100) / sfvfile.size()) + "%"); racetext += bundle.getString("cwd.totals.body") + "\n"; racetext += bundle.getString("cwd.racestats.footer") + "\n"; try { raceformat = ReplacerFormat.createFormat(racetext); } catch (FormatterException e1) { logger.warn(e1); } try { if (raceformat == null) { response.addComment("cwd.uploaders"); } else { response.addComment(SimplePrintf.jprintf(raceformat, env)); } } catch (FormatterException e) { response.addComment("cwd.uploaders"); logger.warn("", e); } } catch (RuntimeException ex) { logger.error("", ex); } catch (IOException e) { //Error fetching SFV, ignore } catch (NoAvailableSlaveException e) { //Error fetching SFV, ignore } } */ return response; } /** * <code>DELE &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * This command causes the file specified in the pathname to be * deleted at the server site. */ private Reply doDELE(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { //out.print(FtpResponse.RESPONSE_501_SYNTAX_ERROR); return Reply.RESPONSE_501_SYNTAX_ERROR; } // get filenames String fileName = request.getArgument(); InodeHandle requestedFile; Reply reply = (Reply) Reply.RESPONSE_250_ACTION_OKAY.clone(); try { requestedFile = conn.getCurrentDirectory().getInodeHandle(fileName); // check permission if (requestedFile.getUsername().equals(conn.getUserNull().getName())) { if (!conn.getGlobalContext().getConfig().checkPathPermission("deleteown", conn.getUserNull(), requestedFile.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } } else if (!conn.getGlobalContext().getConfig().checkPathPermission("delete", conn.getUserNull(), requestedFile.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } if (requestedFile.isDirectory()) { DirectoryHandle victim = (DirectoryHandle) requestedFile; if (victim.getInodeHandles().size() != 0) { return new Reply(550, requestedFile.getPath() + ": Directory not empty"); } } User uploader; try { uploader = conn.getGlobalContext().getUserManager().getUserByName( requestedFile.getUsername()); uploader.updateCredits((long) -(requestedFile.getSize() * conn .getGlobalContext().getConfig().getCreditCheckRatio( requestedFile.getParent(), uploader))); if (!conn.getGlobalContext().getConfig().checkPathPermission( "nostatsup", uploader, conn.getCurrentDirectory())) { uploader.updateUploadedBytes(-requestedFile.getSize()); } } catch (UserFileException e) { reply.addComment("Error removing credits & stats: " + e.getMessage()); } catch (NoSuchUserException e) { reply.addComment("User " + requestedFile.getUsername() + " does not exist, cannot remove credits on deletion"); } conn.getGlobalContext().dispatchFtpEvent(new DirectoryFtpEvent( conn.getUserNull(), "DELE", requestedFile.getParent())); requestedFile.delete(); } catch (FileNotFoundException e) { // good! we're done :) return new Reply(550, e.getMessage()); } return reply; } /** * <code>MDTM &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * Returns the date and time of when a file was modified. */ private Reply doMDTM(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } // get filenames String fileName = request.getArgument(); InodeHandle reqFile; try { reqFile = conn.getCurrentDirectory().getInodeHandle(fileName); } catch (FileNotFoundException ex) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } //fileName = user.getVirtualDirectory().getAbsoluteName(fileName); //String physicalName = // user.getVirtualDirectory().getPhysicalName(fileName); //File reqFile = new File(physicalName); // now print date //if (reqFile.exists()) { try { return new Reply(213, DATE_FMT.format(new Date(reqFile.lastModified()))); } catch (FileNotFoundException e) { return new Reply(550, e.getMessage()); } //out.print(ftpStatus.getResponse(213, request, user, args)); //} else { // out.write(ftpStatus.getResponse(550, request, user, null)); //} } /** * <code>MKD &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * This command causes the directory specified in the pathname * to be created as a directory (if the pathname is absolute) * or as a subdirectory of the current working directory (if * the pathname is relative). * * * MKD * 257 * 500, 501, 502, 421, 530, 550 */ private Reply doMKD(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } String dirName = request.getArgument(); //check for NUKED dir /* * save Teflon's for a few weeks? logger.info(conn.getCurrentDirectory().getName()); logger.info(request.getArgument()); logger.info("[NUKED]-" + ret.getPath()); if (conn.getCurrentDirectory().hasFile("[NUKED]-" + ret.getPath())) { return new Reply(550, "Requested action not taken. " + request.getArgument() + " is nuked!"); } */ // ************************************* // begin nuke log check /* String toPath; if (request.getArgument().substring(0, 1).equals("/")) { toPath = request.getArgument(); } else { StringBuffer toPath2 = new StringBuffer(conn.getCurrentDirectory() .getPath()); if (toPath2.length() != 1) toPath2.append("/"); // isn't / toPath2.append(request.getArgument()); toPath = toPath2.toString(); } // Try Nuke, then if that doesn't work, try TDPSiteNuke. NukeBeans nukeBeans = NukeBeans.getNukeBeans(); if (nukeBeans != null && nukeBeans.findPath(toPath)) { try { String reason = nukeBeans.get(toPath).getReason(); return new Reply(530, "Access denied - Directory already nuked for '" + reason + "'"); } catch (ObjectNotFoundException e) { return new Reply(530, "Access denied - Directory already nuked, reason unavailable - " + e.getMessage()); } }*/ // end nuke log check // ************************************* if (!ListUtils.isLegalFileName(dirName)) { return Reply.RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN; } if (!conn.getGlobalContext().getConfig().checkPathPermission("makedir", conn.getUserNull(), conn.getCurrentDirectory())) { return Reply.RESPONSE_530_ACCESS_DENIED; } try { DirectoryHandle newDir = null; try { newDir = conn.getCurrentDirectory().createDirectory(dirName,conn.getUserNull().getName(), conn.getUserNull().getGroup()); } catch (FileNotFoundException e) { return new Reply(550, "Parent directory does not exist"); } conn.getGlobalContext().dispatchFtpEvent(new DirectoryFtpEvent( conn.getUserNull(), "MKD", newDir)); return new Reply(257, "\"" + newDir.getPath() + "\" created."); } catch (FileExistsException ex) { return new Reply(550, "directory " + dirName + " already exists"); } } /** * <code>PWD &lt;CRLF&gt;</code><br> * * This command causes the name of the current working * directory to be returned in the reply. */ private Reply doPWD(BaseFtpConnection conn) { return new Reply(257, "\"" + conn.getCurrentDirectory().getPath() + "\" is current directory"); } /** * <code>RMD &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * This command causes the directory specified in the pathname * to be removed as a directory (if the pathname is absolute) * or as a subdirectory of the current working directory (if * the pathname is relative). */ private Reply doRMD(BaseFtpConnection conn) { return doDELE(conn); // strange, the ftp rfc says it is exactly equal to DELE, we allow DELE to delete files // that might be wrong, but saves me from writing this method... /* FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } // get file names String fileName = request.getArgument(); LinkedRemoteFile requestedFile; try { requestedFile = conn.getCurrentDirectory().lookupFile(fileName); } catch (FileNotFoundException e) { return new Reply(550, fileName + ": " + e.getMessage()); } if (requestedFile.getUsername().equals(conn.getUserNull().getName())) { if (!conn.getGlobalContext().getConfig().checkPathPermission("deleteown", conn.getUserNull(), requestedFile)) { return Reply.RESPONSE_530_ACCESS_DENIED; } } else if (!conn.getGlobalContext().getConfig().checkPathPermission("delete", conn.getUserNull(), requestedFile)) { return Reply.RESPONSE_530_ACCESS_DENIED; } if (!requestedFile.isDirectory()) { return new Reply(550, fileName + ": Not a directory"); } if (requestedFile.dirSize() != 0) { return new Reply(550, fileName + ": Directory not empty"); } // now delete //if (conn.getConfig().checkDirLog(conn.getUserNull(), requestedFile)) { conn.getGlobalContext().dispatchFtpEvent(new DirectoryFtpEvent( conn.getUserNull(), "RMD", requestedFile)); //} requestedFile.delete(); return Reply.RESPONSE_250_ACTION_OKAY; */ } /** * <code>RNFR &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * This command specifies the old pathname of the file which is * to be renamed. This command must be immediately followed by * a "rename to" command specifying the new file pathname. * * RNFR 450, 550 500, 501, 502, 421, 530 350 */ private Reply doRNFR(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } // set state variable // get filenames //String fileName = request.getArgument(); //fileName = user.getVirtualDirectory().getAbsoluteName(fileName); //mstRenFr = user.getVirtualDirectory().getPhysicalName(fileName); try { _renameFrom = conn.getCurrentDirectory().getInodeHandle(request.getArgument()); //check permission if (_renameFrom.getUsername().equals(conn.getUserNull().getName())) { if (!conn.getGlobalContext().getConfig().checkPathPermission("renameown", conn.getUserNull(), _renameFrom.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } } else if (!conn.getGlobalContext().getConfig().checkPathPermission("rename", conn.getUserNull(), _renameFrom.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } return new Reply(350, "File exists, ready for destination name"); } /** * <code>RNTO &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * This command specifies the new pathname of the file * specified in the immediately preceding "rename from" * command. Together the two commands cause a file to be * renamed. */ private Reply doRNTO(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } // set state variables if (_renameFrom == null) { return Reply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS; } InodeHandle fromInode = _renameFrom; String argument = VirtualFileSystem.fixPath(request.getArgument()); if (!(argument.startsWith(VirtualFileSystem.separator))) { // Not a full path, let's make it one if (conn.getCurrentDirectory().isRoot()) { argument = VirtualFileSystem.separator + argument; } else { argument = conn.getCurrentDirectory().getPath() + VirtualFileSystem.separator + argument; } } DirectoryHandle toDir = null; String newName = null; try { toDir = conn.getCurrentDirectory().getDirectory(argument); // toDir exists and is a directory, so we're just changing the parent directory and not the name newName = fromInode.getName(); } catch (FileNotFoundException e) { // Directory does not exist, that means they may have specified _renameFrom's new name // as the last part of the argument try { toDir = conn.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument)); newName = VirtualFileSystem.getLast(argument); } catch (FileNotFoundException e1) { // Destination doesn't exist logger.debug("Destination doesn't exist", e1); return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } catch (ObjectNotValidException e1) { // Destination isn't a Directory logger.debug("Destination isn't a Directory", e1); return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } } catch (ObjectNotValidException e) { return Reply.RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN_FILE_EXISTS; } InodeHandle toInode = null; if (fromInode.isDirectory()) { toInode = new DirectoryHandle(toDir.getPath() + VirtualFileSystem.separator + newName); } else if (fromInode.isFile()) { toInode = new FileHandle(toDir.getPath() + VirtualFileSystem.separator + newName); } else if (fromInode.isLink()) { toInode = new LinkHandle(toDir.getPath() + VirtualFileSystem.separator + newName); + } else { + return new Reply(500, "Someone has extended the VFS beyond File/Directory/Link"); } try { // check permission if (_renameFrom.getUsername().equals(conn.getUserNull().getName())) { if (!conn.getGlobalContext().getConfig().checkPathPermission( "renameown", conn.getUserNull(), toInode.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } } else if (!conn.getGlobalContext().getConfig() .checkPathPermission("rename", conn.getUserNull(), toInode.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } /* logger.debug("before rename toInode-" +toInode); logger.debug("before rename toInode.getPath()-" + toInode.getPath()); logger.debug("before rename toInode.getParent()-" + toInode.getParent()); logger.debug("before rename toInode.getParent().getPath()-" + toInode.getParent().getPath());*/ fromInode.renameTo(toInode); } catch (FileNotFoundException e) { logger.info("FileNotFoundException on renameTo()", e); return new Reply(500, "FileNotFound - " + e.getMessage()); } catch (IOException e) { logger.info("IOException on renameTo()", e); return new Reply(500, "IOException - " + e.getMessage()); } /* logger.debug("after rename toInode-" +toInode); logger.debug("after rename toInode.getPath()-" + toInode.getPath()); logger.debug("after rename toInode.getParent()-" + toInode.getParent()); logger.debug("after rename toInode.getParent().getPath()-" + toInode.getParent().getPath());*/ // out.write(FtpResponse.RESPONSE_250_ACTION_OKAY.toString()); return new Reply(250, request.getCommand() + " command successful."); } private Reply doSITE_CHOWN(BaseFtpConnection conn) throws UnhandledCommandException { FtpRequest req = conn.getRequest(); StringTokenizer st = new StringTokenizer(conn.getRequest().getArgument()); String owner = st.nextToken(); String group = null; int pos = owner.indexOf('.'); if (pos != -1) { group = owner.substring(pos + 1); owner = owner.substring(0, pos); } else if ("SITE CHGRP".equals(req.getCommand())) { group = owner; owner = null; } else if (!"SITE CHOWN".equals(req.getCommand())) { throw UnhandledCommandException.create(Dir.class, req); } Reply reply = new Reply(200); while (st.hasMoreTokens()) { try { InodeHandle file = conn.getCurrentDirectory().getInodeHandle(st.nextToken()); if (owner != null) { file.setUsername(owner); } if (group != null) { file.setGroup(group); } } catch (FileNotFoundException e) { reply.addComment(e.getMessage()); } } return Reply.RESPONSE_200_COMMAND_OK; } private Reply doSITE_LINK(BaseFtpConnection conn) { if (!conn.getRequest().hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } StringTokenizer st = new StringTokenizer(conn.getRequest().getArgument(), " "); if (st.countTokens() != 2) { return Reply.RESPONSE_501_SYNTAX_ERROR; } String targetName = st.nextToken(); String linkName = st.nextToken(); try { conn.getCurrentDirectory().getInodeHandle(targetName); // checks if the inode exists. conn.getCurrentDirectory().createLink(linkName, targetName, conn.getUserNull().getName(), conn.getUserNull().getGroup()); // create the link } catch (FileExistsException e) { return Reply.RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN_FILE_EXISTS; } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } return Reply.RESPONSE_200_COMMAND_OK; } /** * USAGE: site wipe [-r] <file/directory> * * This is similar to the UNIX rm command. * In glftpd, if you just delete a file, the uploader loses credits and * upload stats for it. There are many people who didn't like that and * were unable/too lazy to write a shell script to do it for them, so I * wrote this command to get them off my back. * * If the argument is a file, it will simply be deleted. If it's a * directory, it and the files it contains will be deleted. If the * directory contains other directories, the deletion will be aborted. * * To remove a directory containing subdirectories, you need to use * "site wipe -r dirname". BE CAREFUL WHO YOU GIVE ACCESS TO THIS COMMAND. * Glftpd will check if the parent directory of the file/directory you're * trying to delete is writable by its owner. If not, wipe will not * execute, so to protect directories from being wiped, make their parent * 555. * * Also, wipe will only work where you have the right to delete (in * glftpd.conf). Delete right and parent directory's mode of 755/777/etc * will cause glftpd to SWITCH TO ROOT UID and wipe the file/directory. * "site wipe -r /" will not work, but "site wipe -r /incoming" WILL, SO * BE CAREFUL. * * This command will remove the deleted files/directories from the dirlog * and dupefile databases. * * To give access to this command, add "-wipe -user flag =group" to the * config file (similar to other site commands). * * @param request * @param out */ private Reply doSITE_WIPE(BaseFtpConnection conn) { if (!conn.getRequest().hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } String arg = conn.getRequest().getArgument(); boolean recursive; if (arg.startsWith("-r ")) { arg = arg.substring(3); recursive = true; } else { recursive = false; } InodeHandle wipeFile; try { wipeFile = conn.getCurrentDirectory().getInodeHandle(arg); if (wipeFile.isDirectory() && !recursive) { if (((DirectoryHandle) wipeFile).getInodeHandles().size() != 0) { return new Reply(200, "Can't wipe, directory not empty"); } } // if (conn.getConfig().checkDirLog(conn.getUserNull(), wipeFile)) { conn.getGlobalContext().dispatchFtpEvent( new DirectoryFtpEvent(conn.getUserNull(), "WIPE", wipeFile .getParent())); // } wipeFile.delete(); } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } return Reply.RESPONSE_200_COMMAND_OK; } /** * <code>SIZE &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * Returns the size of the file in bytes. */ private Reply doSIZE(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } InodeHandle file; try { file = conn.getCurrentDirectory().getInodeHandle(request.getArgument()); return new Reply(213, Long.toString(file.getSize())); } catch (FileNotFoundException ex) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } } /** * http://www.southrivertech.com/support/titanftp/webhelp/xcrc.htm * * Originally implemented by CuteFTP Pro and Globalscape FTP Server */ private Reply doXCRC(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } StringTokenizer st = new StringTokenizer(request.getArgument()); FileHandle myFile; try { myFile = conn.getCurrentDirectory().getFile(st.nextToken()); } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } catch (ObjectNotValidException e) { return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM; } try { if (st.hasMoreTokens()) { if (!st.nextToken().equals("0") || !st.nextToken().equals( Long.toString(myFile.getSize()))) { return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM; } } return new Reply(250, "XCRC Successful. " + Checksum.formatChecksum(myFile.getCheckSum())); } catch (NoAvailableSlaveException e1) { logger.warn("", e1); return new Reply(550, "NoAvailableSlaveException: " + e1.getMessage()); } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } } public Reply execute(BaseFtpConnection conn) throws UnhandledCommandException { FtpRequest request = conn.getRequest(); String cmd = request.getCommand(); if ("CDUP".equals(cmd)) { return doCDUP(conn); } if ("CWD".equals(cmd)) { return doCWD(conn); } if ("MKD".equals(cmd)) { return doMKD(conn); } if ("PWD".equals(cmd)) { return doPWD(conn); } if ("RMD".equals(cmd)) { return doRMD(conn); } if ("RNFR".equals(cmd)) { return doRNFR(conn); } if ("RNTO".equals(cmd)) { return doRNTO(conn); } if ("SITE LINK".equals(cmd)) { return doSITE_LINK(conn); } if ("SITE WIPE".equals(cmd)) { return doSITE_WIPE(conn); } if ("XCRC".equals(cmd)) { return doXCRC(conn); } if ("MDTM".equals(cmd)) { return doMDTM(conn); } if ("SIZE".equals(cmd)) { return doSIZE(conn); } if ("DELE".equals(cmd)) { return doDELE(conn); } if ("SITE CHOWN".equals(cmd) || "SITE CHGRP".equals(cmd)) { return doSITE_CHOWN(conn); } throw UnhandledCommandException.create(Dir.class, request); } // public String getHelp(String cmd) { // ResourceBundle bundle = ResourceBundle.getBundle(Dir.class.getName()); // if ("".equals(cmd)) // return bundle.getString("help.general")+"\n"; // else if("link".equals(cmd) || "link".equals(cmd) || "wipe".equals(cmd)) // return bundle.getString("help."+cmd)+"\n"; // else // return ""; // } public String[] getFeatReplies() { return null; } public CommandHandler initialize(BaseFtpConnection conn, CommandManager initializer) { try { return (Dir) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public void load(CommandManagerFactory initializer) { } public void unload() { } }
true
true
private Reply doRMD(BaseFtpConnection conn) { return doDELE(conn); // strange, the ftp rfc says it is exactly equal to DELE, we allow DELE to delete files // that might be wrong, but saves me from writing this method... /* FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } // get file names String fileName = request.getArgument(); LinkedRemoteFile requestedFile; try { requestedFile = conn.getCurrentDirectory().lookupFile(fileName); } catch (FileNotFoundException e) { return new Reply(550, fileName + ": " + e.getMessage()); } if (requestedFile.getUsername().equals(conn.getUserNull().getName())) { if (!conn.getGlobalContext().getConfig().checkPathPermission("deleteown", conn.getUserNull(), requestedFile)) { return Reply.RESPONSE_530_ACCESS_DENIED; } } else if (!conn.getGlobalContext().getConfig().checkPathPermission("delete", conn.getUserNull(), requestedFile)) { return Reply.RESPONSE_530_ACCESS_DENIED; } if (!requestedFile.isDirectory()) { return new Reply(550, fileName + ": Not a directory"); } if (requestedFile.dirSize() != 0) { return new Reply(550, fileName + ": Directory not empty"); } // now delete //if (conn.getConfig().checkDirLog(conn.getUserNull(), requestedFile)) { conn.getGlobalContext().dispatchFtpEvent(new DirectoryFtpEvent( conn.getUserNull(), "RMD", requestedFile)); //} requestedFile.delete(); return Reply.RESPONSE_250_ACTION_OKAY; */ } /** * <code>RNFR &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * This command specifies the old pathname of the file which is * to be renamed. This command must be immediately followed by * a "rename to" command specifying the new file pathname. * * RNFR 450, 550 500, 501, 502, 421, 530 350 */ private Reply doRNFR(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } // set state variable // get filenames //String fileName = request.getArgument(); //fileName = user.getVirtualDirectory().getAbsoluteName(fileName); //mstRenFr = user.getVirtualDirectory().getPhysicalName(fileName); try { _renameFrom = conn.getCurrentDirectory().getInodeHandle(request.getArgument()); //check permission if (_renameFrom.getUsername().equals(conn.getUserNull().getName())) { if (!conn.getGlobalContext().getConfig().checkPathPermission("renameown", conn.getUserNull(), _renameFrom.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } } else if (!conn.getGlobalContext().getConfig().checkPathPermission("rename", conn.getUserNull(), _renameFrom.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } return new Reply(350, "File exists, ready for destination name"); } /** * <code>RNTO &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * This command specifies the new pathname of the file * specified in the immediately preceding "rename from" * command. Together the two commands cause a file to be * renamed. */ private Reply doRNTO(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } // set state variables if (_renameFrom == null) { return Reply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS; } InodeHandle fromInode = _renameFrom; String argument = VirtualFileSystem.fixPath(request.getArgument()); if (!(argument.startsWith(VirtualFileSystem.separator))) { // Not a full path, let's make it one if (conn.getCurrentDirectory().isRoot()) { argument = VirtualFileSystem.separator + argument; } else { argument = conn.getCurrentDirectory().getPath() + VirtualFileSystem.separator + argument; } } DirectoryHandle toDir = null; String newName = null; try { toDir = conn.getCurrentDirectory().getDirectory(argument); // toDir exists and is a directory, so we're just changing the parent directory and not the name newName = fromInode.getName(); } catch (FileNotFoundException e) { // Directory does not exist, that means they may have specified _renameFrom's new name // as the last part of the argument try { toDir = conn.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument)); newName = VirtualFileSystem.getLast(argument); } catch (FileNotFoundException e1) { // Destination doesn't exist logger.debug("Destination doesn't exist", e1); return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } catch (ObjectNotValidException e1) { // Destination isn't a Directory logger.debug("Destination isn't a Directory", e1); return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } } catch (ObjectNotValidException e) { return Reply.RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN_FILE_EXISTS; } InodeHandle toInode = null; if (fromInode.isDirectory()) { toInode = new DirectoryHandle(toDir.getPath() + VirtualFileSystem.separator + newName); } else if (fromInode.isFile()) { toInode = new FileHandle(toDir.getPath() + VirtualFileSystem.separator + newName); } else if (fromInode.isLink()) { toInode = new LinkHandle(toDir.getPath() + VirtualFileSystem.separator + newName); } try { // check permission if (_renameFrom.getUsername().equals(conn.getUserNull().getName())) { if (!conn.getGlobalContext().getConfig().checkPathPermission( "renameown", conn.getUserNull(), toInode.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } } else if (!conn.getGlobalContext().getConfig() .checkPathPermission("rename", conn.getUserNull(), toInode.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } /* logger.debug("before rename toInode-" +toInode); logger.debug("before rename toInode.getPath()-" + toInode.getPath()); logger.debug("before rename toInode.getParent()-" + toInode.getParent()); logger.debug("before rename toInode.getParent().getPath()-" + toInode.getParent().getPath());*/ fromInode.renameTo(toInode); } catch (FileNotFoundException e) { logger.info("FileNotFoundException on renameTo()", e); return new Reply(500, "FileNotFound - " + e.getMessage()); } catch (IOException e) { logger.info("IOException on renameTo()", e); return new Reply(500, "IOException - " + e.getMessage()); } /* logger.debug("after rename toInode-" +toInode); logger.debug("after rename toInode.getPath()-" + toInode.getPath()); logger.debug("after rename toInode.getParent()-" + toInode.getParent()); logger.debug("after rename toInode.getParent().getPath()-" + toInode.getParent().getPath());*/ // out.write(FtpResponse.RESPONSE_250_ACTION_OKAY.toString()); return new Reply(250, request.getCommand() + " command successful."); } private Reply doSITE_CHOWN(BaseFtpConnection conn) throws UnhandledCommandException { FtpRequest req = conn.getRequest(); StringTokenizer st = new StringTokenizer(conn.getRequest().getArgument()); String owner = st.nextToken(); String group = null; int pos = owner.indexOf('.'); if (pos != -1) { group = owner.substring(pos + 1); owner = owner.substring(0, pos); } else if ("SITE CHGRP".equals(req.getCommand())) { group = owner; owner = null; } else if (!"SITE CHOWN".equals(req.getCommand())) { throw UnhandledCommandException.create(Dir.class, req); } Reply reply = new Reply(200); while (st.hasMoreTokens()) { try { InodeHandle file = conn.getCurrentDirectory().getInodeHandle(st.nextToken()); if (owner != null) { file.setUsername(owner); } if (group != null) { file.setGroup(group); } } catch (FileNotFoundException e) { reply.addComment(e.getMessage()); } } return Reply.RESPONSE_200_COMMAND_OK; } private Reply doSITE_LINK(BaseFtpConnection conn) { if (!conn.getRequest().hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } StringTokenizer st = new StringTokenizer(conn.getRequest().getArgument(), " "); if (st.countTokens() != 2) { return Reply.RESPONSE_501_SYNTAX_ERROR; } String targetName = st.nextToken(); String linkName = st.nextToken(); try { conn.getCurrentDirectory().getInodeHandle(targetName); // checks if the inode exists. conn.getCurrentDirectory().createLink(linkName, targetName, conn.getUserNull().getName(), conn.getUserNull().getGroup()); // create the link } catch (FileExistsException e) { return Reply.RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN_FILE_EXISTS; } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } return Reply.RESPONSE_200_COMMAND_OK; } /** * USAGE: site wipe [-r] <file/directory> * * This is similar to the UNIX rm command. * In glftpd, if you just delete a file, the uploader loses credits and * upload stats for it. There are many people who didn't like that and * were unable/too lazy to write a shell script to do it for them, so I * wrote this command to get them off my back. * * If the argument is a file, it will simply be deleted. If it's a * directory, it and the files it contains will be deleted. If the * directory contains other directories, the deletion will be aborted. * * To remove a directory containing subdirectories, you need to use * "site wipe -r dirname". BE CAREFUL WHO YOU GIVE ACCESS TO THIS COMMAND. * Glftpd will check if the parent directory of the file/directory you're * trying to delete is writable by its owner. If not, wipe will not * execute, so to protect directories from being wiped, make their parent * 555. * * Also, wipe will only work where you have the right to delete (in * glftpd.conf). Delete right and parent directory's mode of 755/777/etc * will cause glftpd to SWITCH TO ROOT UID and wipe the file/directory. * "site wipe -r /" will not work, but "site wipe -r /incoming" WILL, SO * BE CAREFUL. * * This command will remove the deleted files/directories from the dirlog * and dupefile databases. * * To give access to this command, add "-wipe -user flag =group" to the * config file (similar to other site commands). * * @param request * @param out */ private Reply doSITE_WIPE(BaseFtpConnection conn) { if (!conn.getRequest().hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } String arg = conn.getRequest().getArgument(); boolean recursive; if (arg.startsWith("-r ")) { arg = arg.substring(3); recursive = true; } else { recursive = false; } InodeHandle wipeFile; try { wipeFile = conn.getCurrentDirectory().getInodeHandle(arg); if (wipeFile.isDirectory() && !recursive) { if (((DirectoryHandle) wipeFile).getInodeHandles().size() != 0) { return new Reply(200, "Can't wipe, directory not empty"); } } // if (conn.getConfig().checkDirLog(conn.getUserNull(), wipeFile)) { conn.getGlobalContext().dispatchFtpEvent( new DirectoryFtpEvent(conn.getUserNull(), "WIPE", wipeFile .getParent())); // } wipeFile.delete(); } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } return Reply.RESPONSE_200_COMMAND_OK; } /** * <code>SIZE &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * Returns the size of the file in bytes. */ private Reply doSIZE(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } InodeHandle file; try { file = conn.getCurrentDirectory().getInodeHandle(request.getArgument()); return new Reply(213, Long.toString(file.getSize())); } catch (FileNotFoundException ex) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } } /** * http://www.southrivertech.com/support/titanftp/webhelp/xcrc.htm * * Originally implemented by CuteFTP Pro and Globalscape FTP Server */ private Reply doXCRC(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } StringTokenizer st = new StringTokenizer(request.getArgument()); FileHandle myFile; try { myFile = conn.getCurrentDirectory().getFile(st.nextToken()); } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } catch (ObjectNotValidException e) { return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM; } try { if (st.hasMoreTokens()) { if (!st.nextToken().equals("0") || !st.nextToken().equals( Long.toString(myFile.getSize()))) { return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM; } } return new Reply(250, "XCRC Successful. " + Checksum.formatChecksum(myFile.getCheckSum())); } catch (NoAvailableSlaveException e1) { logger.warn("", e1); return new Reply(550, "NoAvailableSlaveException: " + e1.getMessage()); } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } } public Reply execute(BaseFtpConnection conn) throws UnhandledCommandException { FtpRequest request = conn.getRequest(); String cmd = request.getCommand(); if ("CDUP".equals(cmd)) { return doCDUP(conn); } if ("CWD".equals(cmd)) { return doCWD(conn); } if ("MKD".equals(cmd)) { return doMKD(conn); } if ("PWD".equals(cmd)) { return doPWD(conn); } if ("RMD".equals(cmd)) { return doRMD(conn); } if ("RNFR".equals(cmd)) { return doRNFR(conn); } if ("RNTO".equals(cmd)) { return doRNTO(conn); } if ("SITE LINK".equals(cmd)) { return doSITE_LINK(conn); } if ("SITE WIPE".equals(cmd)) { return doSITE_WIPE(conn); } if ("XCRC".equals(cmd)) { return doXCRC(conn); } if ("MDTM".equals(cmd)) { return doMDTM(conn); } if ("SIZE".equals(cmd)) { return doSIZE(conn); } if ("DELE".equals(cmd)) { return doDELE(conn); } if ("SITE CHOWN".equals(cmd) || "SITE CHGRP".equals(cmd)) { return doSITE_CHOWN(conn); } throw UnhandledCommandException.create(Dir.class, request); } // public String getHelp(String cmd) { // ResourceBundle bundle = ResourceBundle.getBundle(Dir.class.getName()); // if ("".equals(cmd)) // return bundle.getString("help.general")+"\n"; // else if("link".equals(cmd) || "link".equals(cmd) || "wipe".equals(cmd)) // return bundle.getString("help."+cmd)+"\n"; // else // return ""; // } public String[] getFeatReplies() { return null; } public CommandHandler initialize(BaseFtpConnection conn, CommandManager initializer) { try { return (Dir) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public void load(CommandManagerFactory initializer) { } public void unload() { } }
private Reply doRMD(BaseFtpConnection conn) { return doDELE(conn); // strange, the ftp rfc says it is exactly equal to DELE, we allow DELE to delete files // that might be wrong, but saves me from writing this method... /* FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } // get file names String fileName = request.getArgument(); LinkedRemoteFile requestedFile; try { requestedFile = conn.getCurrentDirectory().lookupFile(fileName); } catch (FileNotFoundException e) { return new Reply(550, fileName + ": " + e.getMessage()); } if (requestedFile.getUsername().equals(conn.getUserNull().getName())) { if (!conn.getGlobalContext().getConfig().checkPathPermission("deleteown", conn.getUserNull(), requestedFile)) { return Reply.RESPONSE_530_ACCESS_DENIED; } } else if (!conn.getGlobalContext().getConfig().checkPathPermission("delete", conn.getUserNull(), requestedFile)) { return Reply.RESPONSE_530_ACCESS_DENIED; } if (!requestedFile.isDirectory()) { return new Reply(550, fileName + ": Not a directory"); } if (requestedFile.dirSize() != 0) { return new Reply(550, fileName + ": Directory not empty"); } // now delete //if (conn.getConfig().checkDirLog(conn.getUserNull(), requestedFile)) { conn.getGlobalContext().dispatchFtpEvent(new DirectoryFtpEvent( conn.getUserNull(), "RMD", requestedFile)); //} requestedFile.delete(); return Reply.RESPONSE_250_ACTION_OKAY; */ } /** * <code>RNFR &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * This command specifies the old pathname of the file which is * to be renamed. This command must be immediately followed by * a "rename to" command specifying the new file pathname. * * RNFR 450, 550 500, 501, 502, 421, 530 350 */ private Reply doRNFR(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } // set state variable // get filenames //String fileName = request.getArgument(); //fileName = user.getVirtualDirectory().getAbsoluteName(fileName); //mstRenFr = user.getVirtualDirectory().getPhysicalName(fileName); try { _renameFrom = conn.getCurrentDirectory().getInodeHandle(request.getArgument()); //check permission if (_renameFrom.getUsername().equals(conn.getUserNull().getName())) { if (!conn.getGlobalContext().getConfig().checkPathPermission("renameown", conn.getUserNull(), _renameFrom.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } } else if (!conn.getGlobalContext().getConfig().checkPathPermission("rename", conn.getUserNull(), _renameFrom.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } return new Reply(350, "File exists, ready for destination name"); } /** * <code>RNTO &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * This command specifies the new pathname of the file * specified in the immediately preceding "rename from" * command. Together the two commands cause a file to be * renamed. */ private Reply doRNTO(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); // argument check if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } // set state variables if (_renameFrom == null) { return Reply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS; } InodeHandle fromInode = _renameFrom; String argument = VirtualFileSystem.fixPath(request.getArgument()); if (!(argument.startsWith(VirtualFileSystem.separator))) { // Not a full path, let's make it one if (conn.getCurrentDirectory().isRoot()) { argument = VirtualFileSystem.separator + argument; } else { argument = conn.getCurrentDirectory().getPath() + VirtualFileSystem.separator + argument; } } DirectoryHandle toDir = null; String newName = null; try { toDir = conn.getCurrentDirectory().getDirectory(argument); // toDir exists and is a directory, so we're just changing the parent directory and not the name newName = fromInode.getName(); } catch (FileNotFoundException e) { // Directory does not exist, that means they may have specified _renameFrom's new name // as the last part of the argument try { toDir = conn.getCurrentDirectory().getDirectory(VirtualFileSystem.stripLast(argument)); newName = VirtualFileSystem.getLast(argument); } catch (FileNotFoundException e1) { // Destination doesn't exist logger.debug("Destination doesn't exist", e1); return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } catch (ObjectNotValidException e1) { // Destination isn't a Directory logger.debug("Destination isn't a Directory", e1); return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } } catch (ObjectNotValidException e) { return Reply.RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN_FILE_EXISTS; } InodeHandle toInode = null; if (fromInode.isDirectory()) { toInode = new DirectoryHandle(toDir.getPath() + VirtualFileSystem.separator + newName); } else if (fromInode.isFile()) { toInode = new FileHandle(toDir.getPath() + VirtualFileSystem.separator + newName); } else if (fromInode.isLink()) { toInode = new LinkHandle(toDir.getPath() + VirtualFileSystem.separator + newName); } else { return new Reply(500, "Someone has extended the VFS beyond File/Directory/Link"); } try { // check permission if (_renameFrom.getUsername().equals(conn.getUserNull().getName())) { if (!conn.getGlobalContext().getConfig().checkPathPermission( "renameown", conn.getUserNull(), toInode.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } } else if (!conn.getGlobalContext().getConfig() .checkPathPermission("rename", conn.getUserNull(), toInode.getParent())) { return Reply.RESPONSE_530_ACCESS_DENIED; } /* logger.debug("before rename toInode-" +toInode); logger.debug("before rename toInode.getPath()-" + toInode.getPath()); logger.debug("before rename toInode.getParent()-" + toInode.getParent()); logger.debug("before rename toInode.getParent().getPath()-" + toInode.getParent().getPath());*/ fromInode.renameTo(toInode); } catch (FileNotFoundException e) { logger.info("FileNotFoundException on renameTo()", e); return new Reply(500, "FileNotFound - " + e.getMessage()); } catch (IOException e) { logger.info("IOException on renameTo()", e); return new Reply(500, "IOException - " + e.getMessage()); } /* logger.debug("after rename toInode-" +toInode); logger.debug("after rename toInode.getPath()-" + toInode.getPath()); logger.debug("after rename toInode.getParent()-" + toInode.getParent()); logger.debug("after rename toInode.getParent().getPath()-" + toInode.getParent().getPath());*/ // out.write(FtpResponse.RESPONSE_250_ACTION_OKAY.toString()); return new Reply(250, request.getCommand() + " command successful."); } private Reply doSITE_CHOWN(BaseFtpConnection conn) throws UnhandledCommandException { FtpRequest req = conn.getRequest(); StringTokenizer st = new StringTokenizer(conn.getRequest().getArgument()); String owner = st.nextToken(); String group = null; int pos = owner.indexOf('.'); if (pos != -1) { group = owner.substring(pos + 1); owner = owner.substring(0, pos); } else if ("SITE CHGRP".equals(req.getCommand())) { group = owner; owner = null; } else if (!"SITE CHOWN".equals(req.getCommand())) { throw UnhandledCommandException.create(Dir.class, req); } Reply reply = new Reply(200); while (st.hasMoreTokens()) { try { InodeHandle file = conn.getCurrentDirectory().getInodeHandle(st.nextToken()); if (owner != null) { file.setUsername(owner); } if (group != null) { file.setGroup(group); } } catch (FileNotFoundException e) { reply.addComment(e.getMessage()); } } return Reply.RESPONSE_200_COMMAND_OK; } private Reply doSITE_LINK(BaseFtpConnection conn) { if (!conn.getRequest().hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } StringTokenizer st = new StringTokenizer(conn.getRequest().getArgument(), " "); if (st.countTokens() != 2) { return Reply.RESPONSE_501_SYNTAX_ERROR; } String targetName = st.nextToken(); String linkName = st.nextToken(); try { conn.getCurrentDirectory().getInodeHandle(targetName); // checks if the inode exists. conn.getCurrentDirectory().createLink(linkName, targetName, conn.getUserNull().getName(), conn.getUserNull().getGroup()); // create the link } catch (FileExistsException e) { return Reply.RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN_FILE_EXISTS; } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } return Reply.RESPONSE_200_COMMAND_OK; } /** * USAGE: site wipe [-r] <file/directory> * * This is similar to the UNIX rm command. * In glftpd, if you just delete a file, the uploader loses credits and * upload stats for it. There are many people who didn't like that and * were unable/too lazy to write a shell script to do it for them, so I * wrote this command to get them off my back. * * If the argument is a file, it will simply be deleted. If it's a * directory, it and the files it contains will be deleted. If the * directory contains other directories, the deletion will be aborted. * * To remove a directory containing subdirectories, you need to use * "site wipe -r dirname". BE CAREFUL WHO YOU GIVE ACCESS TO THIS COMMAND. * Glftpd will check if the parent directory of the file/directory you're * trying to delete is writable by its owner. If not, wipe will not * execute, so to protect directories from being wiped, make their parent * 555. * * Also, wipe will only work where you have the right to delete (in * glftpd.conf). Delete right and parent directory's mode of 755/777/etc * will cause glftpd to SWITCH TO ROOT UID and wipe the file/directory. * "site wipe -r /" will not work, but "site wipe -r /incoming" WILL, SO * BE CAREFUL. * * This command will remove the deleted files/directories from the dirlog * and dupefile databases. * * To give access to this command, add "-wipe -user flag =group" to the * config file (similar to other site commands). * * @param request * @param out */ private Reply doSITE_WIPE(BaseFtpConnection conn) { if (!conn.getRequest().hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } String arg = conn.getRequest().getArgument(); boolean recursive; if (arg.startsWith("-r ")) { arg = arg.substring(3); recursive = true; } else { recursive = false; } InodeHandle wipeFile; try { wipeFile = conn.getCurrentDirectory().getInodeHandle(arg); if (wipeFile.isDirectory() && !recursive) { if (((DirectoryHandle) wipeFile).getInodeHandles().size() != 0) { return new Reply(200, "Can't wipe, directory not empty"); } } // if (conn.getConfig().checkDirLog(conn.getUserNull(), wipeFile)) { conn.getGlobalContext().dispatchFtpEvent( new DirectoryFtpEvent(conn.getUserNull(), "WIPE", wipeFile .getParent())); // } wipeFile.delete(); } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } return Reply.RESPONSE_200_COMMAND_OK; } /** * <code>SIZE &lt;SP&gt; &lt;pathname&gt; &lt;CRLF&gt;</code><br> * * Returns the size of the file in bytes. */ private Reply doSIZE(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } InodeHandle file; try { file = conn.getCurrentDirectory().getInodeHandle(request.getArgument()); return new Reply(213, Long.toString(file.getSize())); } catch (FileNotFoundException ex) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } } /** * http://www.southrivertech.com/support/titanftp/webhelp/xcrc.htm * * Originally implemented by CuteFTP Pro and Globalscape FTP Server */ private Reply doXCRC(BaseFtpConnection conn) { FtpRequest request = conn.getRequest(); if (!request.hasArgument()) { return Reply.RESPONSE_501_SYNTAX_ERROR; } StringTokenizer st = new StringTokenizer(request.getArgument()); FileHandle myFile; try { myFile = conn.getCurrentDirectory().getFile(st.nextToken()); } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } catch (ObjectNotValidException e) { return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM; } try { if (st.hasMoreTokens()) { if (!st.nextToken().equals("0") || !st.nextToken().equals( Long.toString(myFile.getSize()))) { return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM; } } return new Reply(250, "XCRC Successful. " + Checksum.formatChecksum(myFile.getCheckSum())); } catch (NoAvailableSlaveException e1) { logger.warn("", e1); return new Reply(550, "NoAvailableSlaveException: " + e1.getMessage()); } catch (FileNotFoundException e) { return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN; } } public Reply execute(BaseFtpConnection conn) throws UnhandledCommandException { FtpRequest request = conn.getRequest(); String cmd = request.getCommand(); if ("CDUP".equals(cmd)) { return doCDUP(conn); } if ("CWD".equals(cmd)) { return doCWD(conn); } if ("MKD".equals(cmd)) { return doMKD(conn); } if ("PWD".equals(cmd)) { return doPWD(conn); } if ("RMD".equals(cmd)) { return doRMD(conn); } if ("RNFR".equals(cmd)) { return doRNFR(conn); } if ("RNTO".equals(cmd)) { return doRNTO(conn); } if ("SITE LINK".equals(cmd)) { return doSITE_LINK(conn); } if ("SITE WIPE".equals(cmd)) { return doSITE_WIPE(conn); } if ("XCRC".equals(cmd)) { return doXCRC(conn); } if ("MDTM".equals(cmd)) { return doMDTM(conn); } if ("SIZE".equals(cmd)) { return doSIZE(conn); } if ("DELE".equals(cmd)) { return doDELE(conn); } if ("SITE CHOWN".equals(cmd) || "SITE CHGRP".equals(cmd)) { return doSITE_CHOWN(conn); } throw UnhandledCommandException.create(Dir.class, request); } // public String getHelp(String cmd) { // ResourceBundle bundle = ResourceBundle.getBundle(Dir.class.getName()); // if ("".equals(cmd)) // return bundle.getString("help.general")+"\n"; // else if("link".equals(cmd) || "link".equals(cmd) || "wipe".equals(cmd)) // return bundle.getString("help."+cmd)+"\n"; // else // return ""; // } public String[] getFeatReplies() { return null; } public CommandHandler initialize(BaseFtpConnection conn, CommandManager initializer) { try { return (Dir) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public void load(CommandManagerFactory initializer) { } public void unload() { } }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskWorkingSetFilter.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskWorkingSetFilter.java index 1bfbbc72e..c6bcef8d2 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskWorkingSetFilter.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskWorkingSetFilter.java @@ -1,73 +1,74 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.ui; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.mylyn.internal.tasks.core.LocalTask; import org.eclipse.mylyn.internal.tasks.core.ScheduledTaskContainer; import org.eclipse.mylyn.tasks.core.AbstractRepositoryQuery; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.core.AbstractTaskContainer; import org.eclipse.mylyn.tasks.core.TaskList; import org.eclipse.ui.IWorkingSet; /** * AbstractTaskListFilter for task working sets * * @author Eugene Kuleshov */ public class TaskWorkingSetFilter extends AbstractTaskListFilter { private final TaskList taskList; private IWorkingSet currentWorkingSet; public TaskWorkingSetFilter(TaskList taskList) { this.taskList = taskList; } @Override public boolean select(Object parent, Object element) { - if (parent instanceof AbstractTaskContainer && !(parent instanceof ScheduledTaskContainer)) { + if (parent instanceof AbstractTaskContainer && !(parent instanceof AbstractTask) + && !(parent instanceof ScheduledTaskContainer)) { return selectWorkingSet((AbstractTaskContainer) parent); } if (element instanceof LocalTask) { for (AbstractTaskContainer container : ((LocalTask) element).getParentContainers()) { return selectWorkingSet(container); } } if (element instanceof AbstractTask) { AbstractRepositoryQuery query = taskList.getQueryForHandle(((AbstractTask) element).getHandleIdentifier()); if (query != null) { return selectWorkingSet(query); } } return true; } private boolean selectWorkingSet(AbstractTaskContainer container) { if (currentWorkingSet == null) { return true; } boolean seenTaskWorkingSets = false; String handleIdentifier = container.getHandleIdentifier(); for (IAdaptable adaptable : currentWorkingSet.getElements()) { if (adaptable instanceof AbstractTaskContainer) { seenTaskWorkingSets = true; if (handleIdentifier.equals(((AbstractTaskContainer) adaptable).getHandleIdentifier())) { return true; } } } return !seenTaskWorkingSets; } public void setCurrentWorkingSet(IWorkingSet currentWorkingSet) { this.currentWorkingSet = currentWorkingSet; } }
true
true
public boolean select(Object parent, Object element) { if (parent instanceof AbstractTaskContainer && !(parent instanceof ScheduledTaskContainer)) { return selectWorkingSet((AbstractTaskContainer) parent); } if (element instanceof LocalTask) { for (AbstractTaskContainer container : ((LocalTask) element).getParentContainers()) { return selectWorkingSet(container); } } if (element instanceof AbstractTask) { AbstractRepositoryQuery query = taskList.getQueryForHandle(((AbstractTask) element).getHandleIdentifier()); if (query != null) { return selectWorkingSet(query); } } return true; }
public boolean select(Object parent, Object element) { if (parent instanceof AbstractTaskContainer && !(parent instanceof AbstractTask) && !(parent instanceof ScheduledTaskContainer)) { return selectWorkingSet((AbstractTaskContainer) parent); } if (element instanceof LocalTask) { for (AbstractTaskContainer container : ((LocalTask) element).getParentContainers()) { return selectWorkingSet(container); } } if (element instanceof AbstractTask) { AbstractRepositoryQuery query = taskList.getQueryForHandle(((AbstractTask) element).getHandleIdentifier()); if (query != null) { return selectWorkingSet(query); } } return true; }
diff --git a/core/src/main/java/com/railinc/jook/service/impl/ViewTrackingServiceImpl.java b/core/src/main/java/com/railinc/jook/service/impl/ViewTrackingServiceImpl.java index 187dac6..d72b98d 100644 --- a/core/src/main/java/com/railinc/jook/service/impl/ViewTrackingServiceImpl.java +++ b/core/src/main/java/com/railinc/jook/service/impl/ViewTrackingServiceImpl.java @@ -1,86 +1,87 @@ package com.railinc.jook.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import com.railinc.jook.domain.DomainObject; import com.railinc.jook.domain.LastUserView; import com.railinc.jook.service.ViewTrackingService; public class ViewTrackingServiceImpl extends BaseServiceImpl<LastUserView> implements ViewTrackingService { @Override public void userJustSaw(String user, String application, String resource) { if (user == null) { return; } if (getHibernateTemplate().bulkUpdate("UPDATE LastUserView SET lastViewed=? WHERE app=? AND name=? and user = ?", new Date(), application, resource, user) == 0) { super.saveOrUpdate(new LastUserView(user,application,resource)); } } @Override public boolean hasUserSeen(String user, String application, String resource) { if ( null == user ) { return false; } return super.count(createCriteria().add(Restrictions.eq("name", resource)).add(Restrictions.eq("app", application))) > 0; } @Override public void resetViewState(String application, String resource) { getHibernateTemplate().bulkUpdate("DELETE FROM LastUserView WHERE app=? AND name=?", application,resource); } @Override protected Class<? extends DomainObject> domainClass() { return LastUserView.class; } @Override public boolean userHasNotSeenAll(String user, String viewtrackingAppname, List<? extends Object> itemIds) { if (user == null) { return true; } List<String> ids = new ArrayList<String>(itemIds.size()); for (Object o : itemIds) { ids.add(String.valueOf(o)); } return super.count( createCriteria().add( Restrictions.in("name", ids)) + .add(Restrictions.eq("user", user)) .add(Restrictions.eq("app", viewtrackingAppname) )) < ids.size(); } @Override public void resetViewState(String application, List<? extends Object> itemIds) { for (Object o : itemIds) { resetViewState(application, String.valueOf(o)); } } @Override public void userJustSawItems(String user, String viewtrackingAppname, List<? extends Object> itemIds) { for (Object o : itemIds) { userJustSaw(user, viewtrackingAppname, String.valueOf(o)); } } @Override public List<String> whatHasUserSeen(String user, String viewtrackingAppname) { Date now = new Date(); DetachedCriteria c = DetachedCriteria.forClass(this.domainClass()); c.add(Restrictions.eq("app", viewtrackingAppname)); c.add(Restrictions.eq("user", user)); c.setProjection(Projections.property("name")); return list(String.class, c); } }
true
true
public boolean userHasNotSeenAll(String user, String viewtrackingAppname, List<? extends Object> itemIds) { if (user == null) { return true; } List<String> ids = new ArrayList<String>(itemIds.size()); for (Object o : itemIds) { ids.add(String.valueOf(o)); } return super.count( createCriteria().add( Restrictions.in("name", ids)) .add(Restrictions.eq("app", viewtrackingAppname) )) < ids.size(); }
public boolean userHasNotSeenAll(String user, String viewtrackingAppname, List<? extends Object> itemIds) { if (user == null) { return true; } List<String> ids = new ArrayList<String>(itemIds.size()); for (Object o : itemIds) { ids.add(String.valueOf(o)); } return super.count( createCriteria().add( Restrictions.in("name", ids)) .add(Restrictions.eq("user", user)) .add(Restrictions.eq("app", viewtrackingAppname) )) < ids.size(); }
diff --git a/fixture/src/main/java/onaboat/domain/model/location/SampleLocations.java b/fixture/src/main/java/onaboat/domain/model/location/SampleLocations.java index 9052846..3b2a9da 100644 --- a/fixture/src/main/java/onaboat/domain/model/location/SampleLocations.java +++ b/fixture/src/main/java/onaboat/domain/model/location/SampleLocations.java @@ -1,33 +1,33 @@ package onaboat.domain.model.location; import onaboat.domain.model.location.Location; import onaboat.domain.model.location.UnLocode; import org.apache.isis.applib.fixtures.AbstractFixture; /** * DOC: THIS CLASS HAS NO COMMENT! * * @author adamhoward */ public class SampleLocations extends AbstractFixture { @Override public void install() { getContainer().persistIfNotAlready(new Location(new UnLocode("CNHKG"), "Hongkong")); getContainer().persistIfNotAlready(new Location(new UnLocode("AUMEL"), "Melbourne")); getContainer().persistIfNotAlready(new Location(new UnLocode("SESTO"), "Stockholm")); getContainer().persistIfNotAlready(new Location(new UnLocode("FIHEL"), "Helsinki")); getContainer().persistIfNotAlready(new Location(new UnLocode("USCHI"), "Chicago")); getContainer().persistIfNotAlready(new Location(new UnLocode("JNTKO"), "Tokyo")); getContainer().persistIfNotAlready(new Location(new UnLocode("DEHAM"), "Hamburg")); getContainer().persistIfNotAlready(new Location(new UnLocode("CNSHA"), "Shanghai")); getContainer().persistIfNotAlready(new Location(new UnLocode("NLRTM"), "Rotterdam")); - getContainer().persistIfNotAlready(new Location(new UnLocode("SEGOT"), "G�teborg")); + getContainer().persistIfNotAlready(new Location(new UnLocode("SEGOT"), "Göteborg")); getContainer().persistIfNotAlready(new Location(new UnLocode("CNHGH"), "Hangzhou")); getContainer().persistIfNotAlready(new Location(new UnLocode("USNYC"), "New York")); getContainer().persistIfNotAlready(new Location(new UnLocode("USDAL"), "Dallas")); getContainer().flush(); } }
true
true
public void install() { getContainer().persistIfNotAlready(new Location(new UnLocode("CNHKG"), "Hongkong")); getContainer().persistIfNotAlready(new Location(new UnLocode("AUMEL"), "Melbourne")); getContainer().persistIfNotAlready(new Location(new UnLocode("SESTO"), "Stockholm")); getContainer().persistIfNotAlready(new Location(new UnLocode("FIHEL"), "Helsinki")); getContainer().persistIfNotAlready(new Location(new UnLocode("USCHI"), "Chicago")); getContainer().persistIfNotAlready(new Location(new UnLocode("JNTKO"), "Tokyo")); getContainer().persistIfNotAlready(new Location(new UnLocode("DEHAM"), "Hamburg")); getContainer().persistIfNotAlready(new Location(new UnLocode("CNSHA"), "Shanghai")); getContainer().persistIfNotAlready(new Location(new UnLocode("NLRTM"), "Rotterdam")); getContainer().persistIfNotAlready(new Location(new UnLocode("SEGOT"), "G�teborg")); getContainer().persistIfNotAlready(new Location(new UnLocode("CNHGH"), "Hangzhou")); getContainer().persistIfNotAlready(new Location(new UnLocode("USNYC"), "New York")); getContainer().persistIfNotAlready(new Location(new UnLocode("USDAL"), "Dallas")); getContainer().flush(); }
public void install() { getContainer().persistIfNotAlready(new Location(new UnLocode("CNHKG"), "Hongkong")); getContainer().persistIfNotAlready(new Location(new UnLocode("AUMEL"), "Melbourne")); getContainer().persistIfNotAlready(new Location(new UnLocode("SESTO"), "Stockholm")); getContainer().persistIfNotAlready(new Location(new UnLocode("FIHEL"), "Helsinki")); getContainer().persistIfNotAlready(new Location(new UnLocode("USCHI"), "Chicago")); getContainer().persistIfNotAlready(new Location(new UnLocode("JNTKO"), "Tokyo")); getContainer().persistIfNotAlready(new Location(new UnLocode("DEHAM"), "Hamburg")); getContainer().persistIfNotAlready(new Location(new UnLocode("CNSHA"), "Shanghai")); getContainer().persistIfNotAlready(new Location(new UnLocode("NLRTM"), "Rotterdam")); getContainer().persistIfNotAlready(new Location(new UnLocode("SEGOT"), "Göteborg")); getContainer().persistIfNotAlready(new Location(new UnLocode("CNHGH"), "Hangzhou")); getContainer().persistIfNotAlready(new Location(new UnLocode("USNYC"), "New York")); getContainer().persistIfNotAlready(new Location(new UnLocode("USDAL"), "Dallas")); getContainer().flush(); }
diff --git a/Fallout-Equestria-The-Game/src/screenCore/PonyCreatorScreen.java b/Fallout-Equestria-The-Game/src/screenCore/PonyCreatorScreen.java index d1cf93f..c1005cd 100644 --- a/Fallout-Equestria-The-Game/src/screenCore/PonyCreatorScreen.java +++ b/Fallout-Equestria-The-Game/src/screenCore/PonyCreatorScreen.java @@ -1,716 +1,716 @@ package screenCore; import java.util.ArrayList; import java.util.List; import java.util.Random; import animation.AnimationPlayer; import animation.Bones; import animation.ManeStyle; import animation.PonyColorChangeHelper; import animation.TextureDictionary; import animation.TextureEntry; import common.PlayerCharacteristics; import common.Race; import common.SpecialStats; import GUI.IItemFormater; import GUI.ItemEventArgs; import GUI.ScrollEventArgs; import GUI.controls.AnimationBox; import GUI.controls.Button; import GUI.controls.ComboBox; import GUI.controls.ImageBox; import GUI.controls.Label; import GUI.controls.Panel; import GUI.controls.Slider; import GUI.controls.Textfield; import GUI.controls.ToggleButton; import GUI.graphics.GUIRenderingContext; import GUI.graphics.LookAndFeel; import math.Vector2; import misc.EventArgs; import misc.IEventListener; import utils.GameTime; import utils.Rectangle; import utils.TimeSpan; import content.ContentManager; import content.PlayerCharacteristicsWriter; import graphics.Color; import graphics.ShaderEffect; import graphics.SpriteBatch; import graphics.Texture2D; public class PonyCreatorScreen extends TransitioningGUIScreen { public static final String PonyArchetypePath = "Player.archetype"; private GUIRenderingContext context; private ContentManager contentManager = new ContentManager("resources"); private PlayerCharacteristicsWriter charWriter = new PlayerCharacteristicsWriter(contentManager); private AnimationPlayer ponyPlayer; private PlayerCharacteristics character = new PlayerCharacteristics(); private TextureDictionary assetDictionary = this.contentManager.load("rddict.tdict", TextureDictionary.class); private Vector2 ponyPosition = new Vector2(1025,96); private Vector2 ponyScale = new Vector2(2,2); private ImageBox bG; private Button button; private Button button2; private Button button3; private Textfield nameField; private Slider bodyRedSlider; private Slider bodyGreenSlider; private Slider bodyBlueSlider; private Slider eyeRedSlider; private Slider eyeGreenSlider; private Slider eyeBlueSlider; private Slider maneRedSlider; private Slider maneGreenSlider; private Slider maneBlueSlider; private ComboBox<ManeEntries> maneComboBox; private ComboBox<EyeEntries> eyeComboBox; private ComboBox<MarkEntries> markComboBox; private ToggleButton earthPonyButton; private ToggleButton pegasusButton; private ToggleButton unicornButton; private List<ManeEntries> maneStyles; private List<EyeEntries> eyeStyles; private List<MarkEntries> markStyles; private ToggleButton walkButton; private Label nameLabel; private Label bodyLabel; private Label eyeLabel; private Label maneLabel; private Panel namePanel; private Panel racePanel; private Panel bodyPanel; private Panel eyePanel; private Panel manePanel; private AnimationBox ponyBox; public PonyCreatorScreen(String lookAndFeelPath) { super(false, TimeSpan.fromSeconds(1d), TimeSpan.fromSeconds(0.5d), lookAndFeelPath); } @Override public void initialize(ContentManager contentManager) { super.initialize(contentManager); this.bG = new ImageBox(); this.bG.setImage(contentManager.load("darkPonyville.png", Texture2D.class)); this.bG.setBounds(this.ScreenManager.getViewport()); super.addGuiControl(this.bG, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(0,0), new Vector2(0,this.ScreenManager.getViewport().Height)); addPony(); this.ponyBox = new AnimationBox(); this.ponyBox.setBounds(0,0,250,208); this.ponyBox.setScale(ponyScale); this.ponyBox.setAnimationPlayer(ponyPlayer); super.addGuiControl(this.ponyBox, new Vector2(0,this.ScreenManager.getViewport().Height), ponyPosition, new Vector2(0,this.ScreenManager.getViewport().Height)); this.maneStyles = new ArrayList<ManeEntries>(); ManeEntries rDManeStyle = new ManeEntries("Rainbow style!", new ManeStyle("RDUPPERMANE", "RDLOWERMANE", "RDUPPERTAIL", "RDLOWERTAIL"), this.assetDictionary); this.maneStyles.add(rDManeStyle); ManeEntries tSManeStyle = new ManeEntries("Twilight style!", new ManeStyle("TSUPPERMANE", "TSLOWERMANE", "TSUPPERTAIL", "TSLOWERTAIL"), this.assetDictionary); this.maneStyles.add(tSManeStyle); this.maneComboBox = new ComboBox<ManeEntries>(); this.maneComboBox.setBounds(0,200, 250, 30); this.maneComboBox.setBgColor(new Color(0,0,0,0)); this.maneComboBox.setFont(contentManager.loadFont("Monofonto24.xml")); this.maneComboBox.addItem(rDManeStyle); this.maneComboBox.addItem(tSManeStyle); this.maneComboBox.setItemFormater(new IItemFormater<ManeEntries>(){ @Override public String formatItem(ManeEntries item) { return item.name; } }); this.maneComboBox.addSelectedChangedListener(new IEventListener<ItemEventArgs<ManeEntries>>() { @Override public void onEvent(Object sender, ItemEventArgs<ManeEntries> e) { setManeStyle(); } }); this.maneComboBox.setSelectedIndex(0); this.eyeStyles = new ArrayList<EyeEntries>(); EyeEntries rDEyeStyle = new EyeEntries("Rainbow style!", "RDEYE", this.assetDictionary); this.eyeStyles.add(rDEyeStyle); EyeEntries tSEyeStyle = new EyeEntries("Twilight style!", "TSEYE", this.assetDictionary); this.eyeStyles.add(tSEyeStyle); this.eyeComboBox = new ComboBox<EyeEntries>(); this.eyeComboBox.setBounds(0,200, 250, 30); this.eyeComboBox.setBgColor(new Color(0,0,0,0)); this.eyeComboBox.setFont(contentManager.loadFont("Monofonto24.xml")); this.eyeComboBox.addItem(rDEyeStyle); this.eyeComboBox.addItem(tSEyeStyle); this.eyeComboBox.setItemFormater(new IItemFormater<EyeEntries>(){ @Override public String formatItem(EyeEntries item) { return item.name; } }); eyeComboBox.addSelectedChangedListener(new IEventListener<ItemEventArgs<EyeEntries>>() { @Override public void onEvent(Object sender, ItemEventArgs<EyeEntries> e) { setEyeStyle(); } }); this.eyeComboBox.setSelectedIndex(0); this.markStyles = new ArrayList<MarkEntries>(); MarkEntries rDMarkStyle = new MarkEntries("Rainbow style!", "RDMARK", this.assetDictionary); this.markStyles.add(rDMarkStyle); MarkEntries tSMarkStyle = new MarkEntries("Twilight style!", "TSMARK", this.assetDictionary); this.markStyles.add(tSMarkStyle); MarkEntries mCMarkStyle = new MarkEntries("Hammer time!", "MCMARK", this.assetDictionary); this.markStyles.add(mCMarkStyle); this.markComboBox = new ComboBox<MarkEntries>(); this.markComboBox.setBounds(0,200, 250, 30); this.markComboBox.setBgColor(new Color(0,0,0,0)); this.markComboBox.setFont(contentManager.loadFont("Monofonto24.xml")); this.markComboBox.addItem(rDMarkStyle); this.markComboBox.addItem(tSMarkStyle); this.markComboBox.addItem(mCMarkStyle); this.markComboBox.setItemFormater(new IItemFormater<MarkEntries>(){ @Override public String formatItem(MarkEntries item) { return item.name; } }); markComboBox.addSelectedChangedListener(new IEventListener<ItemEventArgs<MarkEntries>>() { @Override public void onEvent(Object sender, ItemEventArgs<MarkEntries> e) { setMarkStyle(); } }); this.markComboBox.setSelectedIndex(0); this.nameField = new Textfield(); this.nameField.setBounds(0,50,250,25); - this.nameField.setText("Name goes here :)"); + this.nameField.setText("Name goes here"); this.nameField.setFont(contentManager.loadFont("Monofonto24.xml")); this.nameField.setFgColor(Color.White); this.nameField.setMaxLength(25); this.bodyRedSlider = new Slider(); this.bodyRedSlider.setFgColor(new Color(255,50,50,255)); this.bodyRedSlider.setBounds(0, 50, 250, 30); this.bodyRedSlider.setScrollMax(255); this.bodyRedSlider.setScrollValue(255); this.bodyRedSlider.setHorizontal(true); this.bodyRedSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setBodyColor(); } }); this.bodyGreenSlider = new Slider(); this.bodyGreenSlider.setFgColor(new Color(50,255,50,255)); this.bodyGreenSlider.setBounds(new Rectangle(0,100,250,30)); this.bodyGreenSlider.setScrollMax(255); this.bodyGreenSlider.setScrollValue(255); this.bodyGreenSlider.setHorizontal(true); this.bodyGreenSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setBodyColor(); } }); this.bodyBlueSlider = new Slider(); this.bodyBlueSlider.setFgColor(new Color(50,50,255,255)); this.bodyBlueSlider.setBounds(new Rectangle(0,150,250,30)); this.bodyBlueSlider.setScrollMax(255); this.bodyBlueSlider.setScrollValue(255); this.bodyBlueSlider.setHorizontal(true); this.bodyBlueSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setBodyColor(); } }); this.eyeRedSlider = new Slider(); this.eyeRedSlider.setBounds(0, 50, 250, 30); this.eyeRedSlider.setFgColor(new Color(255,50,50,255)); this.eyeRedSlider.setScrollMax(255); this.eyeRedSlider.setScrollValue(255); this.eyeRedSlider.setHorizontal(true); this.eyeRedSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setEyeColor(); } }); this.eyeGreenSlider = new Slider(); this.eyeGreenSlider.setBounds(0, 100, 250, 30); this.eyeGreenSlider.setFgColor(new Color(50,255,50,255)); this.eyeGreenSlider.setScrollMax(255); this.eyeGreenSlider.setScrollValue(255); this.eyeGreenSlider.setHorizontal(true); this.eyeGreenSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setEyeColor(); } }); this.eyeBlueSlider = new Slider(); this.eyeBlueSlider.setBounds(0, 150, 250, 30); this.eyeBlueSlider.setFgColor(new Color(50,50,255,255)); this.eyeBlueSlider.setScrollMax(255); this.eyeBlueSlider.setScrollValue(255); this.eyeBlueSlider.setHorizontal(true); this.eyeBlueSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setEyeColor(); } }); this.maneRedSlider = new Slider(); this.maneRedSlider.setBounds(0, 50, 250, 30); this.maneRedSlider.setFgColor(new Color(255,50,50,255)); this.maneRedSlider.setScrollMax(255); this.maneRedSlider.setScrollValue(255); this.maneRedSlider.setHorizontal(true); this.maneRedSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setManeColor(); } }); this.maneGreenSlider = new Slider(); this.maneGreenSlider.setBounds(0, 100, 250, 30); this.maneGreenSlider.setFgColor(new Color(50,255,50,255)); this.maneGreenSlider.setScrollMax(255); this.maneGreenSlider.setScrollValue(255); this.maneGreenSlider.setHorizontal(true); this.maneGreenSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setManeColor(); } }); this.maneBlueSlider = new Slider(); this.maneBlueSlider.setBounds(0, 150, 250, 30); this.maneBlueSlider.setFgColor(new Color(50,50,255,255)); this.maneBlueSlider.setScrollMax(255); this.maneBlueSlider.setScrollValue(255); this.maneBlueSlider.setHorizontal(true); this.maneBlueSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setManeColor(); } }); this.bodyLabel = new Label(); this.bodyLabel.setFgColor(Color.White); this.bodyLabel.setBounds(0, 0, 250, 30); this.bodyLabel.setText("Body"); this.bodyLabel.setBgColor(Color.Transparent); this.eyeLabel = new Label(); this.eyeLabel.setFgColor(Color.White); this.eyeLabel.setBounds(0, 0, 250, 30); this.eyeLabel.setText("Eyes"); this.eyeLabel.setBgColor(Color.Transparent); this.maneLabel = new Label(); this.maneLabel.setFgColor(Color.White); this.maneLabel.setBounds(0, 0, 250, 30); this.maneLabel.setText("Mane"); this.maneLabel.setBgColor(Color.Transparent); this.nameLabel = new Label(); this.nameLabel.setFgColor(Color.White); this.nameLabel.setBounds(0, 0, 250, 30); this.nameLabel.setText("Name"); this.nameLabel.setBgColor(Color.Transparent); this.button = new Button(); this.button.setText("Done!"); this.button.setBounds(250,710,200,50); super.addGuiControl(button, new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height), new Vector2(this.ScreenManager.getViewport().Width - 250,this.ScreenManager.getViewport().Height-200), new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height)); LookAndFeel feel = contentManager.load(this.lookAndFeelPath, LookAndFeel.class); feel.setDefaultFont(contentManager.loadFont("Monofonto24.xml")); ShaderEffect dissabledEffect = contentManager.loadShaderEffect("GrayScale.effect"); context = new GUIRenderingContext(this.ScreenManager.getSpriteBatch(), feel, dissabledEffect); this.button.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { savePlayerCharacteristics(); goBack(); } }); this.button2 = new Button(); this.button2.setText("Back"); this.button2.setBounds(250,710,200,50); super.addGuiControl(button2, new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height), new Vector2(this.ScreenManager.getViewport().Width - 250,this.ScreenManager.getViewport().Height-100), new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height)); feel.setDefaultFont(contentManager.loadFont("Monofonto24.xml")); context = new GUIRenderingContext(this.ScreenManager.getSpriteBatch(), feel, dissabledEffect); this.button2.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { goBack(); } }); this.button3 = new Button(); this.button3.setText("Randomize"); this.button3.setBounds(250,710,200,50); super.addGuiControl(button3, new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height), new Vector2(this.ScreenManager.getViewport().Width - 250,this.ScreenManager.getViewport().Height-300), new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height)); feel.setDefaultFont(contentManager.loadFont("Monofonto24.xml")); context = new GUIRenderingContext(this.ScreenManager.getSpriteBatch(), feel, dissabledEffect); this.button3.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { randomizeAttributes(); } }); this.earthPonyButton = new ToggleButton(); this.earthPonyButton.setBounds(0, 0, 55, 55); this.earthPonyButton.setImage(contentManager.loadTexture("Earthponybuttonimage.png")); this.earthPonyButton.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { changeRaceToEarthpony(); } }); this.pegasusButton = new ToggleButton(); this.pegasusButton.setBounds(55, 0, 55, 55); this.pegasusButton.setImage(contentManager.loadTexture("Pegasusbuttonimage.png")); this.pegasusButton.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { changeRaceToPegasus(); } }); this.unicornButton = new ToggleButton(); this.unicornButton.setBounds(110, 0, 55, 55); this.unicornButton.setImage(contentManager.loadTexture("Unicornbuttonimage.png")); this.unicornButton.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { changeRaceToUnicorn(); } }); this.walkButton = new ToggleButton(); this.walkButton.setBounds(0, 0, 110, 40); this.walkButton.setText("Walk"); this.walkButton.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { toggleWalkAnimation(); } }); super.addGuiControl(this.walkButton, new Vector2(0,this.ScreenManager.getViewport().Height), Vector2.add(ponyPosition, new Vector2(70,208)), new Vector2(0,this.ScreenManager.getViewport().Height)); this.racePanel = new Panel(); this.racePanel.setBounds(0, 0, 165, 55); this.racePanel.setBgColor(new Color(0,0,0,0.05f)); this.racePanel.addChild(nameLabel); this.racePanel.addChild(this.earthPonyButton); this.racePanel.addChild(this.pegasusButton); this.racePanel.addChild(this.unicornButton); super.addGuiControl(this.racePanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(50,200), new Vector2(0,this.ScreenManager.getViewport().Height)); this.namePanel = new Panel(); this.namePanel.setBounds(0, 0, 250, 100); this.namePanel.setBgColor(new Color(0,0,0,0.05f)); this.namePanel.addChild(nameLabel); this.namePanel.addChild(this.nameField); super.addGuiControl(this.namePanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(100,50), new Vector2(0,this.ScreenManager.getViewport().Height)); this.bodyPanel = new Panel(); this.bodyPanel.setBounds(0, 0, 250, 500); this.bodyPanel.setBgColor(new Color(0,0,0,0.05f)); this.bodyPanel.addChild(bodyLabel); this.bodyPanel.addChild(this.bodyRedSlider); this.bodyPanel.addChild(this.bodyGreenSlider); this.bodyPanel.addChild(this.bodyBlueSlider); this.bodyPanel.addChild(this.markComboBox); super.addGuiControl(this.bodyPanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(50,300), new Vector2(0,this.ScreenManager.getViewport().Height)); this.eyePanel = new Panel(); this.eyePanel.setBounds(0, 0, 250, 500); this.eyePanel.setBgColor(new Color(0,0,0,0.05f)); this.eyePanel.addChild(eyeLabel); this.eyePanel.addChild(this.eyeComboBox); this.eyePanel.addChild(this.eyeRedSlider); this.eyePanel.addChild(this.eyeGreenSlider); this.eyePanel.addChild(this.eyeBlueSlider); super.addGuiControl(this.eyePanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(350,300), new Vector2(0,this.ScreenManager.getViewport().Height)); this.manePanel = new Panel(); this.manePanel.setBounds(0, 0, 250, 500); this.manePanel.setBgColor(new Color(0,0,0,0.05f)); this.manePanel.addChild(maneLabel); this.manePanel.addChild(this.maneComboBox); this.manePanel.addChild(this.maneRedSlider); this.manePanel.addChild(this.maneGreenSlider); this.manePanel.addChild(this.maneBlueSlider); super.addGuiControl(this.manePanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(650,300), new Vector2(0,this.ScreenManager.getViewport().Height)); setBodyColor(); setEyeColor(); setManeColor(); changeRaceToEarthpony(); this.earthPonyButton.setToggled(true); } protected void toggleWalkAnimation() { if(!this.walkButton.isToggled()){ this.ponyPlayer.startAnimation("walk"); }else{ this.ponyPlayer.startAnimation("idle"); } } protected void changeRaceToEarthpony() { this.ponyPlayer.setBoneHidden(Bones.WINGS.getValue(), true); this.pegasusButton.setToggled(false); this.ponyPlayer.setBoneHidden(Bones.HORN.getValue(), true); this.unicornButton.setToggled(false); } protected void changeRaceToPegasus() { this.earthPonyButton.setToggled(false); this.ponyPlayer.setBoneHidden(Bones.WINGS.getValue(), false); this.ponyPlayer.setBoneHidden(Bones.HORN.getValue(), true); this.unicornButton.setToggled(false); } protected void changeRaceToUnicorn() { this.earthPonyButton.setToggled(false); this.ponyPlayer.setBoneHidden(Bones.WINGS.getValue(), true); this.pegasusButton.setToggled(false); this.ponyPlayer.setBoneHidden(Bones.HORN.getValue(), false); } protected void randomizeAttributes() { Random random = new Random(); this.bodyRedSlider.setScrollValue(random.nextInt(this.bodyRedSlider.getScrollMax())); this.bodyGreenSlider.setScrollValue(random.nextInt(this.bodyGreenSlider.getScrollMax())); this.bodyBlueSlider.setScrollValue(random.nextInt(this.bodyBlueSlider.getScrollMax())); this.eyeRedSlider.setScrollValue(random.nextInt(this.eyeRedSlider.getScrollMax())); this.eyeGreenSlider.setScrollValue(random.nextInt(this.eyeGreenSlider.getScrollMax())); this.eyeBlueSlider.setScrollValue(random.nextInt(this.eyeBlueSlider.getScrollMax())); this.maneRedSlider.setScrollValue(random.nextInt(this.maneRedSlider.getScrollMax())); this.maneGreenSlider.setScrollValue(random.nextInt(this.maneGreenSlider.getScrollMax())); this.maneBlueSlider.setScrollValue(random.nextInt(this.maneBlueSlider.getScrollMax())); this.maneComboBox.setSelectedIndex(random.nextInt(this.maneComboBox.itemCount())); this.eyeComboBox.setSelectedIndex(random.nextInt(this.eyeComboBox.itemCount())); this.markComboBox.setSelectedIndex(random.nextInt(this.markComboBox.itemCount())); int rand = random.nextInt(3); if (rand <= 0){ changeRaceToEarthpony(); this.earthPonyButton.setToggled(true); } else if (rand <= 1){ changeRaceToPegasus(); this.pegasusButton.setToggled(true); } else { changeRaceToUnicorn(); this.unicornButton.setToggled(true); } } protected void savePlayerCharacteristics() { this.character.archetypePath = PonyArchetypePath; this.character.bodyColor = getBodyColor(); this.character.eyeColor = getEyeColor(); this.character.maneColor = getManeColor(); this.character.maneStyle = this.maneComboBox.getSelectedItem().maneStyle; this.character.eyeTexture = this.eyeComboBox.getSelectedItem().eyePath; this.character.name = this.nameField.getText(); this.character.markTexture = this.markComboBox.getSelectedItem().markPath; if(this.earthPonyButton.isToggled()){ this.character.race = Race.EARTHPONY.getValue(); }else if(this.pegasusButton.isToggled()){ this.character.race = Race.PEGASUS.getValue(); }else if(this.unicornButton.isToggled()){ this.character.race = Race.UNICORN.getValue(); } this.character.special = new SpecialStats(5, 3, 6, 7, 5, 7, 8); this.charWriter.savePlayerCharacteristics(this.character); } protected void setEyeStyle() { this.ponyPlayer.setBoneTexture(Bones.EYE.getValue(), this.eyeComboBox.getSelectedItem().eyeEntry); } protected void setManeStyle() { this.ponyPlayer.setBoneTexture(Bones.UPPERMANE.getValue(), this.maneComboBox.getSelectedItem().upperManeEntry); this.ponyPlayer.setBoneTexture(Bones.LOWERMANE.getValue(), this.maneComboBox.getSelectedItem().lowerManeEntry); this.ponyPlayer.setBoneTexture(Bones.UPPERTAIL.getValue(), this.maneComboBox.getSelectedItem().upperTailEntry); this.ponyPlayer.setBoneTexture(Bones.LOWERTAIL.getValue(), this.maneComboBox.getSelectedItem().lowerTailEntry); } protected void setMarkStyle() { this.ponyPlayer.setBoneTexture(Bones.MARK.getValue(), this.markComboBox.getSelectedItem().markEntry); } public void goBack() { this.exitScreen(); } protected void setBodyColor() { Color color = new Color(this.bodyRedSlider.getScrollValue(),this.bodyGreenSlider.getScrollValue(),this.bodyBlueSlider.getScrollValue(),255); setBodyColor(color); } protected void setBodyColor(Color color) { PonyColorChangeHelper.setBodyColor(color, ponyPlayer); } protected void setEyeColor() { Color color = new Color(this.eyeRedSlider.getScrollValue(),this.eyeGreenSlider.getScrollValue(),this.eyeBlueSlider.getScrollValue(),255); setEyeColor(color); } protected void setEyeColor(Color color) { PonyColorChangeHelper.setEyeColor(color, ponyPlayer); } protected void setManeColor() { Color color = new Color(this.maneRedSlider.getScrollValue(),this.maneGreenSlider.getScrollValue(),this.maneBlueSlider.getScrollValue(),255); setManeColor(color); } protected void setManeColor(Color color) { PonyColorChangeHelper.setManeColor(color, ponyPlayer); } protected Color getBodyColor() { Color color = new Color(this.bodyRedSlider.getScrollValue(),this.bodyGreenSlider.getScrollValue(),this.bodyBlueSlider.getScrollValue(),255); return color; } protected Color getEyeColor() { Color color = new Color(this.eyeRedSlider.getScrollValue(),this.eyeGreenSlider.getScrollValue(),this.eyeBlueSlider.getScrollValue(),255); return color; } protected Color getManeColor() { Color color = new Color(this.maneRedSlider.getScrollValue(),this.maneGreenSlider.getScrollValue(),this.maneBlueSlider.getScrollValue(),255); return color; } protected void showPauseScreen() { this.ScreenManager.addScreen("PauseScreen"); } @Override public void update(GameTime time, boolean otherScreeenHasFocus, boolean coveredByOtherScreen) { if(!otherScreeenHasFocus) { super.update(time, otherScreeenHasFocus, coveredByOtherScreen); } } private void addPony() { this.ponyPlayer = this.contentManager.load("rdset.animset", AnimationPlayer.class);; this.ponyPlayer.startAnimation("idle"); } @Override public void render(GameTime time, SpriteBatch batch) { super.render(time, batch); } private class ManeEntries{ String name; TextureEntry upperManeEntry; TextureEntry lowerManeEntry; TextureEntry upperTailEntry; TextureEntry lowerTailEntry; ManeStyle maneStyle; public ManeEntries(String name, ManeStyle maneStyle, TextureDictionary assetDict) { this.name = name; this.upperManeEntry = assetDict.extractTextureEntry(maneStyle.upperManeStyle); this.lowerManeEntry = assetDict.extractTextureEntry(maneStyle.lowerManeStyle); this.upperTailEntry = assetDict.extractTextureEntry(maneStyle.upperTailStyle); this.lowerTailEntry = assetDict.extractTextureEntry(maneStyle.lowerTailStyle); this.maneStyle = maneStyle; } } private class EyeEntries{ String name; TextureEntry eyeEntry; String eyePath; public EyeEntries(String name, String eyePath, TextureDictionary assetDict) { this.name = name; this.eyeEntry = assetDict.extractTextureEntry(eyePath); this.eyePath = eyePath; } } private class MarkEntries{ String name; TextureEntry markEntry; String markPath; public MarkEntries(String name, String markPath, TextureDictionary assetDict) { this.name = name; this.markEntry = assetDict.extractTextureEntry(markPath); this.markPath = markPath; } } }
true
true
public void initialize(ContentManager contentManager) { super.initialize(contentManager); this.bG = new ImageBox(); this.bG.setImage(contentManager.load("darkPonyville.png", Texture2D.class)); this.bG.setBounds(this.ScreenManager.getViewport()); super.addGuiControl(this.bG, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(0,0), new Vector2(0,this.ScreenManager.getViewport().Height)); addPony(); this.ponyBox = new AnimationBox(); this.ponyBox.setBounds(0,0,250,208); this.ponyBox.setScale(ponyScale); this.ponyBox.setAnimationPlayer(ponyPlayer); super.addGuiControl(this.ponyBox, new Vector2(0,this.ScreenManager.getViewport().Height), ponyPosition, new Vector2(0,this.ScreenManager.getViewport().Height)); this.maneStyles = new ArrayList<ManeEntries>(); ManeEntries rDManeStyle = new ManeEntries("Rainbow style!", new ManeStyle("RDUPPERMANE", "RDLOWERMANE", "RDUPPERTAIL", "RDLOWERTAIL"), this.assetDictionary); this.maneStyles.add(rDManeStyle); ManeEntries tSManeStyle = new ManeEntries("Twilight style!", new ManeStyle("TSUPPERMANE", "TSLOWERMANE", "TSUPPERTAIL", "TSLOWERTAIL"), this.assetDictionary); this.maneStyles.add(tSManeStyle); this.maneComboBox = new ComboBox<ManeEntries>(); this.maneComboBox.setBounds(0,200, 250, 30); this.maneComboBox.setBgColor(new Color(0,0,0,0)); this.maneComboBox.setFont(contentManager.loadFont("Monofonto24.xml")); this.maneComboBox.addItem(rDManeStyle); this.maneComboBox.addItem(tSManeStyle); this.maneComboBox.setItemFormater(new IItemFormater<ManeEntries>(){ @Override public String formatItem(ManeEntries item) { return item.name; } }); this.maneComboBox.addSelectedChangedListener(new IEventListener<ItemEventArgs<ManeEntries>>() { @Override public void onEvent(Object sender, ItemEventArgs<ManeEntries> e) { setManeStyle(); } }); this.maneComboBox.setSelectedIndex(0); this.eyeStyles = new ArrayList<EyeEntries>(); EyeEntries rDEyeStyle = new EyeEntries("Rainbow style!", "RDEYE", this.assetDictionary); this.eyeStyles.add(rDEyeStyle); EyeEntries tSEyeStyle = new EyeEntries("Twilight style!", "TSEYE", this.assetDictionary); this.eyeStyles.add(tSEyeStyle); this.eyeComboBox = new ComboBox<EyeEntries>(); this.eyeComboBox.setBounds(0,200, 250, 30); this.eyeComboBox.setBgColor(new Color(0,0,0,0)); this.eyeComboBox.setFont(contentManager.loadFont("Monofonto24.xml")); this.eyeComboBox.addItem(rDEyeStyle); this.eyeComboBox.addItem(tSEyeStyle); this.eyeComboBox.setItemFormater(new IItemFormater<EyeEntries>(){ @Override public String formatItem(EyeEntries item) { return item.name; } }); eyeComboBox.addSelectedChangedListener(new IEventListener<ItemEventArgs<EyeEntries>>() { @Override public void onEvent(Object sender, ItemEventArgs<EyeEntries> e) { setEyeStyle(); } }); this.eyeComboBox.setSelectedIndex(0); this.markStyles = new ArrayList<MarkEntries>(); MarkEntries rDMarkStyle = new MarkEntries("Rainbow style!", "RDMARK", this.assetDictionary); this.markStyles.add(rDMarkStyle); MarkEntries tSMarkStyle = new MarkEntries("Twilight style!", "TSMARK", this.assetDictionary); this.markStyles.add(tSMarkStyle); MarkEntries mCMarkStyle = new MarkEntries("Hammer time!", "MCMARK", this.assetDictionary); this.markStyles.add(mCMarkStyle); this.markComboBox = new ComboBox<MarkEntries>(); this.markComboBox.setBounds(0,200, 250, 30); this.markComboBox.setBgColor(new Color(0,0,0,0)); this.markComboBox.setFont(contentManager.loadFont("Monofonto24.xml")); this.markComboBox.addItem(rDMarkStyle); this.markComboBox.addItem(tSMarkStyle); this.markComboBox.addItem(mCMarkStyle); this.markComboBox.setItemFormater(new IItemFormater<MarkEntries>(){ @Override public String formatItem(MarkEntries item) { return item.name; } }); markComboBox.addSelectedChangedListener(new IEventListener<ItemEventArgs<MarkEntries>>() { @Override public void onEvent(Object sender, ItemEventArgs<MarkEntries> e) { setMarkStyle(); } }); this.markComboBox.setSelectedIndex(0); this.nameField = new Textfield(); this.nameField.setBounds(0,50,250,25); this.nameField.setText("Name goes here :)"); this.nameField.setFont(contentManager.loadFont("Monofonto24.xml")); this.nameField.setFgColor(Color.White); this.nameField.setMaxLength(25); this.bodyRedSlider = new Slider(); this.bodyRedSlider.setFgColor(new Color(255,50,50,255)); this.bodyRedSlider.setBounds(0, 50, 250, 30); this.bodyRedSlider.setScrollMax(255); this.bodyRedSlider.setScrollValue(255); this.bodyRedSlider.setHorizontal(true); this.bodyRedSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setBodyColor(); } }); this.bodyGreenSlider = new Slider(); this.bodyGreenSlider.setFgColor(new Color(50,255,50,255)); this.bodyGreenSlider.setBounds(new Rectangle(0,100,250,30)); this.bodyGreenSlider.setScrollMax(255); this.bodyGreenSlider.setScrollValue(255); this.bodyGreenSlider.setHorizontal(true); this.bodyGreenSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setBodyColor(); } }); this.bodyBlueSlider = new Slider(); this.bodyBlueSlider.setFgColor(new Color(50,50,255,255)); this.bodyBlueSlider.setBounds(new Rectangle(0,150,250,30)); this.bodyBlueSlider.setScrollMax(255); this.bodyBlueSlider.setScrollValue(255); this.bodyBlueSlider.setHorizontal(true); this.bodyBlueSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setBodyColor(); } }); this.eyeRedSlider = new Slider(); this.eyeRedSlider.setBounds(0, 50, 250, 30); this.eyeRedSlider.setFgColor(new Color(255,50,50,255)); this.eyeRedSlider.setScrollMax(255); this.eyeRedSlider.setScrollValue(255); this.eyeRedSlider.setHorizontal(true); this.eyeRedSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setEyeColor(); } }); this.eyeGreenSlider = new Slider(); this.eyeGreenSlider.setBounds(0, 100, 250, 30); this.eyeGreenSlider.setFgColor(new Color(50,255,50,255)); this.eyeGreenSlider.setScrollMax(255); this.eyeGreenSlider.setScrollValue(255); this.eyeGreenSlider.setHorizontal(true); this.eyeGreenSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setEyeColor(); } }); this.eyeBlueSlider = new Slider(); this.eyeBlueSlider.setBounds(0, 150, 250, 30); this.eyeBlueSlider.setFgColor(new Color(50,50,255,255)); this.eyeBlueSlider.setScrollMax(255); this.eyeBlueSlider.setScrollValue(255); this.eyeBlueSlider.setHorizontal(true); this.eyeBlueSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setEyeColor(); } }); this.maneRedSlider = new Slider(); this.maneRedSlider.setBounds(0, 50, 250, 30); this.maneRedSlider.setFgColor(new Color(255,50,50,255)); this.maneRedSlider.setScrollMax(255); this.maneRedSlider.setScrollValue(255); this.maneRedSlider.setHorizontal(true); this.maneRedSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setManeColor(); } }); this.maneGreenSlider = new Slider(); this.maneGreenSlider.setBounds(0, 100, 250, 30); this.maneGreenSlider.setFgColor(new Color(50,255,50,255)); this.maneGreenSlider.setScrollMax(255); this.maneGreenSlider.setScrollValue(255); this.maneGreenSlider.setHorizontal(true); this.maneGreenSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setManeColor(); } }); this.maneBlueSlider = new Slider(); this.maneBlueSlider.setBounds(0, 150, 250, 30); this.maneBlueSlider.setFgColor(new Color(50,50,255,255)); this.maneBlueSlider.setScrollMax(255); this.maneBlueSlider.setScrollValue(255); this.maneBlueSlider.setHorizontal(true); this.maneBlueSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setManeColor(); } }); this.bodyLabel = new Label(); this.bodyLabel.setFgColor(Color.White); this.bodyLabel.setBounds(0, 0, 250, 30); this.bodyLabel.setText("Body"); this.bodyLabel.setBgColor(Color.Transparent); this.eyeLabel = new Label(); this.eyeLabel.setFgColor(Color.White); this.eyeLabel.setBounds(0, 0, 250, 30); this.eyeLabel.setText("Eyes"); this.eyeLabel.setBgColor(Color.Transparent); this.maneLabel = new Label(); this.maneLabel.setFgColor(Color.White); this.maneLabel.setBounds(0, 0, 250, 30); this.maneLabel.setText("Mane"); this.maneLabel.setBgColor(Color.Transparent); this.nameLabel = new Label(); this.nameLabel.setFgColor(Color.White); this.nameLabel.setBounds(0, 0, 250, 30); this.nameLabel.setText("Name"); this.nameLabel.setBgColor(Color.Transparent); this.button = new Button(); this.button.setText("Done!"); this.button.setBounds(250,710,200,50); super.addGuiControl(button, new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height), new Vector2(this.ScreenManager.getViewport().Width - 250,this.ScreenManager.getViewport().Height-200), new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height)); LookAndFeel feel = contentManager.load(this.lookAndFeelPath, LookAndFeel.class); feel.setDefaultFont(contentManager.loadFont("Monofonto24.xml")); ShaderEffect dissabledEffect = contentManager.loadShaderEffect("GrayScale.effect"); context = new GUIRenderingContext(this.ScreenManager.getSpriteBatch(), feel, dissabledEffect); this.button.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { savePlayerCharacteristics(); goBack(); } }); this.button2 = new Button(); this.button2.setText("Back"); this.button2.setBounds(250,710,200,50); super.addGuiControl(button2, new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height), new Vector2(this.ScreenManager.getViewport().Width - 250,this.ScreenManager.getViewport().Height-100), new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height)); feel.setDefaultFont(contentManager.loadFont("Monofonto24.xml")); context = new GUIRenderingContext(this.ScreenManager.getSpriteBatch(), feel, dissabledEffect); this.button2.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { goBack(); } }); this.button3 = new Button(); this.button3.setText("Randomize"); this.button3.setBounds(250,710,200,50); super.addGuiControl(button3, new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height), new Vector2(this.ScreenManager.getViewport().Width - 250,this.ScreenManager.getViewport().Height-300), new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height)); feel.setDefaultFont(contentManager.loadFont("Monofonto24.xml")); context = new GUIRenderingContext(this.ScreenManager.getSpriteBatch(), feel, dissabledEffect); this.button3.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { randomizeAttributes(); } }); this.earthPonyButton = new ToggleButton(); this.earthPonyButton.setBounds(0, 0, 55, 55); this.earthPonyButton.setImage(contentManager.loadTexture("Earthponybuttonimage.png")); this.earthPonyButton.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { changeRaceToEarthpony(); } }); this.pegasusButton = new ToggleButton(); this.pegasusButton.setBounds(55, 0, 55, 55); this.pegasusButton.setImage(contentManager.loadTexture("Pegasusbuttonimage.png")); this.pegasusButton.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { changeRaceToPegasus(); } }); this.unicornButton = new ToggleButton(); this.unicornButton.setBounds(110, 0, 55, 55); this.unicornButton.setImage(contentManager.loadTexture("Unicornbuttonimage.png")); this.unicornButton.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { changeRaceToUnicorn(); } }); this.walkButton = new ToggleButton(); this.walkButton.setBounds(0, 0, 110, 40); this.walkButton.setText("Walk"); this.walkButton.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { toggleWalkAnimation(); } }); super.addGuiControl(this.walkButton, new Vector2(0,this.ScreenManager.getViewport().Height), Vector2.add(ponyPosition, new Vector2(70,208)), new Vector2(0,this.ScreenManager.getViewport().Height)); this.racePanel = new Panel(); this.racePanel.setBounds(0, 0, 165, 55); this.racePanel.setBgColor(new Color(0,0,0,0.05f)); this.racePanel.addChild(nameLabel); this.racePanel.addChild(this.earthPonyButton); this.racePanel.addChild(this.pegasusButton); this.racePanel.addChild(this.unicornButton); super.addGuiControl(this.racePanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(50,200), new Vector2(0,this.ScreenManager.getViewport().Height)); this.namePanel = new Panel(); this.namePanel.setBounds(0, 0, 250, 100); this.namePanel.setBgColor(new Color(0,0,0,0.05f)); this.namePanel.addChild(nameLabel); this.namePanel.addChild(this.nameField); super.addGuiControl(this.namePanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(100,50), new Vector2(0,this.ScreenManager.getViewport().Height)); this.bodyPanel = new Panel(); this.bodyPanel.setBounds(0, 0, 250, 500); this.bodyPanel.setBgColor(new Color(0,0,0,0.05f)); this.bodyPanel.addChild(bodyLabel); this.bodyPanel.addChild(this.bodyRedSlider); this.bodyPanel.addChild(this.bodyGreenSlider); this.bodyPanel.addChild(this.bodyBlueSlider); this.bodyPanel.addChild(this.markComboBox); super.addGuiControl(this.bodyPanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(50,300), new Vector2(0,this.ScreenManager.getViewport().Height)); this.eyePanel = new Panel(); this.eyePanel.setBounds(0, 0, 250, 500); this.eyePanel.setBgColor(new Color(0,0,0,0.05f)); this.eyePanel.addChild(eyeLabel); this.eyePanel.addChild(this.eyeComboBox); this.eyePanel.addChild(this.eyeRedSlider); this.eyePanel.addChild(this.eyeGreenSlider); this.eyePanel.addChild(this.eyeBlueSlider); super.addGuiControl(this.eyePanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(350,300), new Vector2(0,this.ScreenManager.getViewport().Height)); this.manePanel = new Panel(); this.manePanel.setBounds(0, 0, 250, 500); this.manePanel.setBgColor(new Color(0,0,0,0.05f)); this.manePanel.addChild(maneLabel); this.manePanel.addChild(this.maneComboBox); this.manePanel.addChild(this.maneRedSlider); this.manePanel.addChild(this.maneGreenSlider); this.manePanel.addChild(this.maneBlueSlider); super.addGuiControl(this.manePanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(650,300), new Vector2(0,this.ScreenManager.getViewport().Height)); setBodyColor(); setEyeColor(); setManeColor(); changeRaceToEarthpony(); this.earthPonyButton.setToggled(true); }
public void initialize(ContentManager contentManager) { super.initialize(contentManager); this.bG = new ImageBox(); this.bG.setImage(contentManager.load("darkPonyville.png", Texture2D.class)); this.bG.setBounds(this.ScreenManager.getViewport()); super.addGuiControl(this.bG, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(0,0), new Vector2(0,this.ScreenManager.getViewport().Height)); addPony(); this.ponyBox = new AnimationBox(); this.ponyBox.setBounds(0,0,250,208); this.ponyBox.setScale(ponyScale); this.ponyBox.setAnimationPlayer(ponyPlayer); super.addGuiControl(this.ponyBox, new Vector2(0,this.ScreenManager.getViewport().Height), ponyPosition, new Vector2(0,this.ScreenManager.getViewport().Height)); this.maneStyles = new ArrayList<ManeEntries>(); ManeEntries rDManeStyle = new ManeEntries("Rainbow style!", new ManeStyle("RDUPPERMANE", "RDLOWERMANE", "RDUPPERTAIL", "RDLOWERTAIL"), this.assetDictionary); this.maneStyles.add(rDManeStyle); ManeEntries tSManeStyle = new ManeEntries("Twilight style!", new ManeStyle("TSUPPERMANE", "TSLOWERMANE", "TSUPPERTAIL", "TSLOWERTAIL"), this.assetDictionary); this.maneStyles.add(tSManeStyle); this.maneComboBox = new ComboBox<ManeEntries>(); this.maneComboBox.setBounds(0,200, 250, 30); this.maneComboBox.setBgColor(new Color(0,0,0,0)); this.maneComboBox.setFont(contentManager.loadFont("Monofonto24.xml")); this.maneComboBox.addItem(rDManeStyle); this.maneComboBox.addItem(tSManeStyle); this.maneComboBox.setItemFormater(new IItemFormater<ManeEntries>(){ @Override public String formatItem(ManeEntries item) { return item.name; } }); this.maneComboBox.addSelectedChangedListener(new IEventListener<ItemEventArgs<ManeEntries>>() { @Override public void onEvent(Object sender, ItemEventArgs<ManeEntries> e) { setManeStyle(); } }); this.maneComboBox.setSelectedIndex(0); this.eyeStyles = new ArrayList<EyeEntries>(); EyeEntries rDEyeStyle = new EyeEntries("Rainbow style!", "RDEYE", this.assetDictionary); this.eyeStyles.add(rDEyeStyle); EyeEntries tSEyeStyle = new EyeEntries("Twilight style!", "TSEYE", this.assetDictionary); this.eyeStyles.add(tSEyeStyle); this.eyeComboBox = new ComboBox<EyeEntries>(); this.eyeComboBox.setBounds(0,200, 250, 30); this.eyeComboBox.setBgColor(new Color(0,0,0,0)); this.eyeComboBox.setFont(contentManager.loadFont("Monofonto24.xml")); this.eyeComboBox.addItem(rDEyeStyle); this.eyeComboBox.addItem(tSEyeStyle); this.eyeComboBox.setItemFormater(new IItemFormater<EyeEntries>(){ @Override public String formatItem(EyeEntries item) { return item.name; } }); eyeComboBox.addSelectedChangedListener(new IEventListener<ItemEventArgs<EyeEntries>>() { @Override public void onEvent(Object sender, ItemEventArgs<EyeEntries> e) { setEyeStyle(); } }); this.eyeComboBox.setSelectedIndex(0); this.markStyles = new ArrayList<MarkEntries>(); MarkEntries rDMarkStyle = new MarkEntries("Rainbow style!", "RDMARK", this.assetDictionary); this.markStyles.add(rDMarkStyle); MarkEntries tSMarkStyle = new MarkEntries("Twilight style!", "TSMARK", this.assetDictionary); this.markStyles.add(tSMarkStyle); MarkEntries mCMarkStyle = new MarkEntries("Hammer time!", "MCMARK", this.assetDictionary); this.markStyles.add(mCMarkStyle); this.markComboBox = new ComboBox<MarkEntries>(); this.markComboBox.setBounds(0,200, 250, 30); this.markComboBox.setBgColor(new Color(0,0,0,0)); this.markComboBox.setFont(contentManager.loadFont("Monofonto24.xml")); this.markComboBox.addItem(rDMarkStyle); this.markComboBox.addItem(tSMarkStyle); this.markComboBox.addItem(mCMarkStyle); this.markComboBox.setItemFormater(new IItemFormater<MarkEntries>(){ @Override public String formatItem(MarkEntries item) { return item.name; } }); markComboBox.addSelectedChangedListener(new IEventListener<ItemEventArgs<MarkEntries>>() { @Override public void onEvent(Object sender, ItemEventArgs<MarkEntries> e) { setMarkStyle(); } }); this.markComboBox.setSelectedIndex(0); this.nameField = new Textfield(); this.nameField.setBounds(0,50,250,25); this.nameField.setText("Name goes here"); this.nameField.setFont(contentManager.loadFont("Monofonto24.xml")); this.nameField.setFgColor(Color.White); this.nameField.setMaxLength(25); this.bodyRedSlider = new Slider(); this.bodyRedSlider.setFgColor(new Color(255,50,50,255)); this.bodyRedSlider.setBounds(0, 50, 250, 30); this.bodyRedSlider.setScrollMax(255); this.bodyRedSlider.setScrollValue(255); this.bodyRedSlider.setHorizontal(true); this.bodyRedSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setBodyColor(); } }); this.bodyGreenSlider = new Slider(); this.bodyGreenSlider.setFgColor(new Color(50,255,50,255)); this.bodyGreenSlider.setBounds(new Rectangle(0,100,250,30)); this.bodyGreenSlider.setScrollMax(255); this.bodyGreenSlider.setScrollValue(255); this.bodyGreenSlider.setHorizontal(true); this.bodyGreenSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setBodyColor(); } }); this.bodyBlueSlider = new Slider(); this.bodyBlueSlider.setFgColor(new Color(50,50,255,255)); this.bodyBlueSlider.setBounds(new Rectangle(0,150,250,30)); this.bodyBlueSlider.setScrollMax(255); this.bodyBlueSlider.setScrollValue(255); this.bodyBlueSlider.setHorizontal(true); this.bodyBlueSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setBodyColor(); } }); this.eyeRedSlider = new Slider(); this.eyeRedSlider.setBounds(0, 50, 250, 30); this.eyeRedSlider.setFgColor(new Color(255,50,50,255)); this.eyeRedSlider.setScrollMax(255); this.eyeRedSlider.setScrollValue(255); this.eyeRedSlider.setHorizontal(true); this.eyeRedSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setEyeColor(); } }); this.eyeGreenSlider = new Slider(); this.eyeGreenSlider.setBounds(0, 100, 250, 30); this.eyeGreenSlider.setFgColor(new Color(50,255,50,255)); this.eyeGreenSlider.setScrollMax(255); this.eyeGreenSlider.setScrollValue(255); this.eyeGreenSlider.setHorizontal(true); this.eyeGreenSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setEyeColor(); } }); this.eyeBlueSlider = new Slider(); this.eyeBlueSlider.setBounds(0, 150, 250, 30); this.eyeBlueSlider.setFgColor(new Color(50,50,255,255)); this.eyeBlueSlider.setScrollMax(255); this.eyeBlueSlider.setScrollValue(255); this.eyeBlueSlider.setHorizontal(true); this.eyeBlueSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setEyeColor(); } }); this.maneRedSlider = new Slider(); this.maneRedSlider.setBounds(0, 50, 250, 30); this.maneRedSlider.setFgColor(new Color(255,50,50,255)); this.maneRedSlider.setScrollMax(255); this.maneRedSlider.setScrollValue(255); this.maneRedSlider.setHorizontal(true); this.maneRedSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setManeColor(); } }); this.maneGreenSlider = new Slider(); this.maneGreenSlider.setBounds(0, 100, 250, 30); this.maneGreenSlider.setFgColor(new Color(50,255,50,255)); this.maneGreenSlider.setScrollMax(255); this.maneGreenSlider.setScrollValue(255); this.maneGreenSlider.setHorizontal(true); this.maneGreenSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setManeColor(); } }); this.maneBlueSlider = new Slider(); this.maneBlueSlider.setBounds(0, 150, 250, 30); this.maneBlueSlider.setFgColor(new Color(50,50,255,255)); this.maneBlueSlider.setScrollMax(255); this.maneBlueSlider.setScrollValue(255); this.maneBlueSlider.setHorizontal(true); this.maneBlueSlider.addScrollListener(new IEventListener<ScrollEventArgs>() { @Override public void onEvent(Object sender, ScrollEventArgs e) { setManeColor(); } }); this.bodyLabel = new Label(); this.bodyLabel.setFgColor(Color.White); this.bodyLabel.setBounds(0, 0, 250, 30); this.bodyLabel.setText("Body"); this.bodyLabel.setBgColor(Color.Transparent); this.eyeLabel = new Label(); this.eyeLabel.setFgColor(Color.White); this.eyeLabel.setBounds(0, 0, 250, 30); this.eyeLabel.setText("Eyes"); this.eyeLabel.setBgColor(Color.Transparent); this.maneLabel = new Label(); this.maneLabel.setFgColor(Color.White); this.maneLabel.setBounds(0, 0, 250, 30); this.maneLabel.setText("Mane"); this.maneLabel.setBgColor(Color.Transparent); this.nameLabel = new Label(); this.nameLabel.setFgColor(Color.White); this.nameLabel.setBounds(0, 0, 250, 30); this.nameLabel.setText("Name"); this.nameLabel.setBgColor(Color.Transparent); this.button = new Button(); this.button.setText("Done!"); this.button.setBounds(250,710,200,50); super.addGuiControl(button, new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height), new Vector2(this.ScreenManager.getViewport().Width - 250,this.ScreenManager.getViewport().Height-200), new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height)); LookAndFeel feel = contentManager.load(this.lookAndFeelPath, LookAndFeel.class); feel.setDefaultFont(contentManager.loadFont("Monofonto24.xml")); ShaderEffect dissabledEffect = contentManager.loadShaderEffect("GrayScale.effect"); context = new GUIRenderingContext(this.ScreenManager.getSpriteBatch(), feel, dissabledEffect); this.button.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { savePlayerCharacteristics(); goBack(); } }); this.button2 = new Button(); this.button2.setText("Back"); this.button2.setBounds(250,710,200,50); super.addGuiControl(button2, new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height), new Vector2(this.ScreenManager.getViewport().Width - 250,this.ScreenManager.getViewport().Height-100), new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height)); feel.setDefaultFont(contentManager.loadFont("Monofonto24.xml")); context = new GUIRenderingContext(this.ScreenManager.getSpriteBatch(), feel, dissabledEffect); this.button2.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { goBack(); } }); this.button3 = new Button(); this.button3.setText("Randomize"); this.button3.setBounds(250,710,200,50); super.addGuiControl(button3, new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height), new Vector2(this.ScreenManager.getViewport().Width - 250,this.ScreenManager.getViewport().Height-300), new Vector2(this.ScreenManager.getViewport().Width - 250, this.ScreenManager.getViewport().Height)); feel.setDefaultFont(contentManager.loadFont("Monofonto24.xml")); context = new GUIRenderingContext(this.ScreenManager.getSpriteBatch(), feel, dissabledEffect); this.button3.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { randomizeAttributes(); } }); this.earthPonyButton = new ToggleButton(); this.earthPonyButton.setBounds(0, 0, 55, 55); this.earthPonyButton.setImage(contentManager.loadTexture("Earthponybuttonimage.png")); this.earthPonyButton.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { changeRaceToEarthpony(); } }); this.pegasusButton = new ToggleButton(); this.pegasusButton.setBounds(55, 0, 55, 55); this.pegasusButton.setImage(contentManager.loadTexture("Pegasusbuttonimage.png")); this.pegasusButton.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { changeRaceToPegasus(); } }); this.unicornButton = new ToggleButton(); this.unicornButton.setBounds(110, 0, 55, 55); this.unicornButton.setImage(contentManager.loadTexture("Unicornbuttonimage.png")); this.unicornButton.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { changeRaceToUnicorn(); } }); this.walkButton = new ToggleButton(); this.walkButton.setBounds(0, 0, 110, 40); this.walkButton.setText("Walk"); this.walkButton.addClicked(new IEventListener<EventArgs>() { @Override public void onEvent(Object sender, EventArgs e) { toggleWalkAnimation(); } }); super.addGuiControl(this.walkButton, new Vector2(0,this.ScreenManager.getViewport().Height), Vector2.add(ponyPosition, new Vector2(70,208)), new Vector2(0,this.ScreenManager.getViewport().Height)); this.racePanel = new Panel(); this.racePanel.setBounds(0, 0, 165, 55); this.racePanel.setBgColor(new Color(0,0,0,0.05f)); this.racePanel.addChild(nameLabel); this.racePanel.addChild(this.earthPonyButton); this.racePanel.addChild(this.pegasusButton); this.racePanel.addChild(this.unicornButton); super.addGuiControl(this.racePanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(50,200), new Vector2(0,this.ScreenManager.getViewport().Height)); this.namePanel = new Panel(); this.namePanel.setBounds(0, 0, 250, 100); this.namePanel.setBgColor(new Color(0,0,0,0.05f)); this.namePanel.addChild(nameLabel); this.namePanel.addChild(this.nameField); super.addGuiControl(this.namePanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(100,50), new Vector2(0,this.ScreenManager.getViewport().Height)); this.bodyPanel = new Panel(); this.bodyPanel.setBounds(0, 0, 250, 500); this.bodyPanel.setBgColor(new Color(0,0,0,0.05f)); this.bodyPanel.addChild(bodyLabel); this.bodyPanel.addChild(this.bodyRedSlider); this.bodyPanel.addChild(this.bodyGreenSlider); this.bodyPanel.addChild(this.bodyBlueSlider); this.bodyPanel.addChild(this.markComboBox); super.addGuiControl(this.bodyPanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(50,300), new Vector2(0,this.ScreenManager.getViewport().Height)); this.eyePanel = new Panel(); this.eyePanel.setBounds(0, 0, 250, 500); this.eyePanel.setBgColor(new Color(0,0,0,0.05f)); this.eyePanel.addChild(eyeLabel); this.eyePanel.addChild(this.eyeComboBox); this.eyePanel.addChild(this.eyeRedSlider); this.eyePanel.addChild(this.eyeGreenSlider); this.eyePanel.addChild(this.eyeBlueSlider); super.addGuiControl(this.eyePanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(350,300), new Vector2(0,this.ScreenManager.getViewport().Height)); this.manePanel = new Panel(); this.manePanel.setBounds(0, 0, 250, 500); this.manePanel.setBgColor(new Color(0,0,0,0.05f)); this.manePanel.addChild(maneLabel); this.manePanel.addChild(this.maneComboBox); this.manePanel.addChild(this.maneRedSlider); this.manePanel.addChild(this.maneGreenSlider); this.manePanel.addChild(this.maneBlueSlider); super.addGuiControl(this.manePanel, new Vector2(0,this.ScreenManager.getViewport().Height), new Vector2(650,300), new Vector2(0,this.ScreenManager.getViewport().Height)); setBodyColor(); setEyeColor(); setManeColor(); changeRaceToEarthpony(); this.earthPonyButton.setToggled(true); }
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/objectmanager/ContainerAdapter.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/objectmanager/ContainerAdapter.java index a82c74465..a9a33ddc4 100644 --- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/objectmanager/ContainerAdapter.java +++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/objectmanager/ContainerAdapter.java @@ -1,769 +1,773 @@ /* * ContainerAdapter.java * * Version: $Revision: 1.6 $ * * Date: $Date: 2006/05/02 01:24:11 $ * * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * 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 * HOLDERS 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.dspace.app.xmlui.objectmanager; import org.dspace.app.xmlui.wing.AttributeMap; import org.dspace.app.xmlui.wing.WingException; import org.dspace.authorize.AuthorizeException; import org.dspace.browse.ItemCounter; import org.dspace.browse.ItemCountException; import org.dspace.content.Bitstream; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DSpaceObject; import org.dspace.content.crosswalk.CrosswalkException; import org.dspace.content.crosswalk.DisseminationCrosswalk; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.uri.IdentifierService; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.SAXOutputter; import org.xml.sax.SAXException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.sql.SQLException; /** * This is an adapter which translates DSpace containers * (communities & collections) into METS documents. This adapter follows * the DSpace METS profile however that profile does not define how a * community or collection should be described, but we make the obvious * decisions to deviate when nessasary from the profile. * * The METS document consists of three parts: descriptive metadata section, * file section, and a structural map. The descriptive metadata sections holds * metadata about the item being adapted using DSpace crosswalks. This is the * same way the item adapter works. * * However the file section and structural map are a bit different. In these * casses the the only files listed is the one logo that may be attached to * a community or collection. * * @author Scott Phillips */ public class ContainerAdapter extends AbstractAdapter { /** The community or collection this adapter represents. */ private DSpaceObject dso; /** A space seperated list of descriptive metadata sections */ private StringBuffer dmdSecIDS; /** Current DSpace context **/ private Context dspaceContext; /** * Construct a new CommunityCollectionMETSAdapter. * * @param dso * A DSpace Community or Collection to adapt. * @param contextPath * The contextPath of this webapplication. */ public ContainerAdapter(Context context, DSpaceObject dso,String contextPath) { super(contextPath); this.dso = dso; this.dspaceContext = context; } /** Return the container, community or collection, object */ public DSpaceObject getContainer() { return this.dso; } /** * * * * Required abstract methods * * * */ /** * Return the URL of this community/collection in the interface */ protected String getMETSOBJID() { return IdentifierService.getURL(dso).toString(); } /** * @return Return the URL for editing this item */ protected String getMETSOBJEDIT() { return null; } /** * Use the handle as the id for this METS document */ protected String getMETSID() { return IdentifierService.getCanonicalForm(dso); } /** * Return the profile to use for communities and collections. * */ protected String getMETSProfile() throws WingException { return "DSPACE METS SIP Profile 1.0"; } /** * Return a friendly label for the METS document to say we are a community * or collection. */ protected String getMETSLabel() { if (dso instanceof Community) return "DSpace Community"; else return "DSpace Collection"; } /** * Return a unique id for the given bitstream */ protected String getFileID(Bitstream bitstream) { return "file_" + bitstream.getID(); } /** * Return a group id for the given bitstream */ protected String getGroupFileID(Bitstream bitstream) { return "group_file_" + bitstream.getID(); } /** * * * * METS structural methods * * * */ /** * Render the METS descriptive section. This will create a new metadata * section for each crosswalk configured. * * Example: * <dmdSec> * <mdWrap MDTYPE="MODS"> * <xmlData> * ... content from the crosswalk ... * </xmlDate> * </mdWrap> * </dmdSec */ protected void renderDescriptiveSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException { AttributeMap attributes; String groupID = getGenericID("group_dmd_"); dmdSecIDS = new StringBuffer(); // Add DIM descriptive metadata if it was requested or if no metadata types // were specified. Further more since this is the default type we also use a // faster rendering method that the crosswalk API. if(dmdTypes.size() == 0 || dmdTypes.contains("DIM")) { // Metadata element's ID String dmdID = getGenericID("dmd_"); // Keep track of all descriptive sections dmdSecIDS.append(dmdID); // //////////////////////////////// // Start a new dmdSec for each crosswalk. attributes = new AttributeMap(); attributes.put("ID", dmdID); attributes.put("GROUPID", groupID); startElement(METS,"dmdSec",attributes); // //////////////////////////////// // Start metadata wrapper attributes = new AttributeMap(); attributes.put("MDTYPE", "OTHER"); attributes.put("OTHERMDTYPE", "DIM"); startElement(METS,"mdWrap",attributes); // //////////////////////////////// // Start the xml data startElement(METS,"xmlData"); // /////////////////////////////// // Start the DIM element attributes = new AttributeMap(); attributes.put("dspaceType", Constants.typeText[dso.getType()]); startElement(DIM,"dim",attributes); // Add each field for this collection if (dso.getType() == Constants.COLLECTION) { Collection collection = (Collection) dso; String description = collection.getMetadata("introductory_text"); String description_abstract = collection.getMetadata("short_description"); String description_table = collection.getMetadata("side_bar_text"); // FIXME: Oh, so broken. String identifier_uri = IdentifierService.getURL(collection).toString(); String provenance = collection.getMetadata("provenance_description"); String rights = collection.getMetadata("copyright_text"); String rights_license = collection.getMetadata("license"); String title = collection.getMetadata("name"); createField("dc","description",null,null,description); createField("dc","description","abstract",null,description_abstract); createField("dc","description","tableofcontents",null,description_table); createField("dc","identifier","uri",null,identifier_uri); createField("dc","provenance",null,null,provenance); createField("dc","rights",null,null,rights); createField("dc","rights","license",null,rights_license); createField("dc","title",null,null,title); boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache"); //To improve scalability, XMLUI only adds item counts if they are cached if (useCache) { try { //try to determine Collection size (i.e. # of items) int size = new ItemCounter(this.dspaceContext).getCount(collection); createField("dc","format","extent",null, String.valueOf(size)); } catch(ItemCountException e) { - throw new IOException("Could not obtain Collection item-count: ", e); + IOException ioe = new IOException("Could not obtain Collection item-count"); + ioe.initCause(e); + throw ioe; } } } else if (dso.getType() == Constants.COMMUNITY) { Community community = (Community) dso; String description = community.getMetadata("introductory_text"); String description_abstract = community.getMetadata("short_description"); String description_table = community.getMetadata("side_bar_text"); // FIXME: Oh, so broken. String identifier_uri = IdentifierService.getURL(community).toString(); String rights = community.getMetadata("copyright_text"); String title = community.getMetadata("name"); createField("dc","description",null,null,description); createField("dc","description","abstract",null,description_abstract); createField("dc","description","tableofcontents",null,description_table); createField("dc","identifier","uri",null,identifier_uri); createField("dc","rights",null,null,rights); createField("dc","title",null,null,title); boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache"); //To improve scalability, XMLUI only adds item counts if they are cached if (useCache) { try { //try to determine Community size (i.e. # of items) int size = new ItemCounter(this.dspaceContext).getCount(community); createField("dc","format","extent",null, String.valueOf(size)); } catch(ItemCountException e) { - throw new IOException("Could not obtain Community item-count: ", e); + IOException ioe = new IOException("Could not obtain Collection item-count"); + ioe.initCause(e); + throw ioe; } } } // /////////////////////////////// // End the DIM element endElement(DIM,"dim"); // //////////////////////////////// // End elements endElement(METS,"xmlData"); endElement(METS,"mdWrap"); endElement(METS, "dmdSec"); } for (String dmdType : dmdTypes) { // If DIM was requested then it was generated above without using // the crosswalk API. So we can skip this one. if ("DIM".equals(dmdType)) continue; DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(dmdType); if (crosswalk == null) continue; String dmdID = getGenericID("dmd_"); // Add our id to the list. dmdSecIDS.append(" " + dmdID); // //////////////////////////////// // Start a new dmdSec for each crosswalk. attributes = new AttributeMap(); attributes.put("ID", dmdID); attributes.put("GROUPID", groupID); startElement(METS,"dmdSec",attributes); // //////////////////////////////// // Start metadata wrapper attributes = new AttributeMap(); if (isDefinedMETStype(dmdType)) { attributes.put("MDTYPE", dmdType); } else { attributes.put("MDTYPE", "OTHER"); attributes.put("OTHERMDTYPE", dmdType); } startElement(METS,"mdWrap",attributes); // //////////////////////////////// // Start the xml data startElement(METS,"xmlData"); // /////////////////////////////// // Send the actual XML content try { Element dissemination = crosswalk.disseminateElement(dso); SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces); // Allow the basics for XML filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings(); SAXOutputter outputter = new SAXOutputter(); outputter.setContentHandler(filter); outputter.setLexicalHandler(filter); outputter.output(dissemination); } catch (JDOMException jdome) { throw new WingException(jdome); } catch (AuthorizeException ae) { // just ignore the authorize exception and continue on with //out parsing the xml document. } // //////////////////////////////// // End elements endElement(METS,"xmlData"); endElement(METS,"mdWrap"); endElement(METS, "dmdSec"); // Record keeping if (dmdSecIDS == null) { dmdSecIDS = new StringBuffer(dmdID); } else { dmdSecIDS.append(" " + dmdID); } } } /** * Render the METS file section. If a logo is present for this * container then that single bitstream is listed in the * file section. * * Example: * <fileSec> * <fileGrp USE="LOGO"> * <file ... > * <fLocate ... > * </file> * </fileGrp> * </fileSec> */ protected void renderFileSection() throws SAXException { AttributeMap attributes; // Get the Community or Collection logo. Bitstream logo = getLogo(); if (logo != null) { // //////////////////////////////// // Start the file section startElement(METS,"fileSec"); // //////////////////////////////// // Start a new fileGrp for the logo. attributes = new AttributeMap(); attributes.put("USE", "LOGO"); startElement(METS,"fileGrp",attributes); // //////////////////////////////// // Add the actual file element String fileID = getFileID(logo); String groupID = getGroupFileID(logo); renderFile(null, logo, fileID, groupID); // //////////////////////////////// // End th file group and file section endElement(METS,"fileGrp"); endElement(METS,"fileSec"); } } /** * Render the container's structural map. This includes a refrence * to the container's logo, if available, otherwise it is an empty * division that just states it is a DSpace community or Collection. * * Examlpe: * <structMap TYPE="LOGICAL" LABEL="DSpace"> * <div TYPE="DSpace Collection" DMDID="space seperated list of ids"> * <fptr FILEID="logo id"/> * </div> * </structMap> */ protected void renderStructureMap() throws SQLException, SAXException { AttributeMap attributes; // /////////////////////// // Start a new structure map attributes = new AttributeMap(); attributes.put("TYPE", "LOGICAL"); attributes.put("LABEL", "DSpace"); startElement(METS,"structMap",attributes); // //////////////////////////////// // Start the special first division attributes = new AttributeMap(); attributes.put("TYPE", getMETSLabel()); // add references to the Descriptive metadata if (dmdSecIDS != null) attributes.put("DMDID", dmdSecIDS.toString()); startElement(METS,"div",attributes); // add a fptr pointer to the logo. Bitstream logo = getLogo(); if (logo != null) { // //////////////////////////////// // Add a refrence to the logo as the primary bitstream. attributes = new AttributeMap(); attributes.put("FILEID",getFileID(logo)); startElement(METS,"fptr",attributes); endElement(METS,"fptr"); // /////////////////////////////////////////////// // Add a div for the publicaly viewable bitstreams (i.e. the logo) attributes = new AttributeMap(); attributes.put("ID", getGenericID("div_")); attributes.put("TYPE", "DSpace Content Bitstream"); startElement(METS,"div",attributes); // //////////////////////////////// // Add a refrence to the logo as the primary bitstream. attributes = new AttributeMap(); attributes.put("FILEID",getFileID(logo)); startElement(METS,"fptr",attributes); endElement(METS,"fptr"); // ////////////////////////// // End the logo division endElement(METS,"div"); } // //////////////////////////////// // End the special first division endElement(METS,"div"); // /////////////////////// // End the structure map endElement(METS,"structMap"); } /** * * * * Private helpfull methods * * * */ /** * Return the logo bitstream associated with this community or collection. * If there is no logo then null is returned. */ private Bitstream getLogo() { if (dso instanceof Community) { Community community = (Community) dso; return community.getLogo(); } else if (dso instanceof Collection) { Collection collection = (Collection) dso; return collection.getLogo(); } return null; } /** * Count how many occurance there is of the given * character in the given string. * * @param string The string value to be counted. * @param character the character to count in the string. */ private int countOccurances(String string, char character) { if (string == null || string.length() == 0) return 0; int fromIndex = -1; int count = 0; while (true) { fromIndex = string.indexOf('>', fromIndex+1); if (fromIndex == -1) break; count++; } return count; } /** * Check if the given character sequence is located in the given * string at the specified index. If it is then return true, otherwise false. * * @param string The string to test against * @param index The location within the string * @param characters The character sequence to look for. * @return true if the character sequence was found, otherwise false. */ private boolean substringCompare(String string, int index, char ... characters) { // Is the string long enough? if (string.length() <= index + characters.length) return false; // Do all the characters match? for (char character : characters) { if (string.charAt(index) != character) return false; index++; } return false; } /** * Create a new DIM field element with the given attributes. * * @param schema The schema the DIM field belongs too. * @param element The element the DIM field belongs too. * @param qualifier The qualifier the DIM field belongs too. * @param language The language the DIM field belongs too. * @param value The value of the DIM field. * @return A new DIM field element * @throws SAXException */ private void createField(String schema, String element, String qualifier, String language, String value) throws SAXException { // /////////////////////////////// // Field element for each metadata field. AttributeMap attributes = new AttributeMap(); attributes.put("mdschema",schema); attributes.put("element", element); if (qualifier != null) attributes.put("qualifier", qualifier); if (language != null) attributes.put("language", language); startElement(DIM,"field",attributes); // Only try and add the metadata's value, but only if it is non null. if (value != null) { // First, preform a queck check to see if the value may be XML. int countOpen = countOccurances(value,'<'); int countClose = countOccurances(value, '>'); // If it passed the quick test, then try and parse the value. Element xmlDocument = null; if (countOpen > 0 && countOpen == countClose) { // This may be XML, First try and remove any bad entity refrences. int amp = -1; while ((amp = value.indexOf('&', amp+1)) > -1) { // Is it an xml entity named by number? if (substringCompare(value,amp+1,'#')) continue; // &amp; if (substringCompare(value,amp+1,'a','m','p',';')) continue; // &apos; if (substringCompare(value,amp+1,'a','p','o','s',';')) continue; // &quot; if (substringCompare(value,amp+1,'q','u','o','t',';')) continue; // &lt; if (substringCompare(value,amp+1,'l','t',';')) continue; // &gt; if (substringCompare(value,amp+1,'g','t',';')) continue; // Replace the ampersand with an XML entity. value = value.substring(0,amp) + "&amp;" + value.substring(amp+1); } // Second try and parse the XML into a mini-dom try { // Wrap the value inside a root element (which will be trimed out // by the SAX filter and set the default namespace to XHTML. String xml = "<fragment xmlns=\"http://www.w3.org/1999/xhtml\">"+value+"</fragment>"; ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes()); SAXBuilder builder = new SAXBuilder(); Document document = builder.build(inputStream); xmlDocument = document.getRootElement(); } catch (Exception e) { // ignore any errors we get, and just add the string literaly. } } // Third, If we have xml, attempt to serialize the dom. if (xmlDocument != null) { SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces); // Allow the basics for XML filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings(); // Special option, only allow elements below the second level to pass through. This // will trim out the METS declaration and only leave the actual METS parts to be // included. filter.allowElements(1); SAXOutputter outputter = new SAXOutputter(); outputter.setContentHandler(filter); outputter.setLexicalHandler(filter); try { outputter.output(xmlDocument); } catch (JDOMException jdome) { // serialization failed so let's just fallback sending the plain characters. sendCharacters(value); } } else { // We don't have XML, so just send the plain old characters. sendCharacters(value); } } // ////////////////////////////// // Close out field endElement(DIM,"field"); } }
false
true
protected void renderDescriptiveSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException { AttributeMap attributes; String groupID = getGenericID("group_dmd_"); dmdSecIDS = new StringBuffer(); // Add DIM descriptive metadata if it was requested or if no metadata types // were specified. Further more since this is the default type we also use a // faster rendering method that the crosswalk API. if(dmdTypes.size() == 0 || dmdTypes.contains("DIM")) { // Metadata element's ID String dmdID = getGenericID("dmd_"); // Keep track of all descriptive sections dmdSecIDS.append(dmdID); // //////////////////////////////// // Start a new dmdSec for each crosswalk. attributes = new AttributeMap(); attributes.put("ID", dmdID); attributes.put("GROUPID", groupID); startElement(METS,"dmdSec",attributes); // //////////////////////////////// // Start metadata wrapper attributes = new AttributeMap(); attributes.put("MDTYPE", "OTHER"); attributes.put("OTHERMDTYPE", "DIM"); startElement(METS,"mdWrap",attributes); // //////////////////////////////// // Start the xml data startElement(METS,"xmlData"); // /////////////////////////////// // Start the DIM element attributes = new AttributeMap(); attributes.put("dspaceType", Constants.typeText[dso.getType()]); startElement(DIM,"dim",attributes); // Add each field for this collection if (dso.getType() == Constants.COLLECTION) { Collection collection = (Collection) dso; String description = collection.getMetadata("introductory_text"); String description_abstract = collection.getMetadata("short_description"); String description_table = collection.getMetadata("side_bar_text"); // FIXME: Oh, so broken. String identifier_uri = IdentifierService.getURL(collection).toString(); String provenance = collection.getMetadata("provenance_description"); String rights = collection.getMetadata("copyright_text"); String rights_license = collection.getMetadata("license"); String title = collection.getMetadata("name"); createField("dc","description",null,null,description); createField("dc","description","abstract",null,description_abstract); createField("dc","description","tableofcontents",null,description_table); createField("dc","identifier","uri",null,identifier_uri); createField("dc","provenance",null,null,provenance); createField("dc","rights",null,null,rights); createField("dc","rights","license",null,rights_license); createField("dc","title",null,null,title); boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache"); //To improve scalability, XMLUI only adds item counts if they are cached if (useCache) { try { //try to determine Collection size (i.e. # of items) int size = new ItemCounter(this.dspaceContext).getCount(collection); createField("dc","format","extent",null, String.valueOf(size)); } catch(ItemCountException e) { throw new IOException("Could not obtain Collection item-count: ", e); } } } else if (dso.getType() == Constants.COMMUNITY) { Community community = (Community) dso; String description = community.getMetadata("introductory_text"); String description_abstract = community.getMetadata("short_description"); String description_table = community.getMetadata("side_bar_text"); // FIXME: Oh, so broken. String identifier_uri = IdentifierService.getURL(community).toString(); String rights = community.getMetadata("copyright_text"); String title = community.getMetadata("name"); createField("dc","description",null,null,description); createField("dc","description","abstract",null,description_abstract); createField("dc","description","tableofcontents",null,description_table); createField("dc","identifier","uri",null,identifier_uri); createField("dc","rights",null,null,rights); createField("dc","title",null,null,title); boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache"); //To improve scalability, XMLUI only adds item counts if they are cached if (useCache) { try { //try to determine Community size (i.e. # of items) int size = new ItemCounter(this.dspaceContext).getCount(community); createField("dc","format","extent",null, String.valueOf(size)); } catch(ItemCountException e) { throw new IOException("Could not obtain Community item-count: ", e); } } } // /////////////////////////////// // End the DIM element endElement(DIM,"dim"); // //////////////////////////////// // End elements endElement(METS,"xmlData"); endElement(METS,"mdWrap"); endElement(METS, "dmdSec"); } for (String dmdType : dmdTypes) { // If DIM was requested then it was generated above without using // the crosswalk API. So we can skip this one. if ("DIM".equals(dmdType)) continue; DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(dmdType); if (crosswalk == null) continue; String dmdID = getGenericID("dmd_"); // Add our id to the list. dmdSecIDS.append(" " + dmdID); // //////////////////////////////// // Start a new dmdSec for each crosswalk. attributes = new AttributeMap(); attributes.put("ID", dmdID); attributes.put("GROUPID", groupID); startElement(METS,"dmdSec",attributes); // //////////////////////////////// // Start metadata wrapper attributes = new AttributeMap(); if (isDefinedMETStype(dmdType)) { attributes.put("MDTYPE", dmdType); } else { attributes.put("MDTYPE", "OTHER"); attributes.put("OTHERMDTYPE", dmdType); } startElement(METS,"mdWrap",attributes); // //////////////////////////////// // Start the xml data startElement(METS,"xmlData"); // /////////////////////////////// // Send the actual XML content try { Element dissemination = crosswalk.disseminateElement(dso); SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces); // Allow the basics for XML filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings(); SAXOutputter outputter = new SAXOutputter(); outputter.setContentHandler(filter); outputter.setLexicalHandler(filter); outputter.output(dissemination); } catch (JDOMException jdome) { throw new WingException(jdome); } catch (AuthorizeException ae) { // just ignore the authorize exception and continue on with //out parsing the xml document. } // //////////////////////////////// // End elements endElement(METS,"xmlData"); endElement(METS,"mdWrap"); endElement(METS, "dmdSec"); // Record keeping if (dmdSecIDS == null) { dmdSecIDS = new StringBuffer(dmdID); } else { dmdSecIDS.append(" " + dmdID); } } }
protected void renderDescriptiveSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException { AttributeMap attributes; String groupID = getGenericID("group_dmd_"); dmdSecIDS = new StringBuffer(); // Add DIM descriptive metadata if it was requested or if no metadata types // were specified. Further more since this is the default type we also use a // faster rendering method that the crosswalk API. if(dmdTypes.size() == 0 || dmdTypes.contains("DIM")) { // Metadata element's ID String dmdID = getGenericID("dmd_"); // Keep track of all descriptive sections dmdSecIDS.append(dmdID); // //////////////////////////////// // Start a new dmdSec for each crosswalk. attributes = new AttributeMap(); attributes.put("ID", dmdID); attributes.put("GROUPID", groupID); startElement(METS,"dmdSec",attributes); // //////////////////////////////// // Start metadata wrapper attributes = new AttributeMap(); attributes.put("MDTYPE", "OTHER"); attributes.put("OTHERMDTYPE", "DIM"); startElement(METS,"mdWrap",attributes); // //////////////////////////////// // Start the xml data startElement(METS,"xmlData"); // /////////////////////////////// // Start the DIM element attributes = new AttributeMap(); attributes.put("dspaceType", Constants.typeText[dso.getType()]); startElement(DIM,"dim",attributes); // Add each field for this collection if (dso.getType() == Constants.COLLECTION) { Collection collection = (Collection) dso; String description = collection.getMetadata("introductory_text"); String description_abstract = collection.getMetadata("short_description"); String description_table = collection.getMetadata("side_bar_text"); // FIXME: Oh, so broken. String identifier_uri = IdentifierService.getURL(collection).toString(); String provenance = collection.getMetadata("provenance_description"); String rights = collection.getMetadata("copyright_text"); String rights_license = collection.getMetadata("license"); String title = collection.getMetadata("name"); createField("dc","description",null,null,description); createField("dc","description","abstract",null,description_abstract); createField("dc","description","tableofcontents",null,description_table); createField("dc","identifier","uri",null,identifier_uri); createField("dc","provenance",null,null,provenance); createField("dc","rights",null,null,rights); createField("dc","rights","license",null,rights_license); createField("dc","title",null,null,title); boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache"); //To improve scalability, XMLUI only adds item counts if they are cached if (useCache) { try { //try to determine Collection size (i.e. # of items) int size = new ItemCounter(this.dspaceContext).getCount(collection); createField("dc","format","extent",null, String.valueOf(size)); } catch(ItemCountException e) { IOException ioe = new IOException("Could not obtain Collection item-count"); ioe.initCause(e); throw ioe; } } } else if (dso.getType() == Constants.COMMUNITY) { Community community = (Community) dso; String description = community.getMetadata("introductory_text"); String description_abstract = community.getMetadata("short_description"); String description_table = community.getMetadata("side_bar_text"); // FIXME: Oh, so broken. String identifier_uri = IdentifierService.getURL(community).toString(); String rights = community.getMetadata("copyright_text"); String title = community.getMetadata("name"); createField("dc","description",null,null,description); createField("dc","description","abstract",null,description_abstract); createField("dc","description","tableofcontents",null,description_table); createField("dc","identifier","uri",null,identifier_uri); createField("dc","rights",null,null,rights); createField("dc","title",null,null,title); boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache"); //To improve scalability, XMLUI only adds item counts if they are cached if (useCache) { try { //try to determine Community size (i.e. # of items) int size = new ItemCounter(this.dspaceContext).getCount(community); createField("dc","format","extent",null, String.valueOf(size)); } catch(ItemCountException e) { IOException ioe = new IOException("Could not obtain Collection item-count"); ioe.initCause(e); throw ioe; } } } // /////////////////////////////// // End the DIM element endElement(DIM,"dim"); // //////////////////////////////// // End elements endElement(METS,"xmlData"); endElement(METS,"mdWrap"); endElement(METS, "dmdSec"); } for (String dmdType : dmdTypes) { // If DIM was requested then it was generated above without using // the crosswalk API. So we can skip this one. if ("DIM".equals(dmdType)) continue; DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(dmdType); if (crosswalk == null) continue; String dmdID = getGenericID("dmd_"); // Add our id to the list. dmdSecIDS.append(" " + dmdID); // //////////////////////////////// // Start a new dmdSec for each crosswalk. attributes = new AttributeMap(); attributes.put("ID", dmdID); attributes.put("GROUPID", groupID); startElement(METS,"dmdSec",attributes); // //////////////////////////////// // Start metadata wrapper attributes = new AttributeMap(); if (isDefinedMETStype(dmdType)) { attributes.put("MDTYPE", dmdType); } else { attributes.put("MDTYPE", "OTHER"); attributes.put("OTHERMDTYPE", dmdType); } startElement(METS,"mdWrap",attributes); // //////////////////////////////// // Start the xml data startElement(METS,"xmlData"); // /////////////////////////////// // Send the actual XML content try { Element dissemination = crosswalk.disseminateElement(dso); SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces); // Allow the basics for XML filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings(); SAXOutputter outputter = new SAXOutputter(); outputter.setContentHandler(filter); outputter.setLexicalHandler(filter); outputter.output(dissemination); } catch (JDOMException jdome) { throw new WingException(jdome); } catch (AuthorizeException ae) { // just ignore the authorize exception and continue on with //out parsing the xml document. } // //////////////////////////////// // End elements endElement(METS,"xmlData"); endElement(METS,"mdWrap"); endElement(METS, "dmdSec"); // Record keeping if (dmdSecIDS == null) { dmdSecIDS = new StringBuffer(dmdID); } else { dmdSecIDS.append(" " + dmdID); } } }
diff --git a/src/controller/SpikesController.java b/src/controller/SpikesController.java index d7dfe64..97ecb69 100644 --- a/src/controller/SpikesController.java +++ b/src/controller/SpikesController.java @@ -1,69 +1,68 @@ package controller; import org.jbox2d.callbacks.ContactImpulse; import org.jbox2d.callbacks.ContactListener; import org.jbox2d.collision.Manifold; import org.jbox2d.dynamics.Fixture; import org.jbox2d.dynamics.contacts.Contact; import model.Spikes; import view.CharacterView; import view.SpikesView; public class SpikesController implements ContactListener { private Spikes spikes; private SpikesView spikesView; private InGameController inGameController; public SpikesController(InGameController inGameController, int index){ this.inGameController = inGameController; this.spikes = new Spikes(inGameController.getBlockMapController().getSpikesMap().getBlockList().get(index).getPosX(), inGameController.getBlockMapController().getSpikesMap().getBlockList().get(index).getPosY()); this.spikesView = new SpikesView(this.spikes, inGameController.getWorldController().getWorldView()); inGameController.getWorldController().getWorldView().getjBox2DWorld().setContactListener(this); } public Spikes getSpikes() { return spikes; } public SpikesView getSpikesView() { return spikesView; } @Override public void beginContact(Contact contact) { Fixture fixtA = contact.getFixtureA(); Fixture fixtB = contact.getFixtureB(); if(fixtA.getUserData() != null && fixtB.getUserData() != null) { if(fixtA.getUserData().equals("spikes") && fixtB.getUserData().equals("player") && inGameController.getCharacterController().getCharacter().getTimeSinceHit() > 1) { this.inGameController.getCharacterController().getCharacterView().animateBlinking(); this.inGameController.getCharacterController().getCharacter().setOnSpikes(true); - this.inGameController.getCharacterController().getCharacter().setTimeSinceHit(0); } } } @Override public void endContact(Contact contact) { Fixture fixtA = contact.getFixtureA(); Fixture fixtB = contact.getFixtureB(); if(fixtA.getUserData() != null && fixtB.getUserData() != null) { if(fixtA.getUserData().equals("spikes") && fixtB.getUserData().equals("player")) { inGameController.getCharacterController().getCharacterView().animateWalking(); this.inGameController.getCharacterController().getCharacter().setOnSpikes(false); } } } @Override public void postSolve(Contact contact, ContactImpulse impulse) {} @Override public void preSolve(Contact contact, Manifold oldManifold) {} }
true
true
public void beginContact(Contact contact) { Fixture fixtA = contact.getFixtureA(); Fixture fixtB = contact.getFixtureB(); if(fixtA.getUserData() != null && fixtB.getUserData() != null) { if(fixtA.getUserData().equals("spikes") && fixtB.getUserData().equals("player") && inGameController.getCharacterController().getCharacter().getTimeSinceHit() > 1) { this.inGameController.getCharacterController().getCharacterView().animateBlinking(); this.inGameController.getCharacterController().getCharacter().setOnSpikes(true); this.inGameController.getCharacterController().getCharacter().setTimeSinceHit(0); } } }
public void beginContact(Contact contact) { Fixture fixtA = contact.getFixtureA(); Fixture fixtB = contact.getFixtureB(); if(fixtA.getUserData() != null && fixtB.getUserData() != null) { if(fixtA.getUserData().equals("spikes") && fixtB.getUserData().equals("player") && inGameController.getCharacterController().getCharacter().getTimeSinceHit() > 1) { this.inGameController.getCharacterController().getCharacterView().animateBlinking(); this.inGameController.getCharacterController().getCharacter().setOnSpikes(true); } } }
diff --git a/appjar/src/main/java/com/google/gerrit/client/data/PatchSetDetail.java b/appjar/src/main/java/com/google/gerrit/client/data/PatchSetDetail.java index 9ca347315..53992163d 100644 --- a/appjar/src/main/java/com/google/gerrit/client/data/PatchSetDetail.java +++ b/appjar/src/main/java/com/google/gerrit/client/data/PatchSetDetail.java @@ -1,73 +1,73 @@ // Copyright 2008 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.gerrit.client.data; import com.google.gerrit.client.reviewdb.Account; import com.google.gerrit.client.reviewdb.Patch; import com.google.gerrit.client.reviewdb.PatchLineComment; import com.google.gerrit.client.reviewdb.PatchSet; import com.google.gerrit.client.reviewdb.PatchSetInfo; import com.google.gerrit.client.reviewdb.ReviewDb; import com.google.gerrit.client.rpc.Common; import com.google.gwtorm.client.OrmException; import java.util.List; import java.util.Map; public class PatchSetDetail { protected PatchSet patchSet; protected PatchSetInfo info; protected List<Patch> patches; public PatchSetDetail() { } public void load(final ReviewDb db, final PatchSet ps) throws OrmException { patchSet = ps; info = db.patchSetInfo().get(patchSet.getId()); patches = db.patches().byPatchSet(patchSet.getId()).toList(); final Account.Id me = Common.getAccountId(); if (me != null) { // If we are signed in, compute the number of draft comments by the - // current user on each of these patch files. This way the can more + // current user on each of these patch files. This way they can more // quickly locate where they have pending drafts, and review them. // final List<PatchLineComment> comments = db.patchComments().draft(ps.getId(), me).toList(); if (!comments.isEmpty()) { final Map<Patch.Key, Patch> byKey = db.patches().toMap(patches); for (final PatchLineComment c : comments) { final Patch p = byKey.get(c.getKey().getParentKey()); if (p != null) { p.setDraftCount(p.getDraftCount() + 1); } } } } } public PatchSet getPatchSet() { return patchSet; } public PatchSetInfo getInfo() { return info; } public List<Patch> getPatches() { return patches; } }
true
true
public void load(final ReviewDb db, final PatchSet ps) throws OrmException { patchSet = ps; info = db.patchSetInfo().get(patchSet.getId()); patches = db.patches().byPatchSet(patchSet.getId()).toList(); final Account.Id me = Common.getAccountId(); if (me != null) { // If we are signed in, compute the number of draft comments by the // current user on each of these patch files. This way the can more // quickly locate where they have pending drafts, and review them. // final List<PatchLineComment> comments = db.patchComments().draft(ps.getId(), me).toList(); if (!comments.isEmpty()) { final Map<Patch.Key, Patch> byKey = db.patches().toMap(patches); for (final PatchLineComment c : comments) { final Patch p = byKey.get(c.getKey().getParentKey()); if (p != null) { p.setDraftCount(p.getDraftCount() + 1); } } } } }
public void load(final ReviewDb db, final PatchSet ps) throws OrmException { patchSet = ps; info = db.patchSetInfo().get(patchSet.getId()); patches = db.patches().byPatchSet(patchSet.getId()).toList(); final Account.Id me = Common.getAccountId(); if (me != null) { // If we are signed in, compute the number of draft comments by the // current user on each of these patch files. This way they can more // quickly locate where they have pending drafts, and review them. // final List<PatchLineComment> comments = db.patchComments().draft(ps.getId(), me).toList(); if (!comments.isEmpty()) { final Map<Patch.Key, Patch> byKey = db.patches().toMap(patches); for (final PatchLineComment c : comments) { final Patch p = byKey.get(c.getKey().getParentKey()); if (p != null) { p.setDraftCount(p.getDraftCount() + 1); } } } } }
diff --git a/motech-server-omod/src/main/java/org/motechproject/server/omod/sdsched/ScheduleMaintServiceImpl.java b/motech-server-omod/src/main/java/org/motechproject/server/omod/sdsched/ScheduleMaintServiceImpl.java index 313c84b5..b46b8c93 100644 --- a/motech-server-omod/src/main/java/org/motechproject/server/omod/sdsched/ScheduleMaintServiceImpl.java +++ b/motech-server-omod/src/main/java/org/motechproject/server/omod/sdsched/ScheduleMaintServiceImpl.java @@ -1,81 +1,82 @@ package org.motechproject.server.omod.sdsched; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implementation of {@link ScheduleMaintService}. * * @author batkinson * */ public class ScheduleMaintServiceImpl implements ScheduleMaintService { private static Log log = LogFactory.getLog(ScheduleMaintServiceImpl.class); public static String RESOURCE_NAME = "_DS_SCHEDULER_UTILS_RESOURCE"; TxSyncManWrapper syncManWrapper; ScheduleAdjuster scheduleAdjuster; public void setSyncManWrapper(TxSyncManWrapper txSyncManWrapper) { this.syncManWrapper = txSyncManWrapper; } public void setScheduleAdjuster(ScheduleAdjuster scheduleAdjuster) { this.scheduleAdjuster = scheduleAdjuster; } /** * Returns the {@link AffectedPatients} object for the current transaction. * * @return the AffectedPatients object for the current tx, or null if * non-existent */ private AffectedPatients getAffectedPatients() { AffectedPatients patients = null; try { patients = (AffectedPatients) syncManWrapper .getResource(RESOURCE_NAME); } catch (ClassCastException e) { log.debug("Cannot cast affected patients", e); + clearAffectedPatients(); } return patients; } public AffectedPatients getAffectedPatients(boolean create) { AffectedPatients patients = getAffectedPatients(); if (patients == null && create) { patients = new AffectedPatients(); syncManWrapper.bindResource(RESOURCE_NAME, patients); } return patients; } public void addAffectedPatient(Integer patientId) { getAffectedPatients(true).getAffectedIds().add(patientId); } public void removeAffectedPatient(Integer patientId) { AffectedPatients patients = getAffectedPatients(); if (patients != null) patients.getAffectedIds().remove(patientId); } public void clearAffectedPatients() { syncManWrapper.unbindResource(RESOURCE_NAME); } public void requestSynch() { if (!syncManWrapper .containsSynchronization(ScheduleMaintSynchronization.class)) { ScheduleMaintSynchronization schedSync = new ScheduleMaintSynchronization(); schedSync.setSchedService(this); syncManWrapper.registerSynchronization(schedSync); } } public void updateSchedule(Integer patientId) { scheduleAdjuster.adjustSchedule(patientId); } }
true
true
private AffectedPatients getAffectedPatients() { AffectedPatients patients = null; try { patients = (AffectedPatients) syncManWrapper .getResource(RESOURCE_NAME); } catch (ClassCastException e) { log.debug("Cannot cast affected patients", e); } return patients; }
private AffectedPatients getAffectedPatients() { AffectedPatients patients = null; try { patients = (AffectedPatients) syncManWrapper .getResource(RESOURCE_NAME); } catch (ClassCastException e) { log.debug("Cannot cast affected patients", e); clearAffectedPatients(); } return patients; }
diff --git a/core/src/visad/trunk/test/ImageAnimationTest.java b/core/src/visad/trunk/test/ImageAnimationTest.java index e99b63ef9..8e1c639a6 100644 --- a/core/src/visad/trunk/test/ImageAnimationTest.java +++ b/core/src/visad/trunk/test/ImageAnimationTest.java @@ -1,132 +1,132 @@ package visad.test; import java.awt.BorderLayout; import java.rmi.RemoteException; import javax.media.j3d.BranchGroup; import javax.swing.JFrame; import javax.swing.JPanel; import visad.AnimationControl; import visad.DataReference; import visad.DataReferenceImpl; import visad.Display; import visad.DisplayImpl; import visad.Field; import visad.FieldImpl; import visad.FlatField; import visad.FunctionType; import visad.Integer1DSet; import visad.Linear2DSet; import visad.RealTupleType; import visad.RealType; import visad.ScalarMap; import visad.VisADException; import visad.bom.ImageRendererJ3D; import visad.java3d.DisplayImplJ3D; import visad.java3d.DisplayRendererJ3D; import visad.util.Util; /** * Simple test for <code>AnimationControl</code> and <code>ImageRendererJ3D</code>. */ public class ImageAnimationTest extends JPanel { public static final float[] makeSinusoidalSamples(int lenX, int lenY, int waveNum) { float[] samples = new float[lenX*lenY]; int index = 0; double PI = Math.PI; for (int ii = 0; ii < lenX; ii++) { for (int jj = 0; jj < lenY; jj++) { samples[index] = (float) ( Math.sin((waveNum*PI) / 100 * jj) * Math.sin((waveNum*PI) / 100 * ii)); index++; } } return samples; } protected float[][] makeSamples(int size, int num) { float[][] samples = new float[num][size^2]; for (int i=0; i<num; i++) samples[i] = makeSinusoidalSamples(size, size, i); return samples; } public ImageAnimationTest(int num, int size) throws VisADException, RemoteException { // (Time -> ((x, y) -> val)) RealTupleType pxl = new RealTupleType(RealType.getRealType("x"), RealType.getRealType("y")); FunctionType pxlVal = new FunctionType(pxl, RealType.getRealType("val")); FunctionType timePxlVal = new FunctionType(RealType.Time, pxlVal); System.err.println(timePxlVal.toString()); Field timeFld = new FieldImpl(timePxlVal, new Integer1DSet(RealType.Time, num)); float[][] samples = makeSamples(size, num); for (int i = 0; i < samples.length; i++) { Linear2DSet imgSet = new Linear2DSet(pxlVal.getDomain(), 0, size - 1, size, 0, size - 1, size); FlatField imgFld = new FlatField(pxlVal, imgSet); imgFld.setSamples(new float[][]{samples[i]}); // set image for time timeFld.setSample(i, imgFld); } DataReference ref = new DataReferenceImpl("image"); ref.setData(timeFld); DisplayImpl display = new DisplayImplJ3D("image display"); ImageRendererJ3D imgRend = new ImageRendererJ3D(); System.err.println("Renderer:"+imgRend.toString()); - display.addReferences(imgRend, ref); display.addMap(new ScalarMap(RealType.getRealType("x"), Display.XAxis)); display.addMap(new ScalarMap(RealType.getRealType("y"), Display.YAxis)); display.addMap(new ScalarMap(RealType.getRealType("val"), Display.RGBA)); ScalarMap aniMap = new ScalarMap(RealType.Time, Display.Animation); display.addMap(aniMap); AnimationControl aniCtrl = (AnimationControl) aniMap.getControl(); aniCtrl.setStep(1000); aniCtrl.setOn(true); + display.addReferences(imgRend, ref); setLayout(new BorderLayout()); add(display.getComponent()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } BranchGroup scene = ((DisplayRendererJ3D) imgRend.getDisplayRenderer()).getRoot(); Util.printSceneGraph(scene); } public static void main(String[] args) throws RemoteException, VisADException { int num = 0; int size = 0; try { num = Integer.parseInt(args[0]); size = Integer.parseInt(args[1]); } catch (Exception e) { System.err.println("USAGE: ImageAnimationTest <numImgs> <size>"); System.exit(1); } Util.printJ3DProperties(null); JFrame frame = new JFrame("Image Animation Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new ImageAnimationTest(num, size)); frame.setSize(600, 600); frame.setVisible(true); } }
false
true
public ImageAnimationTest(int num, int size) throws VisADException, RemoteException { // (Time -> ((x, y) -> val)) RealTupleType pxl = new RealTupleType(RealType.getRealType("x"), RealType.getRealType("y")); FunctionType pxlVal = new FunctionType(pxl, RealType.getRealType("val")); FunctionType timePxlVal = new FunctionType(RealType.Time, pxlVal); System.err.println(timePxlVal.toString()); Field timeFld = new FieldImpl(timePxlVal, new Integer1DSet(RealType.Time, num)); float[][] samples = makeSamples(size, num); for (int i = 0; i < samples.length; i++) { Linear2DSet imgSet = new Linear2DSet(pxlVal.getDomain(), 0, size - 1, size, 0, size - 1, size); FlatField imgFld = new FlatField(pxlVal, imgSet); imgFld.setSamples(new float[][]{samples[i]}); // set image for time timeFld.setSample(i, imgFld); } DataReference ref = new DataReferenceImpl("image"); ref.setData(timeFld); DisplayImpl display = new DisplayImplJ3D("image display"); ImageRendererJ3D imgRend = new ImageRendererJ3D(); System.err.println("Renderer:"+imgRend.toString()); display.addReferences(imgRend, ref); display.addMap(new ScalarMap(RealType.getRealType("x"), Display.XAxis)); display.addMap(new ScalarMap(RealType.getRealType("y"), Display.YAxis)); display.addMap(new ScalarMap(RealType.getRealType("val"), Display.RGBA)); ScalarMap aniMap = new ScalarMap(RealType.Time, Display.Animation); display.addMap(aniMap); AnimationControl aniCtrl = (AnimationControl) aniMap.getControl(); aniCtrl.setStep(1000); aniCtrl.setOn(true); setLayout(new BorderLayout()); add(display.getComponent()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } BranchGroup scene = ((DisplayRendererJ3D) imgRend.getDisplayRenderer()).getRoot(); Util.printSceneGraph(scene); }
public ImageAnimationTest(int num, int size) throws VisADException, RemoteException { // (Time -> ((x, y) -> val)) RealTupleType pxl = new RealTupleType(RealType.getRealType("x"), RealType.getRealType("y")); FunctionType pxlVal = new FunctionType(pxl, RealType.getRealType("val")); FunctionType timePxlVal = new FunctionType(RealType.Time, pxlVal); System.err.println(timePxlVal.toString()); Field timeFld = new FieldImpl(timePxlVal, new Integer1DSet(RealType.Time, num)); float[][] samples = makeSamples(size, num); for (int i = 0; i < samples.length; i++) { Linear2DSet imgSet = new Linear2DSet(pxlVal.getDomain(), 0, size - 1, size, 0, size - 1, size); FlatField imgFld = new FlatField(pxlVal, imgSet); imgFld.setSamples(new float[][]{samples[i]}); // set image for time timeFld.setSample(i, imgFld); } DataReference ref = new DataReferenceImpl("image"); ref.setData(timeFld); DisplayImpl display = new DisplayImplJ3D("image display"); ImageRendererJ3D imgRend = new ImageRendererJ3D(); System.err.println("Renderer:"+imgRend.toString()); display.addMap(new ScalarMap(RealType.getRealType("x"), Display.XAxis)); display.addMap(new ScalarMap(RealType.getRealType("y"), Display.YAxis)); display.addMap(new ScalarMap(RealType.getRealType("val"), Display.RGBA)); ScalarMap aniMap = new ScalarMap(RealType.Time, Display.Animation); display.addMap(aniMap); AnimationControl aniCtrl = (AnimationControl) aniMap.getControl(); aniCtrl.setStep(1000); aniCtrl.setOn(true); display.addReferences(imgRend, ref); setLayout(new BorderLayout()); add(display.getComponent()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } BranchGroup scene = ((DisplayRendererJ3D) imgRend.getDisplayRenderer()).getRoot(); Util.printSceneGraph(scene); }
diff --git a/src/java/org/wings/plaf/css/AbstractLabelCG.java b/src/java/org/wings/plaf/css/AbstractLabelCG.java index 83cfc602..66dc57d1 100644 --- a/src/java/org/wings/plaf/css/AbstractLabelCG.java +++ b/src/java/org/wings/plaf/css/AbstractLabelCG.java @@ -1,133 +1,135 @@ /* * Copyright 2000,2005 wingS development team. * * This file is part of wingS (http://www.j-wings.org). * * wingS 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. * * Please see COPYING for the complete licence. */ package org.wings.plaf.css; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wings.SComponent; import org.wings.SIcon; import org.wings.SLabel; import org.wings.SResourceIcon; import org.wings.io.Device; import org.wings.io.StringBuilderDevice; import java.io.IOException; public abstract class AbstractLabelCG extends AbstractComponentCG { private static final Log log = LogFactory.getLog(AbstractLabelCG.class); public static SIcon TRANSPARENT_ICON = new SResourceIcon("org/wings/icons/transdot.gif"); public final void writeText(Device device, String text, boolean wordWrap) throws IOException { // white-space:nowrap seems to work in all major browser. // Except leading and trailing spaces! device.print("<span").print(wordWrap ? ">" : " style=\"white-space:nowrap\">"); if ((text.length() > 5) && (text.startsWith("<html>"))) { Utils.writeRaw(device, text.substring(6)); } else { // NOTE: Quoting of spaces would be only necessary for trailing and leading spaces !!! // TODO: Quote only trailing/leading spaces Utils.quote(device, text, true, !wordWrap, false); } device.print("</span>"); } public final void writeIcon(Device device, SIcon icon, boolean isMSIE) throws IOException { device.print("<img class=\"nopad\""); if (isMSIE && icon.getURL().toString().endsWith(".png") && icon.getIconWidth() > 0 && icon.getIconHeight() > 0) { Utils.optAttribute(device, "style", "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + icon.getURL() + "', sizingMethod='scale')"); Utils.optAttribute(device, "src", TRANSPARENT_ICON.getURL()); } else Utils.optAttribute(device, "src", icon.getURL()); Utils.optAttribute(device, "width", icon.getIconWidth()); Utils.optAttribute(device, "height", icon.getIconHeight()); device.print(" alt=\""); device.print(icon.getIconTitle()); device.print("\"/>"); } protected class TextUpdate extends AbstractUpdate { private String text; public TextUpdate(SComponent component, String text) { super(component); this.text = text; } public Handler getHandler() { String textCode = ""; String exception = null; try { StringBuilderDevice textDevice = new StringBuilderDevice(); boolean wordWrap = false; if (component instanceof SLabel) wordWrap = ((SLabel) component).isWordWrap(); + if (text == null) + text = ""; writeText(textDevice, text, wordWrap); textCode = textDevice.toString(); } catch (Throwable t) { log.fatal("An error occured during rendering", t); exception = t.getClass().getName(); } UpdateHandler handler = new UpdateHandler("updateText"); handler.addParameter(component.getName()); handler.addParameter(textCode); if (exception != null) { handler.addParameter(exception); } return handler; } } protected class IconUpdate extends AbstractUpdate { private SIcon icon; public IconUpdate(SComponent component, SIcon icon) { super(component); this.icon = icon; } public Handler getHandler() { String iconCode = ""; String exception = null; try { StringBuilderDevice iconDevice = new StringBuilderDevice(); writeIcon(iconDevice, icon, Utils.isMSIE(component)); iconCode = iconDevice.toString(); } catch (Throwable t) { log.fatal("An error occured during rendering", t); exception = t.getClass().getName(); } UpdateHandler handler = new UpdateHandler("updateIcon"); handler.addParameter(component.getName()); handler.addParameter(iconCode); if (exception != null) { handler.addParameter(exception); } return handler; } } }
true
true
public Handler getHandler() { String textCode = ""; String exception = null; try { StringBuilderDevice textDevice = new StringBuilderDevice(); boolean wordWrap = false; if (component instanceof SLabel) wordWrap = ((SLabel) component).isWordWrap(); writeText(textDevice, text, wordWrap); textCode = textDevice.toString(); } catch (Throwable t) { log.fatal("An error occured during rendering", t); exception = t.getClass().getName(); } UpdateHandler handler = new UpdateHandler("updateText"); handler.addParameter(component.getName()); handler.addParameter(textCode); if (exception != null) { handler.addParameter(exception); } return handler; }
public Handler getHandler() { String textCode = ""; String exception = null; try { StringBuilderDevice textDevice = new StringBuilderDevice(); boolean wordWrap = false; if (component instanceof SLabel) wordWrap = ((SLabel) component).isWordWrap(); if (text == null) text = ""; writeText(textDevice, text, wordWrap); textCode = textDevice.toString(); } catch (Throwable t) { log.fatal("An error occured during rendering", t); exception = t.getClass().getName(); } UpdateHandler handler = new UpdateHandler("updateText"); handler.addParameter(component.getName()); handler.addParameter(textCode); if (exception != null) { handler.addParameter(exception); } return handler; }
diff --git a/git-tests/src/jetbrains/buildServer/buildTriggers/vcs/git/tests/CleanerTest.java b/git-tests/src/jetbrains/buildServer/buildTriggers/vcs/git/tests/CleanerTest.java index 4471553..1ea8be2 100644 --- a/git-tests/src/jetbrains/buildServer/buildTriggers/vcs/git/tests/CleanerTest.java +++ b/git-tests/src/jetbrains/buildServer/buildTriggers/vcs/git/tests/CleanerTest.java @@ -1,128 +1,128 @@ /* * Copyright 2000-2012 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.buildTriggers.vcs.git.tests; import jetbrains.buildServer.BaseTestCase; import jetbrains.buildServer.TempFiles; import jetbrains.buildServer.buildTriggers.vcs.git.*; import jetbrains.buildServer.serverSide.BuildServerListener; import jetbrains.buildServer.serverSide.SBuildServer; import jetbrains.buildServer.serverSide.ServerPaths; import jetbrains.buildServer.util.EventDispatcher; import jetbrains.buildServer.util.cache.ResetCacheRegister; import jetbrains.buildServer.vcs.VcsException; import jetbrains.buildServer.vcs.VcsRoot; import org.jmock.Expectations; import org.jmock.Mockery; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * @author dmitry.neverov */ @Test public class CleanerTest extends BaseTestCase { private static final TempFiles ourTempFiles = new TempFiles(); private Cleaner myCleaner; private ScheduledExecutorService myCleanExecutor; private GitVcsSupport mySupport; private RepositoryManager myRepositoryManager; private ServerPluginConfig myConfig; @BeforeMethod public void setUp() throws IOException { File dotBuildServer = ourTempFiles.createTempDir(); ServerPaths myServerPaths = new ServerPaths(dotBuildServer.getAbsolutePath()); PluginConfigBuilder myConfigBuilder = new PluginConfigBuilder(myServerPaths) .setRunNativeGC(true) - .setMirrorExpirationTimeoutMillis(4000); + .setMirrorExpirationTimeoutMillis(10000); if (System.getenv(Constants.TEAMCITY_AGENT_GIT_PATH) != null) myConfigBuilder.setPathToGit(System.getenv(Constants.TEAMCITY_AGENT_GIT_PATH)); Mockery myContext = new Mockery(); myCleanExecutor = Executors.newSingleThreadScheduledExecutor(); final SBuildServer server = myContext.mock(SBuildServer.class); myContext.checking(new Expectations() {{ allowing(server).getExecutor(); will(returnValue(myCleanExecutor)); }}); myConfig = myConfigBuilder.build(); TransportFactory transportFactory = new TransportFactoryImpl(myConfig); FetchCommand fetchCommand = new FetchCommandImpl(myConfig, transportFactory); MirrorManager mirrorManager = new MirrorManagerImpl(myConfig, new HashCalculatorImpl()); myRepositoryManager = new RepositoryManagerImpl(myConfig, mirrorManager); mySupport = new GitVcsSupport(myConfig, new ResetCacheRegister(), transportFactory, fetchCommand, myRepositoryManager, null); myCleaner = new Cleaner(server, EventDispatcher.create(BuildServerListener.class), myConfig, myRepositoryManager); } @AfterMethod public void tearDown() { ourTempFiles.cleanup(); } public void test_clean() throws VcsException, InterruptedException { File baseMirrorsDir = myRepositoryManager.getBaseMirrorsDir(); generateGarbage(baseMirrorsDir); Thread.sleep(myConfig.getMirrorExpirationTimeoutMillis()); final VcsRoot root = GitTestUtil.getVcsRoot(); mySupport.getCurrentVersion(root);//it will create dir in cache directory File repositoryDir = getRepositoryDir(root); invokeClean(); File[] files = baseMirrorsDir.listFiles(new FileFilter() { public boolean accept(File f) { return f.isDirectory(); } }); assertEquals(1, files.length); assertEquals(repositoryDir, files[0]); mySupport.getCurrentVersion(root);//check that repository is fine after git gc } private void invokeClean() throws InterruptedException { myCleaner.cleanupStarted(); myCleanExecutor.shutdown(); myCleanExecutor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS); } private File getRepositoryDir(VcsRoot root) throws VcsException { Settings settings = new Settings(myRepositoryManager, root); return settings.getRepositoryDir(); } private void generateGarbage(File dir) { dir.mkdirs(); for (int i = 0; i < 10; i++) { new File(dir, "git-AHAHAHA"+i+".git").mkdir(); } } }
true
true
public void setUp() throws IOException { File dotBuildServer = ourTempFiles.createTempDir(); ServerPaths myServerPaths = new ServerPaths(dotBuildServer.getAbsolutePath()); PluginConfigBuilder myConfigBuilder = new PluginConfigBuilder(myServerPaths) .setRunNativeGC(true) .setMirrorExpirationTimeoutMillis(4000); if (System.getenv(Constants.TEAMCITY_AGENT_GIT_PATH) != null) myConfigBuilder.setPathToGit(System.getenv(Constants.TEAMCITY_AGENT_GIT_PATH)); Mockery myContext = new Mockery(); myCleanExecutor = Executors.newSingleThreadScheduledExecutor(); final SBuildServer server = myContext.mock(SBuildServer.class); myContext.checking(new Expectations() {{ allowing(server).getExecutor(); will(returnValue(myCleanExecutor)); }}); myConfig = myConfigBuilder.build(); TransportFactory transportFactory = new TransportFactoryImpl(myConfig); FetchCommand fetchCommand = new FetchCommandImpl(myConfig, transportFactory); MirrorManager mirrorManager = new MirrorManagerImpl(myConfig, new HashCalculatorImpl()); myRepositoryManager = new RepositoryManagerImpl(myConfig, mirrorManager); mySupport = new GitVcsSupport(myConfig, new ResetCacheRegister(), transportFactory, fetchCommand, myRepositoryManager, null); myCleaner = new Cleaner(server, EventDispatcher.create(BuildServerListener.class), myConfig, myRepositoryManager); }
public void setUp() throws IOException { File dotBuildServer = ourTempFiles.createTempDir(); ServerPaths myServerPaths = new ServerPaths(dotBuildServer.getAbsolutePath()); PluginConfigBuilder myConfigBuilder = new PluginConfigBuilder(myServerPaths) .setRunNativeGC(true) .setMirrorExpirationTimeoutMillis(10000); if (System.getenv(Constants.TEAMCITY_AGENT_GIT_PATH) != null) myConfigBuilder.setPathToGit(System.getenv(Constants.TEAMCITY_AGENT_GIT_PATH)); Mockery myContext = new Mockery(); myCleanExecutor = Executors.newSingleThreadScheduledExecutor(); final SBuildServer server = myContext.mock(SBuildServer.class); myContext.checking(new Expectations() {{ allowing(server).getExecutor(); will(returnValue(myCleanExecutor)); }}); myConfig = myConfigBuilder.build(); TransportFactory transportFactory = new TransportFactoryImpl(myConfig); FetchCommand fetchCommand = new FetchCommandImpl(myConfig, transportFactory); MirrorManager mirrorManager = new MirrorManagerImpl(myConfig, new HashCalculatorImpl()); myRepositoryManager = new RepositoryManagerImpl(myConfig, mirrorManager); mySupport = new GitVcsSupport(myConfig, new ResetCacheRegister(), transportFactory, fetchCommand, myRepositoryManager, null); myCleaner = new Cleaner(server, EventDispatcher.create(BuildServerListener.class), myConfig, myRepositoryManager); }
diff --git a/oxsit-sing_var_uno/src/com/yacme/ext/oxsit/comp/GlobalLogger.java b/oxsit-sing_var_uno/src/com/yacme/ext/oxsit/comp/GlobalLogger.java index bfe55c6..2fae80d 100644 --- a/oxsit-sing_var_uno/src/com/yacme/ext/oxsit/comp/GlobalLogger.java +++ b/oxsit-sing_var_uno/src/com/yacme/ext/oxsit/comp/GlobalLogger.java @@ -1,420 +1,423 @@ /************************************************************************* * * Copyright 2009 by Giuseppe Castagno [email protected] * * The Contents of this file are made available subject to * the terms of European Union Public License (EUPL) version 1.1 * as published by the European Community. * * This program is free software: you can redistribute it and/or modify * it under the terms of the EUPL. * * 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 * EUPL for more details. * * You should have received a copy of the EUPL along with this * program. If not, see: * https://www.osor.eu/eupl, http://ec.europa.eu/idabc/eupl. * ************************************************************************/ package com.yacme.ext.oxsit.comp; import com.yacme.ext.oxsit.logging.XOX_Logger; import java.io.File; import java.io.IOException; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import com.sun.star.lang.XServiceInfo; import com.sun.star.lib.uno.helper.ComponentBase; import com.sun.star.uno.XComponentContext; import com.yacme.ext.oxsit.logging.LocalLogFormatter; import com.yacme.ext.oxsit.ooo.GlobConstant; import com.yacme.ext.oxsit.singleton.LoggerParametersAccess; /** * This class is a singleton UNO object. * * This class implements the global logger for the extension. * It needs to be a singleton object. * NOTE: it can't use the DynamicLogger, but instead will use the 'real' Java logger. * @author beppe * */ public class GlobalLogger extends ComponentBase implements XServiceInfo, XOX_Logger { // the name of the class implementing this object public static final String m_sImplementationName = GlobalLogger.class.getName(); // the Object name, used to instantiate it inside the OOo APIs public static final String[] m_sServiceNames = { GlobConstant.m_sSINGLETON_LOGGER_SERVICE }; /// This instead is the global logger, instantiated to have a Java singleton available protected static ConsoleHandler m_aConsoleHandl; protected static LocalLogFormatter m_aLogFormatter; protected static FileHandler m_aLogFileHandl; protected static LocalLogFormatter m_aLogFileFormatter; //logger configuration protected int m_nLogLevel; // not yet used... TODO protected static String m_sName; protected static boolean m_bEnableInfoLevel = true; protected static boolean m_bEnableDebugLogging = true; protected static boolean m_bEnableConsoleOutput = false; protected static boolean m_bEnableFileOutput = true; protected static String m_sLogFilePath = ""; protected static int m_nFileRotationCount = 1; protected static int m_nMaxFileSize = 200000; protected boolean m_bCanLogMyself; //only used as a synchronizing object private static Boolean m_bLogConfigChanged = new Boolean(false); // the 'real' global logger private static Logger m_aLogger; private static boolean m_bEnableLogging = true; private LoggerParametersAccess m_aLoggerConfigAccess; /** * * * @param _ctx */ public GlobalLogger(XComponentContext _ctx) { //read the logger configuration locally //get configuration access, using standard registry functions m_aLoggerConfigAccess = new LoggerParametersAccess(_ctx); m_sName = GlobConstant.m_sEXTENSION_IDENTIFIER; m_aLogger = Logger.getLogger(m_sName); m_aLogger.setUseParentHandlers(false);//disables the console output of the root logger getLoggingConfiguration(); configureLogger(); if(m_bCanLogMyself) m_aLogger.info("ctor"); } /* (non-Javadoc) * @see com.sun.star.lang.XServiceInfo#getImplementationName() */ @Override public String getImplementationName() { return m_sImplementationName; } /* (non-Javadoc) * @see com.sun.star.lang.XServiceInfo#getSupportedServiceNames() */ @Override public String[] getSupportedServiceNames() { if(m_bCanLogMyself) m_aLogger.info("getSupportedServiceNames"); return m_sServiceNames; } /* (non-Javadoc) * @see com.sun.star.lang.XServiceInfo#supportsService(java.lang.String) */ @Override public boolean supportsService(String _sService) { int len = m_sServiceNames.length; for (int i = 0; i < len; i++) { if (_sService.equals( m_sServiceNames[i] )) return true; } return false; } // protected logger functions /** * read logging configuration from registry and set internal variables */ protected void getLoggingConfiguration() { m_bEnableInfoLevel = m_aLoggerConfigAccess.getBoolean(GlobConstant.m_sENABLE_INFO_LEVEL); m_bEnableDebugLogging = m_aLoggerConfigAccess.getBoolean(GlobConstant.m_sENABLE_DEBUG_LOGGING); m_bEnableConsoleOutput = m_aLoggerConfigAccess.getBoolean(GlobConstant.m_sENABLE_CONSOLE_OUTPUT); m_bEnableFileOutput = m_aLoggerConfigAccess.getBoolean(GlobConstant.m_sENABLE_FILE_OUTPUT); m_sLogFilePath = m_aLoggerConfigAccess.getText(GlobConstant.m_sLOG_FILE_PATH); m_nFileRotationCount = m_aLoggerConfigAccess.getNumber(GlobConstant.m_sFILE_ROTATION_COUNT); m_nMaxFileSize = m_aLoggerConfigAccess.getNumber(GlobConstant.m_sMAX_FILE_SIZE); } protected void configureLogger() { + //set the general level m_aLogger.setLevel(Level.FINEST); if(m_bEnableConsoleOutput) { m_aConsoleHandl = new ConsoleHandler(); + m_aConsoleHandl.setLevel(Level.FINEST); m_aLogFormatter = new LocalLogFormatter(); m_aConsoleHandl.setFormatter(m_aLogFormatter); m_aLogger.addHandler(m_aConsoleHandl); System.out.println("console logging enabled"); } //DEBUG else System.out.println("console logging NOT enabled"); if(m_bEnableFileOutput) { String sFileName = GlobConstant.m_sEXTENSION_IDENTIFIER+".log"; try { if(m_sLogFilePath.length() > 0) { // e.g.: get the path separator, then scan the file path and change from whatever value to '/' String aFileSeparator = System.getProperty("file.separator"); //now, copy in a new string the sored path, changing the file separator char to '/' String aNewPath = ""; for(int i = 0; i < m_sLogFilePath.length(); i++) if(m_sLogFilePath.charAt(i) == aFileSeparator.charAt(0)) aNewPath = aNewPath +"/"; else aNewPath = aNewPath + m_sLogFilePath.charAt(i); sFileName = aNewPath+"/"+sFileName; } else sFileName = "%h/"+sFileName; m_aLogFileHandl = new FileHandler( sFileName,m_nMaxFileSize,m_nFileRotationCount); + m_aLogFileHandl.setLevel(Level.FINEST); m_aLogFileFormatter = new LocalLogFormatter(); m_aLogFileHandl.setFormatter(m_aLogFileFormatter); m_aLogger.addHandler(m_aLogFileHandl); //FIXME DEBUG System.out.println("files logging enabled, path "+" "+sFileName+" size: "+m_nMaxFileSize+" count: "+m_nFileRotationCount); } catch (SecurityException e) { //FIXME it seems the formatter does act accordingly e.printStackTrace(); System.out.println("file logging NOT enabled "); } catch (IOException e) { e.printStackTrace(); System.out.println("file logging NOT enabled: problem with formatter or file access "); } } /*FIXME DEBUG else System.out.println("file logging NOT enabled ");*/ if(!m_bEnableConsoleOutput && !m_bEnableFileOutput) m_bEnableLogging = false; m_bCanLogMyself = m_bEnableLogging && m_bEnableInfoLevel; //set all levels, the levels are filtered by this class. } /* (non-Javadoc) * @see com.sun.star.logging.XOX_Logger#getLevel() */ @Override public int getLevel() { return m_nLogLevel; } /* (non-Javadoc) * @see com.sun.star.logging.XOX_Logger#getName() */ @Override public String getName() { return m_sName; } /* (non-Javadoc) * @see com.sun.star.logging.XOX_Logger#logp(int, java.lang.String, java.lang.String, java.lang.String) */ @Override public void logp(int _nLevel, String arg1, String arg2, String arg3) { synchronized (m_bLogConfigChanged) { if(m_bEnableLogging) switch (_nLevel) { default: m_aLogger.logp(Level.FINE, arg1, arg2, arg3); break; case GlobConstant.m_nLOG_LEVEL_INFO: if(m_bEnableInfoLevel) m_aLogger.logp(Level.INFO, arg1, arg2, arg3); break; case GlobConstant.m_nLOG_LEVEL_DEBUG: if(m_bEnableDebugLogging) m_aLogger.logp(Level.FINE, arg1, arg2, arg3); break; case GlobConstant.m_nLOG_LEVEL_SEVERE: m_aLogger.logp(Level.SEVERE, arg1, arg2, arg3); break; case GlobConstant.m_nLOG_LEVEL_WARNING: //FIXME: for the time being a warning is always logged // if(m_bEnableDebugLogging) m_aLogger.logp(Level.WARNING, arg1, arg2, arg3); break; } } } /* * * (non-Javadoc) * @see com.sun.star.logging.XOX_Logger#setLevel(int) */ @Override public void setLevel(int _nNewVal) { synchronized (m_bLogConfigChanged) { // m_nLogLevel = _nNewVal; } } /* (non-Javadoc) * @see com.yacme.ext.oxsit.logging.XOX_Logger#getEnableConsoleOutput() */ @Override public boolean getEnableConsoleOutput() { return m_bEnableConsoleOutput; } /* (non-Javadoc) * @see com.yacme.ext.oxsit.logging.XOX_Logger#getEnableFileOutput() */ @Override public boolean getEnableFileOutput() { return m_bEnableFileOutput; } /* (non-Javadoc) * @see com.yacme.ext.oxsit.logging.XOX_Logger#getEnableInfoLevel() */ @Override public boolean getEnableInfoLevel() { return m_bEnableInfoLevel; } /* (non-Javadoc) * @see com.yacme.ext.oxsit.logging.XOX_Logger#getEnableLogging() */ @Override public boolean getEnableLogging() { return m_bEnableLogging; } /* (non-Javadoc) * @see com.yacme.ext.oxsit.logging.XOX_Logger#getEnableWarningLevel() */ @Override public boolean getEnableDebugLogging() { return m_bEnableDebugLogging; } /* (non-Javadoc) * @see com.yacme.ext.oxsit.logging.XOX_Logger#localConfigurationChanged() */ @Override public void localConfigurationChanged() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see com.yacme.ext.oxsit.logging.XOX_Logger#optionsConfigurationChanged() */ @Override public void optionsConfigurationChanged() { synchronized (m_bLogConfigChanged) { m_aLogger.info("setLevel (change config) called"); Level aLev = m_aLogger.getLevel(); // protected area to change base elements of configuration getLoggingConfiguration(); // restart logger, what is possible to restart, that is... // configureLogger(); } } /* (non-Javadoc) * @see com.yacme.ext.oxsit.logging.XOX_Logger#setEnableConsoleOutput(boolean) */ @Override public void setEnableConsoleOutput(boolean _bNewVal) { synchronized (m_bLogConfigChanged) { m_bEnableConsoleOutput = _bNewVal; } } /* (non-Javadoc) * @see com.yacme.ext.oxsit.logging.XOX_Logger#setEnableFileOutput(boolean) */ @Override public void setEnableFileOutput(boolean _bNewVal) { synchronized (m_bLogConfigChanged) { m_bEnableFileOutput = _bNewVal; } } /* (non-Javadoc) * @see com.yacme.ext.oxsit.logging.XOX_Logger#setEnableInfoLevel(boolean) */ @Override public void setEnableInfoLevel(boolean _bNewVal) { synchronized (m_bLogConfigChanged) { m_bEnableInfoLevel = _bNewVal; } } /* (non-Javadoc) * @see com.yacme.ext.oxsit.logging.XOX_Logger#setEnableLogging(boolean) */ @Override public void setEnableLogging(boolean _bNewVal) { synchronized (m_bLogConfigChanged) { m_bEnableLogging = _bNewVal; } } /* (non-Javadoc) * It's called from configuration when the logging * levels in the configuration change: the new level * will be taken into account immediately. * as well as the file name: * close the current handler, * TODO * May be we can use a changelistener object on the * configuration parameters. * * The event is fired when the parameters change. * @see com.yacme.ext.oxsit.logging.XOX_Logger#setEnableWarningLevel(boolean) */ @Override public void setEnableDebugLogging(boolean _bNewVal) { synchronized(m_bLogConfigChanged) { m_bEnableDebugLogging = _bNewVal; } } /* (non-Javadoc) * @see com.yacme.ext.oxsit.logging.XOX_Logger#stopLogging() */ @Override public void stopLogging() { // TODO Auto-generated method stub synchronized(m_bLogConfigChanged) { setEnableLogging(false); } synchronized(m_bLogConfigChanged) { if(m_bEnableFileOutput && m_aLogFileHandl != null) { m_aLogFileHandl.close(); setEnableFileOutput(false); m_aLogFileHandl = null; } } } /* (non-Javadoc) * @see com.sun.star.lang.XComponent#dispose() */ @Override public void dispose() { if(m_bCanLogMyself) m_aLogger.entering("dispose", ""); stopLogging(); super.dispose(); } }
false
true
protected void configureLogger() { m_aLogger.setLevel(Level.FINEST); if(m_bEnableConsoleOutput) { m_aConsoleHandl = new ConsoleHandler(); m_aLogFormatter = new LocalLogFormatter(); m_aConsoleHandl.setFormatter(m_aLogFormatter); m_aLogger.addHandler(m_aConsoleHandl); System.out.println("console logging enabled"); } //DEBUG else System.out.println("console logging NOT enabled"); if(m_bEnableFileOutput) { String sFileName = GlobConstant.m_sEXTENSION_IDENTIFIER+".log"; try { if(m_sLogFilePath.length() > 0) { // e.g.: get the path separator, then scan the file path and change from whatever value to '/' String aFileSeparator = System.getProperty("file.separator"); //now, copy in a new string the sored path, changing the file separator char to '/' String aNewPath = ""; for(int i = 0; i < m_sLogFilePath.length(); i++) if(m_sLogFilePath.charAt(i) == aFileSeparator.charAt(0)) aNewPath = aNewPath +"/"; else aNewPath = aNewPath + m_sLogFilePath.charAt(i); sFileName = aNewPath+"/"+sFileName; } else sFileName = "%h/"+sFileName; m_aLogFileHandl = new FileHandler( sFileName,m_nMaxFileSize,m_nFileRotationCount); m_aLogFileFormatter = new LocalLogFormatter(); m_aLogFileHandl.setFormatter(m_aLogFileFormatter); m_aLogger.addHandler(m_aLogFileHandl); //FIXME DEBUG System.out.println("files logging enabled, path "+" "+sFileName+" size: "+m_nMaxFileSize+" count: "+m_nFileRotationCount); } catch (SecurityException e) { //FIXME it seems the formatter does act accordingly e.printStackTrace(); System.out.println("file logging NOT enabled "); } catch (IOException e) { e.printStackTrace(); System.out.println("file logging NOT enabled: problem with formatter or file access "); } } /*FIXME DEBUG else System.out.println("file logging NOT enabled ");*/ if(!m_bEnableConsoleOutput && !m_bEnableFileOutput) m_bEnableLogging = false; m_bCanLogMyself = m_bEnableLogging && m_bEnableInfoLevel; //set all levels, the levels are filtered by this class. }
protected void configureLogger() { //set the general level m_aLogger.setLevel(Level.FINEST); if(m_bEnableConsoleOutput) { m_aConsoleHandl = new ConsoleHandler(); m_aConsoleHandl.setLevel(Level.FINEST); m_aLogFormatter = new LocalLogFormatter(); m_aConsoleHandl.setFormatter(m_aLogFormatter); m_aLogger.addHandler(m_aConsoleHandl); System.out.println("console logging enabled"); } //DEBUG else System.out.println("console logging NOT enabled"); if(m_bEnableFileOutput) { String sFileName = GlobConstant.m_sEXTENSION_IDENTIFIER+".log"; try { if(m_sLogFilePath.length() > 0) { // e.g.: get the path separator, then scan the file path and change from whatever value to '/' String aFileSeparator = System.getProperty("file.separator"); //now, copy in a new string the sored path, changing the file separator char to '/' String aNewPath = ""; for(int i = 0; i < m_sLogFilePath.length(); i++) if(m_sLogFilePath.charAt(i) == aFileSeparator.charAt(0)) aNewPath = aNewPath +"/"; else aNewPath = aNewPath + m_sLogFilePath.charAt(i); sFileName = aNewPath+"/"+sFileName; } else sFileName = "%h/"+sFileName; m_aLogFileHandl = new FileHandler( sFileName,m_nMaxFileSize,m_nFileRotationCount); m_aLogFileHandl.setLevel(Level.FINEST); m_aLogFileFormatter = new LocalLogFormatter(); m_aLogFileHandl.setFormatter(m_aLogFileFormatter); m_aLogger.addHandler(m_aLogFileHandl); //FIXME DEBUG System.out.println("files logging enabled, path "+" "+sFileName+" size: "+m_nMaxFileSize+" count: "+m_nFileRotationCount); } catch (SecurityException e) { //FIXME it seems the formatter does act accordingly e.printStackTrace(); System.out.println("file logging NOT enabled "); } catch (IOException e) { e.printStackTrace(); System.out.println("file logging NOT enabled: problem with formatter or file access "); } } /*FIXME DEBUG else System.out.println("file logging NOT enabled ");*/ if(!m_bEnableConsoleOutput && !m_bEnableFileOutput) m_bEnableLogging = false; m_bCanLogMyself = m_bEnableLogging && m_bEnableInfoLevel; //set all levels, the levels are filtered by this class. }
diff --git a/component/src/main/java/com/celements/photo/service/ImageService.java b/component/src/main/java/com/celements/photo/service/ImageService.java index 5815e8d..5eace1c 100644 --- a/component/src/main/java/com/celements/photo/service/ImageService.java +++ b/component/src/main/java/com/celements/photo/service/ImageService.java @@ -1,298 +1,300 @@ package com.celements.photo.service; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Random; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xwiki.component.annotation.Component; import org.xwiki.component.annotation.Requirement; import org.xwiki.context.Execution; import org.xwiki.model.EntityType; import org.xwiki.model.reference.AttachmentReference; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReferenceResolver; import org.xwiki.model.reference.SpaceReference; import org.xwiki.model.reference.WikiReference; import com.celements.common.classes.IClassCollectionRole; import com.celements.navigation.NavigationClasses; import com.celements.photo.container.ImageDimensions; import com.celements.photo.image.GenerateThumbnail; import com.celements.web.classcollections.OldCoreClasses; import com.celements.web.plugin.cmd.AttachmentURLCommand; import com.celements.web.plugin.cmd.NextFreeDocNameCommand; import com.celements.web.service.IWebUtilsService; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.Attachment; import com.xpn.xwiki.api.Document; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; @Component public class ImageService implements IImageService { private static final Log LOGGER = LogFactory.getFactory().getInstance( ImageService.class); @Requirement EntityReferenceResolver<String> stringRefResolver; @Requirement("celements.oldCoreClasses") IClassCollectionRole oldCoreClasses; @Requirement("celements.celNavigationClasses") IClassCollectionRole navigationClasses; @Requirement IWebUtilsService webUtilsService; NextFreeDocNameCommand nextFreeDocNameCmd; @Requirement Execution execution; AttachmentURLCommand attURLCmd; private XWikiContext getContext() { return (XWikiContext) execution.getContext().getProperty("xwikicontext"); } private OldCoreClasses getOldCoreClasses() { return (OldCoreClasses) oldCoreClasses; } private NavigationClasses getNavigationClasses() { return (NavigationClasses) navigationClasses; } public BaseObject getPhotoAlbumObject(DocumentReference galleryDocRef ) throws XWikiException { XWikiDocument galleryDoc = getContext().getWiki().getDocument(galleryDocRef, getContext()); BaseObject galleryObj = galleryDoc.getXObject(getOldCoreClasses( ).getPhotoAlbumClassRef(getContext().getDatabase())); return galleryObj; } public BaseObject getPhotoAlbumNavObject(DocumentReference galleryDocRef ) throws XWikiException, NoGalleryDocumentException { XWikiDocument galleryDoc = getContext().getWiki().getDocument(galleryDocRef, getContext()); BaseObject navObj = galleryDoc.getXObject(getNavigationClasses( ).getNavigationConfigClassRef(getContext().getDatabase())); if (navObj == null) { throw new NoGalleryDocumentException(); } return navObj; } public SpaceReference getPhotoAlbumSpaceRef(DocumentReference galleryDocRef ) throws NoGalleryDocumentException { try { String spaceName = getPhotoAlbumNavObject(galleryDocRef).getStringValue( NavigationClasses.MENU_SPACE_FIELD); return new SpaceReference(spaceName, webUtilsService.getWikiRef( galleryDocRef)); } catch (XWikiException exp) { LOGGER.error("Failed to getPhotoAlbumSpaceRef.", exp); } return null; } public int getPhotoAlbumMaxHeight(DocumentReference galleryDocRef ) throws NoGalleryDocumentException { try { return getPhotoAlbumObject(galleryDocRef).getIntValue("height2"); } catch (XWikiException exp) { LOGGER.error("Failed to getPhotoAlbumSpaceRef.", exp); } return 2000; } public int getPhotoAlbumMaxWidth(DocumentReference galleryDocRef ) throws NoGalleryDocumentException { try { return getPhotoAlbumObject(galleryDocRef).getIntValue("photoWidth"); } catch (XWikiException exp) { LOGGER.error("Failed to getPhotoAlbumSpaceRef.", exp); } return 2000; } private DocumentReference getDocRefFromFullName(String collDocName) { DocumentReference eventRef = new DocumentReference(stringRefResolver.resolve( collDocName, EntityType.DOCUMENT)); eventRef.setWikiReference(new WikiReference(getContext().getDatabase())); LOGGER.debug("getDocRefFromFullName: for [" + collDocName + "] got reference [" + eventRef + "]."); return eventRef; } public ImageDimensions getDimension(String imageFullName) throws XWikiException { String fullName = imageFullName.split(";")[0]; String imageFileName = imageFullName.split(";")[1]; DocumentReference docRef = getDocRefFromFullName(fullName); AttachmentReference imgRef = new AttachmentReference(imageFileName, docRef); return getDimension(imgRef); } public ImageDimensions getDimension(AttachmentReference imgRef) throws XWikiException { DocumentReference docRef = (DocumentReference) imgRef.getParent(); XWikiDocument theDoc = getContext().getWiki().getDocument(docRef, getContext()); XWikiAttachment theAttachment = theDoc.getAttachment(imgRef.getName()); ImageDimensions imageDimensions = null; GenerateThumbnail genThumbnail = new GenerateThumbnail(); InputStream imageInStream = null; try { imageInStream = theAttachment.getContentInputStream(getContext()); imageDimensions = genThumbnail.getImageDimensions(imageInStream); } finally { if(imageInStream != null) { try { imageInStream.close(); } catch (IOException ioe) { LOGGER.error("Error closing InputStream.", ioe); } } else { imageDimensions = new ImageDimensions(); } } return imageDimensions; } /** * getRandomImages computes a set of <num> randomly chosen images * from the given AttachmentList. It chooses the Images without duplicates if * possible. */ public List<Attachment> getRandomImages(DocumentReference galleryRef, int num) { try { Document imgDoc = getContext().getWiki().getDocument(galleryRef, getContext() ).newDocument(getContext()); List<Attachment> allImagesList = webUtilsService.getAttachmentListSorted(imgDoc, "AttachmentAscendingNameComparator", true); if (allImagesList.size() > 0) { List<Attachment> preSetImgList = prepareMaxCoverSet(num, allImagesList); List<Attachment> imgList = new ArrayList<Attachment>(num); Random rand = new Random(); for (int i=1; i<=num ; i++) { int nextimg = rand.nextInt(preSetImgList.size()); imgList.add(preSetImgList.remove(nextimg)); } return imgList; } } catch (XWikiException e) { LOGGER.error(e); } return Collections.emptyList(); } <T> List<T> prepareMaxCoverSet(int num, List<T> allImagesList) { List<T> preSetImgList = new Vector<T>(num); preSetImgList.addAll(allImagesList); for(int i=2; i <= coveredQuotient(allImagesList.size(), num); i++) { preSetImgList.addAll(allImagesList); } return preSetImgList; } int coveredQuotient(int divisor, int dividend) { if (dividend >= 0) { return ( (dividend + divisor - 1) / divisor); } else { return (dividend / divisor); } } private NextFreeDocNameCommand getNextFreeDocNameCmd() { if (this.nextFreeDocNameCmd == null) { this.nextFreeDocNameCmd = new NextFreeDocNameCommand(); } return this.nextFreeDocNameCmd; } private AttachmentURLCommand getAttURLCmd() { if (attURLCmd == null) { attURLCmd = new AttachmentURLCommand(); } return attURLCmd; } public boolean checkAddSlideRights(DocumentReference galleryDocRef) { try { DocumentReference newSlideDocRef = getNextFreeDocNameCmd().getNextTitledPageDocRef( getPhotoAlbumSpaceRef(galleryDocRef).getName(), "Testname", getContext()); String newSlideDocFN = webUtilsService.getRefDefaultSerializer().serialize( newSlideDocRef); return (getContext().getWiki().getRightService().hasAccessLevel("edit", getContext().getUser(), newSlideDocFN, getContext())); } catch (XWikiException exp) { LOGGER.error("failed to checkAddSlideRights for [" + galleryDocRef + "].", exp); } catch (NoGalleryDocumentException exp) { LOGGER.debug("failed to checkAddSlideRights for no gallery document [" + galleryDocRef + "].", exp); } return false; } public boolean addSlideFromTemplate(DocumentReference galleryDocRef, String slideBaseName, String attFullName) { try { DocumentReference slideTemplateRef = getImageSlideTemplateRef(); String gallerySpaceName = getPhotoAlbumSpaceRef(galleryDocRef).getName(); DocumentReference newSlideDocRef = getNextFreeDocNameCmd().getNextTitledPageDocRef( gallerySpaceName, slideBaseName, getContext()); if (getContext().getWiki().copyDocument(slideTemplateRef, newSlideDocRef, true, getContext())) { XWikiDocument newSlideDoc = getContext().getWiki().getDocument(newSlideDocRef, getContext()); newSlideDoc.setDefaultLanguage(webUtilsService.getDefaultLanguage( gallerySpaceName)); Date creationDate = new Date(); newSlideDoc.setLanguage(""); newSlideDoc.setCreationDate(creationDate); newSlideDoc.setContentUpdateDate(creationDate); newSlideDoc.setDate(creationDate); newSlideDoc.setCreator(getContext().getUser()); newSlideDoc.setAuthor(getContext().getUser()); newSlideDoc.setTranslation(0); - String imgURL = getAttURLCmd().getAttachmentURL(attFullName, getContext()); + String imgURL = getAttURLCmd().getAttachmentURL(attFullName, "download", + getContext()); String resizeParam = "celwidth=" + getPhotoAlbumMaxWidth(galleryDocRef) + "&celheight=" + getPhotoAlbumMaxHeight(galleryDocRef); - newSlideDoc.setContent("<img src=\"" + imgURL + "?" + resizeParam + "\"/>"); + String fullImgURL = imgURL + ((imgURL.indexOf("?") < 0)?"?":"&") + resizeParam; + newSlideDoc.setContent("<img src=\"" + fullImgURL + "\"/>"); getContext().getWiki().saveDocument(newSlideDoc, "add default image slide" + " content", true, getContext()); return true; } else { LOGGER.warn("failed to copy slideTemplateRef [" + slideTemplateRef + "] to new slide doc [" + newSlideDocRef + "]."); } } catch (NoGalleryDocumentException exp) { LOGGER.error("failed to addSlideFromTemplate because no gallery doc.", exp); } catch (XWikiException exp) { LOGGER.error("failed to addSlideFromTemplate.", exp); } return false; } public DocumentReference getImageSlideTemplateRef() { DocumentReference slideTemplateRef = new DocumentReference( getContext().getDatabase(), "ImageGalleryTemplates", "NewImageGallerySlide"); if(!getContext().getWiki().exists(slideTemplateRef, getContext())) { slideTemplateRef = new DocumentReference("celements2web", "ImageGalleryTemplates", "NewImageGallerySlide"); } return slideTemplateRef; } }
false
true
public boolean addSlideFromTemplate(DocumentReference galleryDocRef, String slideBaseName, String attFullName) { try { DocumentReference slideTemplateRef = getImageSlideTemplateRef(); String gallerySpaceName = getPhotoAlbumSpaceRef(galleryDocRef).getName(); DocumentReference newSlideDocRef = getNextFreeDocNameCmd().getNextTitledPageDocRef( gallerySpaceName, slideBaseName, getContext()); if (getContext().getWiki().copyDocument(slideTemplateRef, newSlideDocRef, true, getContext())) { XWikiDocument newSlideDoc = getContext().getWiki().getDocument(newSlideDocRef, getContext()); newSlideDoc.setDefaultLanguage(webUtilsService.getDefaultLanguage( gallerySpaceName)); Date creationDate = new Date(); newSlideDoc.setLanguage(""); newSlideDoc.setCreationDate(creationDate); newSlideDoc.setContentUpdateDate(creationDate); newSlideDoc.setDate(creationDate); newSlideDoc.setCreator(getContext().getUser()); newSlideDoc.setAuthor(getContext().getUser()); newSlideDoc.setTranslation(0); String imgURL = getAttURLCmd().getAttachmentURL(attFullName, getContext()); String resizeParam = "celwidth=" + getPhotoAlbumMaxWidth(galleryDocRef) + "&celheight=" + getPhotoAlbumMaxHeight(galleryDocRef); newSlideDoc.setContent("<img src=\"" + imgURL + "?" + resizeParam + "\"/>"); getContext().getWiki().saveDocument(newSlideDoc, "add default image slide" + " content", true, getContext()); return true; } else { LOGGER.warn("failed to copy slideTemplateRef [" + slideTemplateRef + "] to new slide doc [" + newSlideDocRef + "]."); } } catch (NoGalleryDocumentException exp) { LOGGER.error("failed to addSlideFromTemplate because no gallery doc.", exp); } catch (XWikiException exp) { LOGGER.error("failed to addSlideFromTemplate.", exp); } return false; }
public boolean addSlideFromTemplate(DocumentReference galleryDocRef, String slideBaseName, String attFullName) { try { DocumentReference slideTemplateRef = getImageSlideTemplateRef(); String gallerySpaceName = getPhotoAlbumSpaceRef(galleryDocRef).getName(); DocumentReference newSlideDocRef = getNextFreeDocNameCmd().getNextTitledPageDocRef( gallerySpaceName, slideBaseName, getContext()); if (getContext().getWiki().copyDocument(slideTemplateRef, newSlideDocRef, true, getContext())) { XWikiDocument newSlideDoc = getContext().getWiki().getDocument(newSlideDocRef, getContext()); newSlideDoc.setDefaultLanguage(webUtilsService.getDefaultLanguage( gallerySpaceName)); Date creationDate = new Date(); newSlideDoc.setLanguage(""); newSlideDoc.setCreationDate(creationDate); newSlideDoc.setContentUpdateDate(creationDate); newSlideDoc.setDate(creationDate); newSlideDoc.setCreator(getContext().getUser()); newSlideDoc.setAuthor(getContext().getUser()); newSlideDoc.setTranslation(0); String imgURL = getAttURLCmd().getAttachmentURL(attFullName, "download", getContext()); String resizeParam = "celwidth=" + getPhotoAlbumMaxWidth(galleryDocRef) + "&celheight=" + getPhotoAlbumMaxHeight(galleryDocRef); String fullImgURL = imgURL + ((imgURL.indexOf("?") < 0)?"?":"&") + resizeParam; newSlideDoc.setContent("<img src=\"" + fullImgURL + "\"/>"); getContext().getWiki().saveDocument(newSlideDoc, "add default image slide" + " content", true, getContext()); return true; } else { LOGGER.warn("failed to copy slideTemplateRef [" + slideTemplateRef + "] to new slide doc [" + newSlideDocRef + "]."); } } catch (NoGalleryDocumentException exp) { LOGGER.error("failed to addSlideFromTemplate because no gallery doc.", exp); } catch (XWikiException exp) { LOGGER.error("failed to addSlideFromTemplate.", exp); } return false; }
diff --git a/src/frontend/edu/brown/hstore/PartitionExecutor.java b/src/frontend/edu/brown/hstore/PartitionExecutor.java index 4beba6e61..bb9abb211 100644 --- a/src/frontend/edu/brown/hstore/PartitionExecutor.java +++ b/src/frontend/edu/brown/hstore/PartitionExecutor.java @@ -1,5150 +1,5150 @@ /*************************************************************************** * Copyright (C) 2013 by H-Store Project * * Brown University * * Massachusetts Institute of Technology * * Yale University * * * * 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 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. * ***************************************************************************/ /* This file is part of VoltDB. * Copyright (C) 2008-2010 VoltDB L.L.C. * * VoltDB is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VoltDB is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package edu.brown.hstore; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.concurrent.BlockingDeque; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import org.voltdb.BackendTarget; import org.voltdb.CatalogContext; import org.voltdb.ClientResponseImpl; import org.voltdb.DependencySet; import org.voltdb.HsqlBackend; import org.voltdb.MemoryStats; import org.voltdb.ParameterSet; import org.voltdb.SQLStmt; import org.voltdb.SnapshotSiteProcessor; import org.voltdb.SnapshotSiteProcessor.SnapshotTableTask; import org.voltdb.SysProcSelector; import org.voltdb.VoltProcedure; import org.voltdb.VoltProcedure.VoltAbortException; import org.voltdb.VoltSystemProcedure; import org.voltdb.VoltTable; import org.voltdb.catalog.Catalog; import org.voltdb.catalog.Cluster; import org.voltdb.catalog.Database; import org.voltdb.catalog.Host; import org.voltdb.catalog.Partition; import org.voltdb.catalog.PlanFragment; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.Site; import org.voltdb.catalog.Statement; import org.voltdb.catalog.Table; import org.voltdb.exceptions.ConstraintFailureException; import org.voltdb.exceptions.EEException; import org.voltdb.exceptions.EvictedTupleAccessException; import org.voltdb.exceptions.MispredictionException; import org.voltdb.exceptions.SQLException; import org.voltdb.exceptions.SerializableException; import org.voltdb.exceptions.ServerFaultException; import org.voltdb.jni.ExecutionEngine; import org.voltdb.jni.ExecutionEngineIPC; import org.voltdb.jni.ExecutionEngineJNI; import org.voltdb.jni.MockExecutionEngine; import org.voltdb.messaging.FastDeserializer; import org.voltdb.messaging.FastSerializer; import org.voltdb.types.SpecExecSchedulerPolicyType; import org.voltdb.types.SpeculationConflictCheckerType; import org.voltdb.types.SpeculationType; import org.voltdb.utils.DBBPool; import org.voltdb.utils.DBBPool.BBContainer; import org.voltdb.utils.Encoder; import org.voltdb.utils.EstTime; import org.voltdb.utils.Pair; import com.google.protobuf.ByteString; import com.google.protobuf.RpcCallback; import edu.brown.catalog.CatalogUtil; import edu.brown.catalog.PlanFragmentIdGenerator; import edu.brown.catalog.special.CountedStatement; import edu.brown.hstore.Hstoreservice.QueryEstimate; import edu.brown.hstore.Hstoreservice.Status; import edu.brown.hstore.Hstoreservice.TransactionPrefetchResult; import edu.brown.hstore.Hstoreservice.TransactionWorkRequest; import edu.brown.hstore.Hstoreservice.TransactionWorkResponse; import edu.brown.hstore.Hstoreservice.WorkFragment; import edu.brown.hstore.Hstoreservice.WorkResult; import edu.brown.hstore.callbacks.LocalFinishCallback; import edu.brown.hstore.callbacks.LocalPrepareCallback; import edu.brown.hstore.callbacks.PartitionCountingCallback; import edu.brown.hstore.callbacks.TransactionCallback; import edu.brown.hstore.conf.HStoreConf; import edu.brown.hstore.estimators.Estimate; import edu.brown.hstore.estimators.EstimatorState; import edu.brown.hstore.estimators.EstimatorUtil; import edu.brown.hstore.estimators.TransactionEstimator; import edu.brown.hstore.internal.DeferredQueryMessage; import edu.brown.hstore.internal.FinishTxnMessage; import edu.brown.hstore.internal.InitializeRequestMessage; import edu.brown.hstore.internal.InitializeTxnMessage; import edu.brown.hstore.internal.InternalMessage; import edu.brown.hstore.internal.InternalTxnMessage; import edu.brown.hstore.internal.PotentialSnapshotWorkMessage; import edu.brown.hstore.internal.PrepareTxnMessage; import edu.brown.hstore.internal.SetDistributedTxnMessage; import edu.brown.hstore.internal.StartTxnMessage; import edu.brown.hstore.internal.UtilityWorkMessage; import edu.brown.hstore.internal.UtilityWorkMessage.TableStatsRequestMessage; import edu.brown.hstore.internal.UtilityWorkMessage.UpdateMemoryMessage; import edu.brown.hstore.internal.WorkFragmentMessage; import edu.brown.hstore.specexec.QueryTracker; import edu.brown.hstore.specexec.checkers.AbstractConflictChecker; import edu.brown.hstore.specexec.checkers.MarkovConflictChecker; import edu.brown.hstore.specexec.checkers.OptimisticConflictChecker; import edu.brown.hstore.specexec.checkers.TableConflictChecker; import edu.brown.hstore.specexec.checkers.UnsafeConflictChecker; import edu.brown.hstore.txns.AbstractTransaction; import edu.brown.hstore.txns.DependencyTracker; import edu.brown.hstore.txns.ExecutionState; import edu.brown.hstore.txns.LocalTransaction; import edu.brown.hstore.txns.MapReduceTransaction; import edu.brown.hstore.txns.PrefetchState; import edu.brown.hstore.txns.RemoteTransaction; import edu.brown.hstore.util.ArrayCache.IntArrayCache; import edu.brown.hstore.util.ArrayCache.LongArrayCache; import edu.brown.hstore.util.ParameterSetArrayCache; import edu.brown.hstore.util.TransactionCounter; import edu.brown.hstore.util.TransactionWorkRequestBuilder; import edu.brown.interfaces.Configurable; import edu.brown.interfaces.DebugContext; import edu.brown.interfaces.Shutdownable; import edu.brown.logging.LoggerUtil; import edu.brown.logging.LoggerUtil.LoggerBoolean; import edu.brown.markov.EstimationThresholds; import edu.brown.profilers.PartitionExecutorProfiler; import edu.brown.statistics.FastIntHistogram; import edu.brown.utils.ClassUtil; import edu.brown.utils.CollectionUtil; import edu.brown.utils.EventObservable; import edu.brown.utils.EventObserver; import edu.brown.utils.PartitionEstimator; import edu.brown.utils.PartitionSet; import edu.brown.utils.StringBoxUtil; import edu.brown.utils.StringUtil; /** * The main executor of transactional work in the system for a single partition. * Controls running stored procedures and manages the execution engine's running of plan * fragments. Interacts with the DTXN system to get work to do. The thread might * do other things, but this is where the good stuff happens. */ public class PartitionExecutor implements Runnable, Configurable, Shutdownable { private static final Logger LOG = Logger.getLogger(PartitionExecutor.class); private static final LoggerBoolean debug = new LoggerBoolean(LOG.isDebugEnabled()); private static final LoggerBoolean trace = new LoggerBoolean(LOG.isTraceEnabled()); static { LoggerUtil.attachObserver(LOG, debug, trace); } private static final long WORK_QUEUE_POLL_TIME = 10; // 0.5 milliseconds private static final TimeUnit WORK_QUEUE_POLL_TIMEUNIT = TimeUnit.MICROSECONDS; private static final UtilityWorkMessage UTIL_WORK_MSG = new UtilityWorkMessage(); private static final UpdateMemoryMessage STATS_WORK_MSG = new UpdateMemoryMessage(); // ---------------------------------------------------------------------------- // INTERNAL EXECUTION STATE // ---------------------------------------------------------------------------- /** * The current execution mode for this PartitionExecutor * This defines what level of speculative execution we have enabled. */ public enum ExecutionMode { /** * Disable processing all transactions until told otherwise. * We will still accept new ones */ DISABLED, /** * Reject any transaction that tries to get added */ DISABLED_REJECT, /** * No speculative execution. All transactions are committed immediately */ COMMIT_ALL, /** * Allow read-only txns to return results. */ COMMIT_READONLY, /** * Allow non-conflicting txns to return results. */ COMMIT_NONCONFLICTING, /** * All txn responses must wait until the current distributed txn is committed */ COMMIT_NONE, }; // ---------------------------------------------------------------------------- // DATA MEMBERS // ---------------------------------------------------------------------------- private Thread self; /** * If this flag is enabled, then we need to shut ourselves down and stop running txns */ private ShutdownState shutdown_state = Shutdownable.ShutdownState.INITIALIZED; private Semaphore shutdown_latch; /** * Catalog objects */ protected final CatalogContext catalogContext; protected Site site; protected int siteId; private Partition partition; private int partitionId; private final BackendTarget backend_target; private final ExecutionEngine ee; private final HsqlBackend hsql; private final DBBPool buffer_pool = new DBBPool(false, false); private final FastSerializer fs = new FastSerializer(this.buffer_pool); /** * The PartitionEstimator is what we use to figure our what partitions each * query invocation needs to be sent to at run time. * It is deterministic. */ private final PartitionEstimator p_estimator; /** * The TransactionEstimator is the runtime piece that we use to keep track of * where a locally running transaction is in its execution workflow. This allows * us to make predictions about what kind of things we expect the xact to do in * the future */ private final TransactionEstimator localTxnEstimator; private EstimationThresholds thresholds = EstimationThresholds.factory(); // Each execution site manages snapshot using a SnapshotSiteProcessor private final SnapshotSiteProcessor m_snapshotter; /** * ProcedureId -> Queue<VoltProcedure> */ private final Queue<VoltProcedure>[] procedures; // ---------------------------------------------------------------------------- // H-Store Transaction Stuff // ---------------------------------------------------------------------------- private HStoreSite hstore_site; private HStoreCoordinator hstore_coordinator; private HStoreConf hstore_conf; private TransactionInitializer txnInitializer; private TransactionQueueManager queueManager; private PartitionLockQueue lockQueue; private DependencyTracker depTracker; // ---------------------------------------------------------------------------- // Work Queue // ---------------------------------------------------------------------------- /** * This is the queue of the list of things that we need to execute. * The entries may be either InitiateTaskMessages (i.e., start a stored procedure) or * WorkFragment (i.e., execute some fragments on behalf of another transaction) * We will use this special wrapper around the PartitionExecutorQueue that can determine * whether this partition is overloaded and therefore new requests should be throttled */ private final PartitionMessageQueue work_queue; // ---------------------------------------------------------------------------- // Internal Execution State // ---------------------------------------------------------------------------- /** * The transaction id of the current transaction * This is mostly used for testing and should not be relied on from the outside. */ private Long currentTxnId = null; /** * We can only have one active "parent" transaction at a time. * We can speculatively execute other transactions out of order, but the active parent * transaction will always be the same. */ private AbstractTransaction currentTxn; /** * We can only have one active distributed transactions at a time. * The multi-partition TransactionState that is currently executing at this partition * When we get the response for these txn, we know we can commit/abort the speculatively executed transactions */ private AbstractTransaction currentDtxn = null; private String lastDtxnDebug = null; /** * The current VoltProcedure handle that is executing at this partition * This will be set to null as soon as the VoltProcedure.run() method completes */ private VoltProcedure currentVoltProc = null; /** * List of messages that are blocked waiting for the outstanding dtxn to commit */ private final List<InternalMessage> currentBlockedTxns = new ArrayList<InternalMessage>(); /** * The current ExecutionMode. This defines when transactions are allowed to execute * and whether they can return their results to the client immediately or whether they * must wait until the current_dtxn commits. */ private ExecutionMode currentExecMode = ExecutionMode.COMMIT_ALL; /** * The time in ms since epoch of the last call to ExecutionEngine.tick(...) */ private long lastTickTime = 0; /** * The time in ms since last stats update */ private long lastStatsTime = 0; /** * The last txn id that we executed (either local or remote) */ private volatile Long lastExecutedTxnId = null; /** * The last txn id that we committed */ private volatile Long lastCommittedTxnId = Long.valueOf(-1l); /** * The last undoToken that we handed out */ private long lastUndoToken = 0l; /** * The last undoToken that we committed at this partition */ private long lastCommittedUndoToken = -1l; // ---------------------------------------------------------------------------- // SPECULATIVE EXECUTION STATE // ---------------------------------------------------------------------------- private SpeculationConflictCheckerType specExecCheckerType; private AbstractConflictChecker specExecChecker; private SpecExecScheduler specExecScheduler; /** * ClientResponses from speculatively executed transactions that were executed * before or after the current distributed transaction finished at this partition and are * now waiting to be committed. */ private final LinkedList<Pair<LocalTransaction, ClientResponseImpl>> specExecBlocked; /** * If this flag is set to true, that means some txn has modified the database * in the current batch of speculatively executed txns. Any read-only specexec txn that * is executed when this flag is set to false can be returned to the client immediately. * TODO: This should really be a bitmap of table ids so that we have finer grain control */ private boolean specExecModified; /** * If set to true, then we should not check for speculative execution candidates * at run time. This needs to be set any time we change the currentDtxn */ private boolean specExecIgnoreCurrent = false; // ---------------------------------------------------------------------------- // SHARED VOLTPROCEDURE DATA MEMBERS // ---------------------------------------------------------------------------- /** * This is the execution state for a running transaction. * We have a circular queue so that we can reuse them for speculatively execute txns */ private final Queue<ExecutionState> execStates = new LinkedList<ExecutionState>(); /** * Mapping from SQLStmt batch hash codes (computed by VoltProcedure.getBatchHashCode()) to BatchPlanners * The idea is that we can quickly derived the partitions for each unique set of SQLStmt list */ private final Map<Integer, BatchPlanner> batchPlanners = new HashMap<Integer, BatchPlanner>(100); // ---------------------------------------------------------------------------- // DISTRIBUTED TRANSACTION TEMPORARY DATA COLLECTIONS // ---------------------------------------------------------------------------- /** * WorkFragments that we need to send to a remote HStoreSite for execution */ private final List<WorkFragment.Builder> tmp_remoteFragmentBuilders = new ArrayList<WorkFragment.Builder>(); /** * WorkFragments that we need to send to our own PartitionExecutor */ private final List<WorkFragment.Builder> tmp_localWorkFragmentBuilders = new ArrayList<WorkFragment.Builder>(); /** * WorkFragments that we need to send to a different PartitionExecutor that is on this same HStoreSite */ private final List<WorkFragment.Builder> tmp_localSiteFragmentBuilders = new ArrayList<WorkFragment.Builder>(); /** * Temporary space used when calling removeInternalDependencies() */ private final HashMap<Integer, List<VoltTable>> tmp_removeDependenciesMap = new HashMap<Integer, List<VoltTable>>(); /** * Remote SiteId -> TransactionWorkRequest.Builder */ private final TransactionWorkRequestBuilder tmp_transactionRequestBuilders[]; /** * PartitionId -> List<VoltTable> */ private final Map<Integer, List<VoltTable>> tmp_EEdependencies = new HashMap<Integer, List<VoltTable>>(); /** * List of serialized ParameterSets */ private final List<ByteString> tmp_serializedParams = new ArrayList<ByteString>(); /** * Histogram for the number of WorkFragments that we're going to send to partitions * in the current batch. */ private final FastIntHistogram tmp_fragmentsPerPartition = new FastIntHistogram(true); /** * Reusable int array for StmtCounters */ private final IntArrayCache tmp_stmtCounters = new IntArrayCache(10); /** * Reusable ParameterSet array cache for WorkFragments */ private final ParameterSetArrayCache tmp_fragmentParams = new ParameterSetArrayCache(5); /** * Reusable long array for fragment ids */ private final LongArrayCache tmp_fragmentIds = new LongArrayCache(10); /** * Reusable long array for fragment id offsets */ private final IntArrayCache tmp_fragmentOffsets = new IntArrayCache(10); /** * Reusable int array for output dependency ids */ private final IntArrayCache tmp_outputDepIds = new IntArrayCache(10); /** * Reusable int array for input dependency ids */ private final IntArrayCache tmp_inputDepIds = new IntArrayCache(10); /** * The following three arrays are used by utilityWork() to create transactions * for deferred queries */ private final SQLStmt[] tmp_def_stmt = new SQLStmt[1]; private final ParameterSet[] tmp_def_params = new ParameterSet[1]; private LocalTransaction tmp_def_txn; // ---------------------------------------------------------------------------- // INTERNAL CLASSES // ---------------------------------------------------------------------------- private class DonePartitionsNotification { /** * All of the partitions that a transaction is currently done with. */ private final PartitionSet donePartitions = new PartitionSet(); /** * RemoteSiteId -> Partitions that we need to notify that this txn is done with. */ private PartitionSet[] notificationsPerSite; /** * Site ids that we need to notify separately about the done partitions. */ private Collection<Integer> _sitesToNotify; public void addSiteNotification(Site remoteSite, int partitionId, boolean noQueriesInBatch) { int remoteSiteId = remoteSite.getId(); if (this.notificationsPerSite == null) { this.notificationsPerSite = new PartitionSet[catalogContext.numberOfSites]; } if (this.notificationsPerSite[remoteSiteId] == null) { this.notificationsPerSite[remoteSiteId] = new PartitionSet(); } this.notificationsPerSite[remoteSiteId].add(partitionId); if (noQueriesInBatch) { if (this._sitesToNotify == null) { this._sitesToNotify = new HashSet<Integer>(); } this._sitesToNotify.add(Integer.valueOf(remoteSiteId)); } } /** * Return the set of partitions that needed to be notified separately * for the given site id. The return value may be null. * @param remoteSiteId * @return */ public PartitionSet getNotifications(int remoteSiteId) { if (this.notificationsPerSite != null) { return (this.notificationsPerSite[remoteSiteId]); } return (null); } public boolean hasSitesToNotify() { return (this._sitesToNotify != null && this._sitesToNotify.isEmpty() == false); } } // ---------------------------------------------------------------------------- // PROFILING OBJECTS // ---------------------------------------------------------------------------- private final PartitionExecutorProfiler profiler = new PartitionExecutorProfiler(); // ---------------------------------------------------------------------------- // WORK REQUEST CALLBACK // ---------------------------------------------------------------------------- /** * This will be invoked for each TransactionWorkResponse that comes back from * the remote HStoreSites. Note that we don't need to do any counting as to whether * a transaction has gotten back all of the responses that it expected. That logic is down * below in waitForResponses() */ private final RpcCallback<TransactionWorkResponse> request_work_callback = new RpcCallback<TransactionWorkResponse>() { @Override public void run(TransactionWorkResponse msg) { Long txn_id = msg.getTransactionId(); LocalTransaction ts = hstore_site.getTransaction(txn_id); // We can ignore anything that comes in for a transaction that we don't know about if (ts == null) { if (debug.val) LOG.debug("No transaction state exists for txn #" + txn_id); return; } if (debug.val) LOG.debug(String.format("Processing TransactionWorkResponse for %s with %d results%s", ts, msg.getResultsCount(), (trace.val ? "\n"+msg : ""))); for (int i = 0, cnt = msg.getResultsCount(); i < cnt; i++) { WorkResult result = msg.getResults(i); if (debug.val) LOG.debug(String.format("Got %s from partition %d for %s", result.getClass().getSimpleName(), result.getPartitionId(), ts)); PartitionExecutor.this.processWorkResult(ts, result); } // FOR if (hstore_conf.site.specexec_enable) { specExecScheduler.interruptSearch(UTIL_WORK_MSG); } } }; // END CLASS // ---------------------------------------------------------------------------- // SYSPROC STUFF // ---------------------------------------------------------------------------- // Associate the system procedure planfragment ids to wrappers. // Planfragments are registered when the procedure wrapper is init()'d. private final Map<Long, VoltSystemProcedure> m_registeredSysProcPlanFragments = new HashMap<Long, VoltSystemProcedure>(); public void registerPlanFragment(final long pfId, final VoltSystemProcedure proc) { synchronized (m_registeredSysProcPlanFragments) { if (!m_registeredSysProcPlanFragments.containsKey(pfId)) { assert(m_registeredSysProcPlanFragments.containsKey(pfId) == false) : "Trying to register the same sysproc more than once: " + pfId; m_registeredSysProcPlanFragments.put(pfId, proc); if (trace.val) LOG.trace(String.format("Registered %s sysproc handle at partition %d for FragmentId #%d", VoltSystemProcedure.procCallName(proc.getClass()), partitionId, pfId)); } } // SYNCH } /** * SystemProcedures are "friends" with PartitionExecutors and granted * access to internal state via m_systemProcedureContext. * access to internal state via m_systemProcedureContext. */ public interface SystemProcedureExecutionContext { public Catalog getCatalog(); public Database getDatabase(); public Cluster getCluster(); public Site getSite(); public Host getHost(); public ExecutionEngine getExecutionEngine(); public long getLastCommittedTxnId(); public PartitionExecutor getPartitionExecutor(); public HStoreSite getHStoreSite(); public Long getCurrentTxnId(); } protected class SystemProcedureContext implements SystemProcedureExecutionContext { public Catalog getCatalog() { return catalogContext.catalog; } public Database getDatabase() { return catalogContext.database; } public Cluster getCluster() { return catalogContext.cluster; } public Site getSite() { return site; } public Host getHost() { return site.getHost(); } public ExecutionEngine getExecutionEngine() { return ee; } public long getLastCommittedTxnId() { return lastCommittedTxnId; } public PartitionExecutor getPartitionExecutor() { return PartitionExecutor.this; } public HStoreSite getHStoreSite() { return hstore_site; } public Long getCurrentTxnId() { return PartitionExecutor.this.currentTxnId; } } private final SystemProcedureContext m_systemProcedureContext = new SystemProcedureContext(); // ---------------------------------------------------------------------------- // INITIALIZATION // ---------------------------------------------------------------------------- /** * Dummy constructor... */ protected PartitionExecutor() { this.catalogContext = null; this.work_queue = null; this.ee = null; this.hsql = null; this.specExecChecker = null; this.specExecScheduler = null; this.specExecBlocked = null; this.p_estimator = null; this.localTxnEstimator = null; this.m_snapshotter = null; this.thresholds = null; this.site = null; this.backend_target = BackendTarget.HSQLDB_BACKEND; this.siteId = 0; this.partitionId = 0; this.procedures = null; this.tmp_transactionRequestBuilders = null; } /** * Initialize the StoredProcedure runner and EE for this Site. * @param partitionId * @param t_estimator * @param coordinator * @param siteManager * @param serializedCatalog A list of catalog commands, separated by * newlines that, when executed, reconstruct the complete m_catalog. */ public PartitionExecutor(final int partitionId, final CatalogContext catalogContext, final BackendTarget target, final PartitionEstimator p_estimator, final TransactionEstimator t_estimator) { this.hstore_conf = HStoreConf.singleton(); this.work_queue = new PartitionMessageQueue(); this.backend_target = target; this.catalogContext = catalogContext; this.partition = catalogContext.getPartitionById(partitionId); assert(this.partition != null) : "Invalid Partition #" + partitionId; this.partitionId = this.partition.getId(); this.site = this.partition.getParent(); assert(site != null) : "Unable to get Site for Partition #" + partitionId; this.siteId = this.site.getId(); this.lastUndoToken = this.partitionId * 1000000; this.p_estimator = p_estimator; this.localTxnEstimator = t_estimator; // Speculative Execution this.specExecBlocked = new LinkedList<Pair<LocalTransaction,ClientResponseImpl>>(); this.specExecModified = false; // VoltProcedure Queues @SuppressWarnings("unchecked") Queue<VoltProcedure> voltProcQueues[] = new Queue[catalogContext.procedures.size()+1]; this.procedures = voltProcQueues; // An execution site can be backed by HSQLDB, by volt's EE accessed // via JNI or by volt's EE accessed via IPC. When backed by HSQLDB, // the VoltProcedure interface invokes HSQLDB directly through its // hsql Backend member variable. The real volt backend is encapsulated // by the ExecutionEngine class. This class has implementations for both // JNI and IPC - and selects the desired implementation based on the // value of this.eeBackend. HsqlBackend hsqlTemp = null; ExecutionEngine eeTemp = null; SnapshotSiteProcessor snapshotter = null; try { if (trace.val) LOG.trace("Creating EE wrapper with target type '" + target + "'"); if (this.backend_target == BackendTarget.HSQLDB_BACKEND) { hsqlTemp = new HsqlBackend(partitionId); final String hexDDL = catalogContext.database.getSchema(); final String ddl = Encoder.hexDecodeToString(hexDDL); final String[] commands = ddl.split(";"); for (String command : commands) { if (command.length() == 0) { continue; } hsqlTemp.runDDL(command); } eeTemp = new MockExecutionEngine(); } else if (target == BackendTarget.NATIVE_EE_JNI) { org.voltdb.EELibraryLoader.loadExecutionEngineLibrary(true); // set up the EE eeTemp = new ExecutionEngineJNI(this, catalogContext.cluster.getRelativeIndex(), this.getSiteId(), this.getPartitionId(), this.site.getHost().getId(), "localhost"); // Initialize Anti-Cache if (hstore_conf.site.anticache_enable) { File acFile = AntiCacheManager.getDatabaseDir(this); long blockSize = hstore_conf.site.anticache_block_size; eeTemp.antiCacheInitialize(acFile, blockSize); } eeTemp.loadCatalog(catalogContext.catalog.serialize()); this.lastTickTime = System.currentTimeMillis(); eeTemp.tick(this.lastTickTime, 0); snapshotter = new SnapshotSiteProcessor(new Runnable() { final PotentialSnapshotWorkMessage msg = new PotentialSnapshotWorkMessage(); @Override public void run() { PartitionExecutor.this.work_queue.add(this.msg); } }); } else { // set up the EE over IPC eeTemp = new ExecutionEngineIPC(this, catalogContext.cluster.getRelativeIndex(), this.getSiteId(), this.getPartitionId(), this.site.getHost().getId(), "localhost", target); eeTemp.loadCatalog(catalogContext.catalog.serialize()); this.lastTickTime = System.currentTimeMillis(); eeTemp.tick(this.lastTickTime, 0); } } // just print error info an bail if we run into an error here catch (final Exception ex) { throw new ServerFaultException("Failed to initialize PartitionExecutor", ex); } this.ee = eeTemp; this.hsql = hsqlTemp; m_snapshotter = snapshotter; assert(this.ee != null); assert(!(this.ee == null && this.hsql == null)) : "Both execution engine objects are empty. This should never happen"; // Initialize temporary data structures int num_sites = this.catalogContext.numberOfSites; this.tmp_transactionRequestBuilders = new TransactionWorkRequestBuilder[num_sites]; } /** * Link this PartitionExecutor with its parent HStoreSite * This will initialize the references the various components shared among the PartitionExecutors * @param hstore_site */ public void initHStoreSite(HStoreSite hstore_site) { if (trace.val) LOG.trace(String.format("Initializing HStoreSite components at partition %d", this.partitionId)); assert(this.hstore_site == null) : String.format("Trying to initialize HStoreSite for PartitionExecutor #%d twice!", this.partitionId); this.hstore_site = hstore_site; this.depTracker = hstore_site.getDependencyTracker(this.partitionId); this.thresholds = hstore_site.getThresholds(); this.txnInitializer = hstore_site.getTransactionInitializer(); this.queueManager = hstore_site.getTransactionQueueManager(); this.lockQueue = this.queueManager.getLockQueue(this.partitionId); if (hstore_conf.site.exec_deferrable_queries) { tmp_def_txn = new LocalTransaction(hstore_site); } // ------------------------------- // BENCHMARK START NOTIFICATIONS // ------------------------------- // Poke ourselves to update the partition stats when the first // non-sysproc procedure shows up. I forget why we need to do this... EventObservable<HStoreSite> observable = this.hstore_site.getStartWorkloadObservable(); observable.addObserver(new EventObserver<HStoreSite>() { @Override public void update(EventObservable<HStoreSite> o, HStoreSite arg) { queueUtilityWork(STATS_WORK_MSG); } }); // Reset our profiling information when we get the first non-sysproc this.profiler.resetOnEventObservable(observable); // Initialize speculative execution scheduler this.initSpecExecScheduler(); } /** * Initialize this PartitionExecutor' speculative execution scheduler */ private void initSpecExecScheduler() { assert(this.specExecScheduler == null); assert(this.hstore_site != null); this.specExecCheckerType = SpeculationConflictCheckerType.get(hstore_conf.site.specexec_scheduler_checker); switch (this.specExecCheckerType) { // ------------------------------- // ROW-LEVEL // ------------------------------- case MARKOV: // The MarkovConflictChecker is thread-safe, so we all of the partitions // at this site can reuse the same one. this.specExecChecker = MarkovConflictChecker.singleton(this.catalogContext, this.thresholds); break; // ------------------------------- // TABLE-LEVEL // ------------------------------- case TABLE: this.specExecChecker = new TableConflictChecker(this.catalogContext); break; // ------------------------------- // UNSAFE // NOTE: You probably don't want to use this! // ------------------------------- case UNSAFE: this.specExecChecker = new UnsafeConflictChecker(this.catalogContext, hstore_conf.site.specexec_unsafe_limit); LOG.warn(String.format("Using %s in the %s for partition %d. This is a bad idea!", this.specExecChecker.getClass().getSimpleName(), this.getClass().getSimpleName(), this.partitionId)); break; // ------------------------------- // OPTIMISTIC // ------------------------------- case OPTIMISTIC: this.specExecChecker = new OptimisticConflictChecker(this.catalogContext, this.ee); break; // BUSTED! default: { String msg = String.format("Invalid %s '%s'", SpeculationConflictCheckerType.class.getSimpleName(), hstore_conf.site.specexec_scheduler_checker); throw new RuntimeException(msg); } } // SWITCH SpecExecSchedulerPolicyType policy = SpecExecSchedulerPolicyType.get(hstore_conf.site.specexec_scheduler_policy); assert(policy != null) : String.format("Invalid %s '%s'", SpecExecSchedulerPolicyType.class.getSimpleName(), hstore_conf.site.specexec_scheduler_policy); assert(this.lockQueue.getPartitionId() == this.partitionId); this.specExecScheduler = new SpecExecScheduler(this.specExecChecker, this.partitionId, this.lockQueue, policy, hstore_conf.site.specexec_scheduler_window); this.specExecChecker.setEstimationThresholds(this.thresholds); this.specExecScheduler.updateConf(hstore_conf, null); if (debug.val && hstore_conf.site.specexec_enable) LOG.debug(String.format("Initialized %s for partition %d [checker=%s, policy=%s]", this.specExecScheduler.getClass().getSimpleName(), this.partitionId, this.specExecChecker.getClass().getSimpleName(), policy)); } private ExecutionState initExecutionState() { ExecutionState state = this.execStates.poll(); if (state == null) { state = new ExecutionState(this); } return (state); } @Override public void updateConf(HStoreConf hstore_conf, String[] changed) { if (this.specExecScheduler != null) { this.specExecScheduler.updateConf(hstore_conf, changed); } } // ---------------------------------------------------------------------------- // MAIN EXECUTION LOOP // ---------------------------------------------------------------------------- /** * Primary run method that is invoked a single time when the thread is started. * Has the opportunity to do startup config. */ @Override public final void run() { if (this.hstore_site == null) { String msg = String.format("Trying to start %s for partition %d before its HStoreSite was initialized", this.getClass().getSimpleName(), this.partitionId); throw new RuntimeException(msg); } else if (this.self != null) { String msg = String.format("Trying to restart %s for partition %d after it was already running", this.getClass().getSimpleName(), this.partitionId); throw new RuntimeException(msg); } // Initialize all of our VoltProcedures handles // This needs to be done here so that the Workload trace handles can be // set up properly this.initializeVoltProcedures(); this.self = Thread.currentThread(); this.self.setName(HStoreThreadManager.getThreadName(this.hstore_site, this.partitionId)); this.hstore_coordinator = hstore_site.getCoordinator(); this.hstore_site.getThreadManager().registerEEThread(partition); this.shutdown_latch = new Semaphore(0); this.shutdown_state = ShutdownState.STARTED; if (hstore_conf.site.exec_profiling) profiler.start_time = System.currentTimeMillis(); assert(this.hstore_site != null); assert(this.hstore_coordinator != null); assert(this.specExecScheduler != null); assert(this.queueManager != null); // *********************************** DEBUG *********************************** if (hstore_conf.site.exec_validate_work) { LOG.warn("Enabled Distributed Transaction Validation Checker"); } // *********************************** DEBUG *********************************** // Things that we will need in the loop below InternalMessage nextWork = null; AbstractTransaction nextTxn = null; if (debug.val) LOG.debug("Starting PartitionExecutor run loop..."); try { while (this.shutdown_state == ShutdownState.STARTED) { this.currentTxnId = null; nextTxn = null; nextWork = null; // This is the starting state of the PartitionExecutor. // At this point here we currently don't have a txn to execute nor // are we involved in a distributed txn running at another partition. // So we need to go our PartitionLockQueue and get back the next // txn that will have our lock. if (this.currentDtxn == null) { this.tick(); if (hstore_conf.site.exec_profiling) profiler.poll_time.start(); try { nextTxn = this.queueManager.checkLockQueue(this.partitionId); // NON-BLOCKING } finally { if (hstore_conf.site.exec_profiling) profiler.poll_time.stopIfStarted(); } // If we get something back here, then it should become our current transaction. if (nextTxn != null) { // If it's a single-partition txn, then we can return the StartTxnMessage // so that we can fire it off right away. if (nextTxn.isPredictSinglePartition()) { LocalTransaction localTxn = (LocalTransaction)nextTxn; nextWork = localTxn.getStartTxnMessage(); if (hstore_conf.site.txn_profiling && localTxn.profiler != null) localTxn.profiler.startQueueExec(); } // If it's as distribued txn, then we'll want to just set it as our // current dtxn at this partition and then keep checking the queue // for more work. else { this.setCurrentDtxn(nextTxn); } } } // ------------------------------- // Poll Work Queue // ------------------------------- // Check if we have anything to do right now if (nextWork == null) { if (hstore_conf.site.exec_profiling) profiler.idle_time.start(); try { // If we're allowed to speculatively execute txns, then we don't want to have // to wait to see if anything will show up in our work queue. if (hstore_conf.site.specexec_enable && this.lockQueue.approximateIsEmpty() == false) { nextWork = this.work_queue.poll(); } else { nextWork = this.work_queue.poll(WORK_QUEUE_POLL_TIME, WORK_QUEUE_POLL_TIMEUNIT); } } catch (InterruptedException ex) { continue; } finally { if (hstore_conf.site.exec_profiling) profiler.idle_time.stopIfStarted(); } } // ------------------------------- // Process Work // ------------------------------- if (nextWork != null) { if (trace.val) LOG.trace("Next Work: " + nextWork); if (hstore_conf.site.exec_profiling) { profiler.numMessages.put(nextWork.getClass().getSimpleName()); profiler.exec_time.start(); if (this.currentDtxn != null) profiler.sp2_time.stopIfStarted(); } try { this.processInternalMessage(nextWork); } finally { if (hstore_conf.site.exec_profiling) { profiler.exec_time.stopIfStarted(); if (this.currentDtxn != null) profiler.sp2_time.start(); } } if (this.currentTxnId != null) this.lastExecutedTxnId = this.currentTxnId; } // Check if we have any utility work to do while we wait else if (hstore_conf.site.specexec_enable) { // if (trace.val) // LOG.trace(String.format("The %s for partition %s empty. Checking for utility work...", // this.work_queue.getClass().getSimpleName(), this.partitionId)); if (this.utilityWork()) { nextWork = UTIL_WORK_MSG; } } } // WHILE } catch (final Throwable ex) { if (this.isShuttingDown() == false) { // ex.printStackTrace(); LOG.fatal(String.format("Unexpected error at partition %d [current=%s, lastDtxn=%s]", this.partitionId, this.currentTxn, this.lastDtxnDebug), ex); if (this.currentTxn != null) LOG.fatal("TransactionState Dump:\n" + this.currentTxn.debug()); } this.shutdown_latch.release(); this.hstore_coordinator.shutdownClusterBlocking(ex); } finally { if (debug.val) { String txnDebug = ""; if (this.currentTxn != null && this.currentTxn.getBasePartition() == this.partitionId) { txnDebug = " while a txn is still running\n" + this.currentTxn.debug(); } LOG.warn(String.format("PartitionExecutor %d is stopping%s%s", this.partitionId, (this.currentTxnId != null ? " In-Flight Txn: #" + this.currentTxnId : ""), txnDebug)); } // Release the shutdown latch in case anybody waiting for us this.shutdown_latch.release(); } } /** * Special function that allows us to do some utility work while * we are waiting for a response or something real to do. * Note: this tracks how long the system spends doing utility work. It would * be interesting to have the system report on this before it shuts down. * @return true if there is more utility work that can be done */ private boolean utilityWork() { if (hstore_conf.site.exec_profiling) this.profiler.util_time.start(); // ------------------------------- // Poll Lock Queue // ------------------------------- LocalTransaction specTxn = null; InternalMessage work = null; // Check whether there is something we can speculatively execute right now if (this.specExecIgnoreCurrent == false && this.lockQueue.approximateIsEmpty() == false) { // if (trace.val) // LOG.trace(String.format("Checking %s for something to do at partition %d while %s", // this.specExecScheduler.getClass().getSimpleName(), // this.partitionId, // (this.currentDtxn != null ? "blocked on " + this.currentDtxn : "idle"))); assert(hstore_conf.site.specexec_enable) : "Trying to schedule speculative txn even though it is disabled"; SpeculationType specType = this.calculateSpeculationType(); if (hstore_conf.site.exec_profiling) this.profiler.conflicts_time.start(); try { specTxn = this.specExecScheduler.next(this.currentDtxn, specType); } finally { if (hstore_conf.site.exec_profiling) this.profiler.conflicts_time.stopIfStarted(); } // Because we don't have fine-grained undo support, we are just going // keep all of our speculative execution txn results around if (specTxn != null) { // TODO: What we really want to do is check to see whether we have anything // in our work queue before we go ahead and fire off this txn if (debug.val) { if (this.work_queue.isEmpty() == false) { LOG.warn(String.format("About to speculatively execute %s on partition %d but there " + "are %d messages in the work queue\n%s", specTxn, this.partitionId, this.work_queue.size(), CollectionUtil.first(this.work_queue))); } LOG.debug(String.format("Utility Work found speculative txn to execute on " + "partition %d [%s, specType=%s]", this.partitionId, specTxn, specType)); // IMPORTANT: We need to make sure that we remove this transaction for the lock queue // before we execute it so that we don't try to run it again. // We have to do this now because otherwise we may get the same transaction again assert(this.lockQueue.contains(specTxn.getTransactionId()) == false) : String.format("Failed to remove speculative %s before executing", specTxn); } assert(specTxn.getBasePartition() == this.partitionId) : String.format("Trying to speculatively execute %s at partition %d but its base partition is %d\n%s", specTxn, this.partitionId, specTxn.getBasePartition(), specTxn.debug()); assert(specTxn.isMarkExecuted() == false) : String.format("Trying to speculatively execute %s at partition %d but was already executed\n%s", specTxn, this.partitionId, specTxn.getBasePartition(), specTxn.debug()); assert(specTxn.isSpeculative() == false) : String.format("Trying to speculatively execute %s at partition %d but was already speculative\n%s", specTxn, this.partitionId, specTxn.getBasePartition(), specTxn.debug()); // It's also important that we cancel this txn's init queue callback, otherwise // it will never get cleaned up properly. This is necessary in order to support // sending out client results *before* the dtxn finishes specTxn.getInitCallback().cancel(); // Ok now that that's out of the way, let's run this baby... specTxn.setSpeculative(specType); if (hstore_conf.site.exec_profiling) profiler.specexec_time.start(); try { this.executeTransaction(specTxn); } finally { if (hstore_conf.site.exec_profiling) profiler.specexec_time.stopIfStarted(); } } // else if (trace.val) { // LOG.trace(String.format("%s - No speculative execution candidates found at partition %d [queueSize=%d]", // this.currentDtxn, this.partitionId, this.queueManager.getLockQueue(this.partitionId).size())); // } } // else if (trace.val && this.currentDtxn != null) { // LOG.trace(String.format("%s - Skipping check for speculative execution txns at partition %d " + // "[lockQueue=%d, specExecIgnoreCurrent=%s]", // this.currentDtxn, this.partitionId, this.lockQueue.size(), this.specExecIgnoreCurrent)); // } if (hstore_conf.site.exec_profiling) this.profiler.util_time.stopIfStarted(); return (specTxn != null || work != null); } // ---------------------------------------------------------------------------- // MESSAGE PROCESSING METHODS // ---------------------------------------------------------------------------- /** * Process an InternalMessage * @param work */ private final void processInternalMessage(InternalMessage work) { // ------------------------------- // TRANSACTIONAL WORK // ------------------------------- if (work instanceof InternalTxnMessage) { this.processInternalTxnMessage((InternalTxnMessage)work); } // ------------------------------- // UTILITY WORK // ------------------------------- else if (work instanceof UtilityWorkMessage) { // UPDATE MEMORY STATS if (work instanceof UpdateMemoryMessage) { this.updateMemoryStats(EstTime.currentTimeMillis()); } // TABLE STATS REQUEST else if (work instanceof TableStatsRequestMessage) { TableStatsRequestMessage stats_work = (TableStatsRequestMessage)work; VoltTable results[] = this.ee.getStats(SysProcSelector.TABLE, stats_work.getLocators(), false, EstTime.currentTimeMillis()); assert(results.length == 1); stats_work.getObservable().notifyObservers(results[0]); } else { // IGNORE } } // ------------------------------- // TRANSACTION INITIALIZATION // ------------------------------- else if (work instanceof InitializeRequestMessage) { this.processInitializeRequestMessage((InitializeRequestMessage)work); } // ------------------------------- // DEFERRED QUERIES // ------------------------------- else if (work instanceof DeferredQueryMessage) { DeferredQueryMessage def_work = (DeferredQueryMessage)work; // Set the txnId in our handle to be what the original txn was that // deferred this query. tmp_def_stmt[0] = def_work.getStmt(); tmp_def_params[0] = def_work.getParams(); tmp_def_txn.init(def_work.getTxnId(), -1, // We don't really need the clientHandle EstTime.currentTimeMillis(), this.partitionId, catalogContext.getPartitionSetSingleton(this.partitionId), false, false, tmp_def_stmt[0].getProcedure(), def_work.getParams(), null // We don't need the client callback ); this.executeSQLStmtBatch(tmp_def_txn, 1, tmp_def_stmt, tmp_def_params, false, false); } // ------------------------------- // SNAPSHOT WORK // ------------------------------- else if (work instanceof PotentialSnapshotWorkMessage) { m_snapshotter.doSnapshotWork(ee); } // ------------------------------- // BAD MOJO! // ------------------------------- else { String msg = "Unexpected work message in queue: " + work; throw new ServerFaultException(msg, this.currentTxnId); } } /** * Process an InitializeRequestMessage * @param work */ protected void processInitializeRequestMessage(InitializeRequestMessage work) { LocalTransaction ts = this.txnInitializer.createLocalTransaction( work.getSerializedRequest(), work.getInitiateTime(), work.getClientHandle(), this.partitionId, work.getProcedure(), work.getProcParams(), work.getClientCallback()); // ------------------------------- // SINGLE-PARTITION TRANSACTION // ------------------------------- if (ts.isPredictSinglePartition() && ts.isMapReduce() == false && ts.isSysProc() == false) { if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.startQueueExec(); // If we are in the middle of a distributed txn at this partition, then we can't // just go and fire off this txn. We actually need to use our SpecExecScheduler to // decide whether it is safe to speculatively execute this txn. But the problem is that // the SpecExecScheduler is only examining the work queue when utilityWork() is called // But it will never be called at this point because if we add this txn back to the queue // it will get picked up right away. if (this.currentDtxn != null) { this.blockTransaction(ts); } else { this.executeTransaction(ts); } } // ------------------------------- // DISTRIBUTED TRANSACTION // ------------------------------- else { if (debug.val) LOG.debug(ts + " - Queuing up txn at local HStoreSite for further processing"); this.hstore_site.transactionQueue(ts); } } /** * Process an InternalTxnMessage * @param work */ private void processInternalTxnMessage(InternalTxnMessage work) { AbstractTransaction ts = work.getTransaction(); this.currentTxn = ts; this.currentTxnId = ts.getTransactionId(); // If this transaction has already been aborted and they are trying to give us // something that isn't a FinishTaskMessage, then we won't bother processing it if (ts.isAborted() && (work instanceof FinishTxnMessage) == false) { if (debug.val) LOG.debug(String.format("%s - Cannot process %s on partition %d because txn was marked as aborted", ts, work.getClass().getSimpleName(), this.partitionId)); return; } if (debug.val) LOG.debug(String.format("Processing %s at partition %d", work, this.partitionId)); // ------------------------------- // Start Transaction // ------------------------------- if (work instanceof StartTxnMessage) { if (hstore_conf.site.specexec_enable && ts.isPredictSinglePartition()) this.specExecScheduler.reset(); if (hstore_conf.site.exec_profiling) profiler.txn_time.start(); try { this.executeTransaction((LocalTransaction)ts); } finally { if (hstore_conf.site.exec_profiling) profiler.txn_time.stopIfStarted(); } } // ------------------------------- // Execute Query Plan Fragments // ------------------------------- else if (work instanceof WorkFragmentMessage) { WorkFragment fragment = ((WorkFragmentMessage)work).getFragment(); assert(fragment != null); // HACK HACK HACK if (ts.isInitialized() == false) { LOG.warn(String.format("Skipping %s at partition %d for unitialized txn", work.getClass().getSimpleName(), this.partitionId)); return; } // Get the ParameterSet array for this WorkFragment // It can either be attached to the AbstractTransaction handle if it came // over the wire directly from the txn's base partition, or it can be attached // as for prefetch WorkFragments ParameterSet parameters[] = null; if (fragment.getPrefetch()) { parameters = ts.getPrefetchParameterSets(); ts.markExecPrefetchQuery(this.partitionId); if (trace.val && ts.isSysProc() == false) LOG.trace(ts + " - Prefetch Parameters:\n" + StringUtil.join("\n", parameters)); } else { parameters = ts.getAttachedParameterSets(); if (trace.val && ts.isSysProc() == false) LOG.trace(ts + " - Attached Parameters:\n" + StringUtil.join("\n", parameters)); } // At this point we know that we are either the current dtxn or the current dtxn is null // We will allow any read-only transaction to commit if // (1) The WorkFragment for the remote txn is read-only // (2) This txn has always been read-only up to this point at this partition ExecutionMode newMode = null; if (hstore_conf.site.specexec_enable) { if (fragment.getReadOnly() && ts.isExecReadOnly(this.partitionId)) { newMode = ExecutionMode.COMMIT_READONLY ; } else { newMode = ExecutionMode.COMMIT_NONE; } } else { newMode = ExecutionMode.DISABLED; } // There is no current DTXN, so that means its us! if (this.currentDtxn == null) { this.setCurrentDtxn(ts); if (debug.val) LOG.debug(String.format("Marking %s as current DTXN on partition %d [nextMode=%s]", ts, this.partitionId, newMode)); } // There is a current DTXN but it's not us! // That means we need to block ourselves until it finishes else if (this.currentDtxn != ts) { if (debug.val) LOG.debug(String.format("%s - Blocking on partition %d until current Dtxn %s finishes", ts, this.partitionId, this.currentDtxn)); this.blockTransaction(work); return; } assert(this.currentDtxn == ts) : String.format("Trying to execute a second Dtxn %s before the current one has finished [current=%s]", ts, this.currentDtxn); this.setExecutionMode(ts, newMode); this.processWorkFragment(ts, fragment, parameters); } // ------------------------------- // Finish Transaction // ------------------------------- else if (work instanceof FinishTxnMessage) { FinishTxnMessage ftask = (FinishTxnMessage)work; this.finishDistributedTransaction(ftask.getTransaction(), ftask.getStatus()); } // ------------------------------- // Prepare Transaction // ------------------------------- else if (work instanceof PrepareTxnMessage) { PrepareTxnMessage ftask = (PrepareTxnMessage)work; // assert(this.currentDtxn.equals(ftask.getTransaction())) : // String.format("The current dtxn %s does not match %s given in the %s", // this.currentTxn, ftask.getTransaction(), ftask.getClass().getSimpleName()); this.prepareTransaction(ftask.getTransaction()); } // ------------------------------- // Set Distributed Transaction // ------------------------------- else if (work instanceof SetDistributedTxnMessage) { if (this.currentDtxn != null) { this.blockTransaction(work); } else { this.setCurrentDtxn(((SetDistributedTxnMessage)work).getTransaction()); } } // ------------------------------- // Add Transaction to Lock Queue // ------------------------------- else if (work instanceof InitializeTxnMessage) { this.queueManager.lockQueueInsert(ts, this.partitionId, ts.getInitCallback()); } } // ---------------------------------------------------------------------------- // DATA MEMBER METHODS // ---------------------------------------------------------------------------- public final ExecutionEngine getExecutionEngine() { return (this.ee); } public final Thread getExecutionThread() { return (this.self); } public final HsqlBackend getHsqlBackend() { return (this.hsql); } public final PartitionEstimator getPartitionEstimator() { return (this.p_estimator); } public final TransactionEstimator getTransactionEstimator() { return (this.localTxnEstimator); } public final BackendTarget getBackendTarget() { return (this.backend_target); } public final HStoreSite getHStoreSite() { return (this.hstore_site); } public final HStoreConf getHStoreConf() { return (this.hstore_conf); } public final CatalogContext getCatalogContext() { return (this.catalogContext); } public final int getSiteId() { return (this.siteId); } public final Partition getPartition() { return (this.partition); } public final int getPartitionId() { return (this.partitionId); } public final DependencyTracker getDependencyTracker() { return (this.depTracker); } public final PartitionExecutorProfiler getProfiler() { return profiler; } // ---------------------------------------------------------------------------- // VOLT PROCEDURE HELPER METHODS // ---------------------------------------------------------------------------- protected void initializeVoltProcedures() { // load up all the stored procedures for (final Procedure catalog_proc : catalogContext.procedures) { VoltProcedure volt_proc = this.initializeVoltProcedure(catalog_proc); Queue<VoltProcedure> queue = new LinkedList<VoltProcedure>(); queue.add(volt_proc); this.procedures[catalog_proc.getId()] = queue; } // FOR } @SuppressWarnings("unchecked") protected VoltProcedure initializeVoltProcedure(Procedure catalog_proc) { VoltProcedure volt_proc = null; if (catalog_proc.getHasjava()) { // Only try to load the Java class file for the SP if it has one Class<? extends VoltProcedure> p_class = null; final String className = catalog_proc.getClassname(); try { p_class = (Class<? extends VoltProcedure>)Class.forName(className); volt_proc = (VoltProcedure)p_class.newInstance(); } catch (Exception e) { throw new ServerFaultException("Failed to created VoltProcedure instance for " + catalog_proc.getName() , e); } } else { volt_proc = new VoltProcedure.StmtProcedure(); } volt_proc.globalInit(PartitionExecutor.this, catalog_proc, this.backend_target, this.hsql, this.p_estimator); return (volt_proc); } /** * Returns a new VoltProcedure instance for a given stored procedure name * <B>Note:</B> You will get a new VoltProcedure for each invocation * @param proc_name * @return */ protected VoltProcedure getVoltProcedure(int proc_id) { VoltProcedure voltProc = this.procedures[proc_id].poll(); if (voltProc == null) { Procedure catalog_proc = catalogContext.getProcedureById(proc_id); voltProc = this.initializeVoltProcedure(catalog_proc); } return (voltProc); } /** * Return the given VoltProcedure back into the queue to be re-used again * @param voltProc */ protected void finishVoltProcedure(VoltProcedure voltProc) { voltProc.finish(); this.procedures[voltProc.getProcedureId()].offer(voltProc); } // ---------------------------------------------------------------------------- // UTILITY METHODS // ---------------------------------------------------------------------------- private void tick() { // invoke native ee tick if at least one second has passed final long time = EstTime.currentTimeMillis(); long elapsed = time - this.lastTickTime; if (elapsed >= 1000) { if ((this.lastTickTime != 0) && (this.ee != null)) { this.ee.tick(time, this.lastCommittedTxnId); // do other periodic work if (m_snapshotter != null) m_snapshotter.doSnapshotWork(this.ee); if ((time - this.lastStatsTime) >= 20000) { this.updateMemoryStats(time); } } this.lastTickTime = time; } } private void updateMemoryStats(long time) { if (trace.val) LOG.trace("Updating memory stats for partition " + this.partitionId); Collection<Table> tables = this.catalogContext.database.getTables(); int[] tableIds = new int[tables.size()]; int i = 0; for (Table table : tables) { tableIds[i++] = table.getRelativeIndex(); } // data to aggregate long tupleCount = 0; @SuppressWarnings("unused") long tupleAccessCount = 0; int tupleDataMem = 0; int tupleAllocatedMem = 0; int indexMem = 0; int stringMem = 0; // ACTIVE long tuplesEvicted = 0; long blocksEvicted = 0; long bytesEvicted = 0; // GLOBAL WRITTEN long tuplesWritten = 0; long blocksWritten = 0; long bytesWritten = 0; // GLOBAL READ long tuplesRead = 0; long blocksRead = 0; long bytesRead = 0; // update table stats VoltTable[] s1 = null; try { s1 = this.ee.getStats(SysProcSelector.TABLE, tableIds, false, time); } catch (RuntimeException ex) { LOG.warn("Unexpected error when trying to retrieve EE stats for partition " + this.partitionId, ex); } if (s1 != null) { VoltTable stats = s1[0]; assert(stats != null); // rollup the table memory stats for this site while (stats.advanceRow()) { int idx = 7; tupleCount += stats.getLong(idx++); tupleAccessCount += stats.getLong(idx++); tupleAllocatedMem += (int) stats.getLong(idx++); tupleDataMem += (int) stats.getLong(idx++); stringMem += (int) stats.getLong(idx++); // ACTIVE if (hstore_conf.site.anticache_enable) { tuplesEvicted += (long) stats.getLong(idx++); blocksEvicted += (long) stats.getLong(idx++); bytesEvicted += (long) stats.getLong(idx++); // GLOBAL WRITTEN tuplesWritten += (long) stats.getLong(idx++); blocksWritten += (long) stats.getLong(idx++); bytesWritten += (long) stats.getLong(idx++); // GLOBAL READ tuplesRead += (long) stats.getLong(idx++); blocksRead += (long) stats.getLong(idx++); bytesRead += (long) stats.getLong(idx++); } } stats.resetRowPosition(); } // update index stats // final VoltTable[] s2 = ee.getStats(SysProcSelector.INDEX, tableIds, false, time); // if ((s2 != null) && (s2.length > 0)) { // VoltTable stats = s2[0]; // assert(stats != null); // LOG.info("INDEX:\n" + VoltTableUtil.format(stats)); // // // rollup the index memory stats for this site //// while (stats.advanceRow()) { //// indexMem += stats.getLong(10); //// } // stats.resetRowPosition(); // // // m_indexStats.setStatsTable(stats); // } // update the rolled up memory statistics MemoryStats memoryStats = hstore_site.getMemoryStatsSource(); memoryStats.eeUpdateMemStats(this.siteId, tupleCount, tupleDataMem, tupleAllocatedMem, indexMem, stringMem, 0, // FIXME // ACTIVE tuplesEvicted, blocksEvicted, bytesEvicted, // GLOBAL WRITTEN tuplesWritten, blocksWritten, bytesWritten, // GLOBAL READ tuplesRead, blocksRead, bytesRead ); this.lastStatsTime = time; } public void haltProcessing() { // if (debug.val) LOG.warn("Halting transaction processing at partition " + this.partitionId); ExecutionMode origMode = this.currentExecMode; this.setExecutionMode(this.currentTxn, ExecutionMode.DISABLED_REJECT); List<InternalMessage> toKeep = new ArrayList<InternalMessage>(); InternalMessage msg = null; while ((msg = this.work_queue.poll()) != null) { // ------------------------------- // InitializeRequestMessage // ------------------------------- if (msg instanceof InitializeRequestMessage) { InitializeRequestMessage initMsg = (InitializeRequestMessage)msg; hstore_site.responseError(initMsg.getClientHandle(), Status.ABORT_REJECT, hstore_site.getRejectionMessage() + " - [2]", initMsg.getClientCallback(), EstTime.currentTimeMillis()); } // ------------------------------- // InitializeTxnMessage // ------------------------------- if (msg instanceof InitializeTxnMessage) { InitializeTxnMessage initMsg = (InitializeTxnMessage)msg; AbstractTransaction ts = initMsg.getTransaction(); TransactionCallback callback = ts.getInitCallback(); callback.abort(this.partitionId, Status.ABORT_REJECT); } // ------------------------------- // StartTxnMessage // ------------------------------- else if (msg instanceof StartTxnMessage) { StartTxnMessage startMsg = (StartTxnMessage)msg; hstore_site.transactionReject((LocalTransaction)startMsg.getTransaction(), Status.ABORT_REJECT); } // ------------------------------- // Things to keep // ------------------------------- else { toKeep.add(msg); } } // WHILE // assert(this.work_queue.isEmpty()); this.work_queue.addAll(toKeep); // For now we'll set it back so that we can execute new stuff. Clearing out // the queue should enough for now this.setExecutionMode(this.currentTxn, origMode); } /** * Figure out the current speculative execution mode for this partition * @return */ private SpeculationType calculateSpeculationType() { SpeculationType specType = SpeculationType.NULL; // IDLE if (this.currentDtxn == null) { specType = SpeculationType.IDLE; } // LOCAL else if (this.currentDtxn.getBasePartition() == this.partitionId) { if (((LocalTransaction)this.currentDtxn).isMarkExecuted() == false) { specType = SpeculationType.IDLE; } else if (this.currentDtxn.isMarkedPrepared(this.partitionId)) { specType = SpeculationType.SP3_LOCAL; } else { specType = SpeculationType.SP1_LOCAL; } } // REMOTE else { if (this.currentDtxn.isMarkedPrepared(this.partitionId)) { specType = SpeculationType.SP3_REMOTE; } else if (this.currentDtxn.hasExecutedWork(this.partitionId) == false) { specType = SpeculationType.SP2_REMOTE_BEFORE; } else { specType = SpeculationType.SP2_REMOTE_AFTER; } } return (specType); } /** * Set the current ExecutionMode for this executor. The transaction handle given as an input * argument is the transaction that caused the mode to get changed. It is only used for debug * purposes. * @param newMode * @param txn_id */ private void setExecutionMode(AbstractTransaction ts, ExecutionMode newMode) { if (debug.val && this.currentExecMode != newMode) { LOG.debug(String.format("Setting ExecutionMode for partition %d to %s because of %s [origMode=%s]", this.partitionId, newMode, ts, this.currentExecMode)); } assert(newMode != ExecutionMode.COMMIT_READONLY || (newMode == ExecutionMode.COMMIT_READONLY && this.currentDtxn != null)) : String.format("%s is trying to set partition %d to %s when the current DTXN is null?", ts, this.partitionId, newMode); this.currentExecMode = newMode; } /** * Returns the next undo token to use when hitting up the EE with work * MAX_VALUE = no undo * @param txn_id * @return */ private long getNextUndoToken() { if (trace.val) LOG.trace(String.format("Next Undo for Partition %d: %d", this.partitionId, this.lastUndoToken+1)); return (++this.lastUndoToken); } /** * For the given txn, return the next undo token to use for its next execution round * @param ts * @param readOnly * @return */ private long calculateNextUndoToken(AbstractTransaction ts, boolean readOnly) { long undoToken = HStoreConstants.DISABLE_UNDO_LOGGING_TOKEN; long lastUndoToken = ts.getLastUndoToken(this.partitionId); boolean singlePartition = ts.isPredictSinglePartition(); // Speculative txns always need an undo token // It's just easier this way... if (ts.isSpeculative()) { undoToken = this.getNextUndoToken(); } // If this plan is read-only, then we don't need a new undo token (unless // we don't have one already) else if (readOnly) { if (lastUndoToken == HStoreConstants.NULL_UNDO_LOGGING_TOKEN) { lastUndoToken = HStoreConstants.DISABLE_UNDO_LOGGING_TOKEN; // lastUndoToken = this.getNextUndoToken(); } undoToken = lastUndoToken; } // Otherwise, we need to figure out whether we want to be a brave soul and // not use undo logging at all else { // If one of the following conditions are true, then we need to get a new token: // (1) If this our first time up at bat // (2) If we're a distributed transaction // (3) The force undo logging option is enabled if (lastUndoToken == HStoreConstants.NULL_UNDO_LOGGING_TOKEN || singlePartition == false || hstore_conf.site.exec_force_undo_logging_all) { undoToken = this.getNextUndoToken(); } // If we originally executed this transaction with undo buffers and we have a MarkovEstimate, // then we can go back and check whether we want to disable undo logging for the rest of the transaction else if (ts.getEstimatorState() != null && singlePartition && ts.isSpeculative() == false) { Estimate est = ts.getEstimatorState().getLastEstimate(); assert(est != null) : "Got back null MarkovEstimate for " + ts; if (hstore_conf.site.exec_no_undo_logging == false || est.isValid() == false || est.isAbortable(this.thresholds) || est.isReadOnlyPartition(this.thresholds, this.partitionId) == false) { undoToken = lastUndoToken; } else if (debug.val) { LOG.warn(String.format("Bold! Disabling undo buffers for inflight %s\n%s", ts, est)); } } } // Make sure that it's at least as big as the last one handed out if (undoToken < this.lastUndoToken) undoToken = this.lastUndoToken; if (debug.val) LOG.debug(String.format("%s - Next undo token at partition %d is %s [readOnly=%s]", ts, this.partitionId, (undoToken == HStoreConstants.DISABLE_UNDO_LOGGING_TOKEN ? "<DISABLED>" : (undoToken == HStoreConstants.NULL_UNDO_LOGGING_TOKEN ? "<NULL>" : undoToken)), readOnly)); return (undoToken); } /** * Populate the provided inputs map with the VoltTables needed for the give * input DependencyId. If the txn is a LocalTransaction, then we will * get the data we need from the base partition's DependencyTracker. * @param ts * @param input_dep_ids * @param inputs * @return */ private void getFragmentInputs(AbstractTransaction ts, int input_dep_id, Map<Integer, List<VoltTable>> inputs) { if (input_dep_id == HStoreConstants.NULL_DEPENDENCY_ID) return; if (trace.val) LOG.trace(String.format("%s - Attempting to retrieve input dependencies for DependencyId #%d", ts, input_dep_id)); // If the Transaction is on the same HStoreSite, then all the // input dependencies will be internal and can be retrieved locally if (ts instanceof LocalTransaction) { DependencyTracker txnTracker = null; if (ts.getBasePartition() != this.partitionId) { txnTracker = hstore_site.getDependencyTracker(ts.getBasePartition()); } else { txnTracker = this.depTracker; } List<VoltTable> deps = txnTracker.getInternalDependency((LocalTransaction)ts, input_dep_id); assert(deps != null); assert(inputs.containsKey(input_dep_id) == false); inputs.put(input_dep_id, deps); if (trace.val) LOG.trace(String.format("%s - Retrieved %d INTERNAL VoltTables for DependencyId #%d", ts, deps.size(), input_dep_id, (trace.val ? "\n" + deps : ""))); } // Otherwise they will be "attached" inputs to the RemoteTransaction handle // We should really try to merge these two concepts into a single function call else if (ts.getAttachedInputDependencies().containsKey(input_dep_id)) { List<VoltTable> deps = ts.getAttachedInputDependencies().get(input_dep_id); List<VoltTable> pDeps = null; // We have to copy the tables if we have debugging enabled if (trace.val) { // this.firstPartition == false) { pDeps = new ArrayList<VoltTable>(); for (VoltTable vt : deps) { ByteBuffer buffer = vt.getTableDataReference(); byte arr[] = new byte[vt.getUnderlyingBufferSize()]; buffer.get(arr, 0, arr.length); pDeps.add(new VoltTable(ByteBuffer.wrap(arr), true)); } } else { pDeps = deps; } inputs.put(input_dep_id, pDeps); if (trace.val) LOG.trace(String.format("%s - Retrieved %d ATTACHED VoltTables for DependencyId #%d in %s", ts, deps.size(), input_dep_id)); } } /** * Set the given AbstractTransaction handle as the current distributed txn * that is running at this partition. Note that this will check to make sure * that no other txn is marked as the currentDtxn. * @param ts */ private void setCurrentDtxn(AbstractTransaction ts) { // There can never be another current dtxn still unfinished at this partition! assert(this.currentBlockedTxns.isEmpty()) : String.format("Concurrent multi-partition transactions at partition %d: " + "Orig[%s] <=> New[%s] / BlockedQueue:%d", this.partitionId, this.currentDtxn, ts, this.currentBlockedTxns.size()); assert(this.currentDtxn == null) : String.format("Concurrent multi-partition transactions at partition %d: " + "Orig[%s] <=> New[%s] / BlockedQueue:%d", this.partitionId, this.currentDtxn, ts, this.currentBlockedTxns.size()); // Check whether we should check for speculative txns to execute whenever this // dtxn is idle at this partition this.currentDtxn = ts; if (hstore_conf.site.specexec_enable && ts.isSysProc() == false && this.specExecScheduler.isDisabled() == false) { this.specExecIgnoreCurrent = this.specExecChecker.shouldIgnoreTransaction(ts); } else { this.specExecIgnoreCurrent = true; } if (debug.val) { LOG.debug(String.format("Set %s as the current DTXN for partition %d [specExecIgnore=%s, previous=%s]", ts, this.partitionId, this.specExecIgnoreCurrent, this.lastDtxnDebug)); this.lastDtxnDebug = this.currentDtxn.toString(); } if (hstore_conf.site.exec_profiling && ts.getBasePartition() != this.partitionId) { profiler.sp2_time.start(); } } /** * Reset the current dtxn for this partition */ private void resetCurrentDtxn() { assert(this.currentDtxn != null) : "Trying to reset the currentDtxn when it is already null"; if (debug.val) LOG.debug(String.format("Resetting current DTXN for partition %d to null [previous=%s]", this.partitionId, this.lastDtxnDebug)); this.currentDtxn = null; } /** * Store a new prefetch result for a transaction * @param txnId * @param fragmentId * @param partitionId * @param params * @param result */ public void addPrefetchResult(LocalTransaction ts, int stmtCounter, int fragmentId, int partitionId, int paramsHash, VoltTable result) { if (debug.val) LOG.debug(String.format("%s - Adding prefetch result for %s with %d rows from partition %d " + "[stmtCounter=%d / paramsHash=%d]", ts, CatalogUtil.getPlanFragment(catalogContext.catalog, fragmentId).fullName(), result.getRowCount(), partitionId, stmtCounter, paramsHash)); this.depTracker.addPrefetchResult(ts, stmtCounter, fragmentId, partitionId, paramsHash, result); } // --------------------------------------------------------------- // PartitionExecutor API // --------------------------------------------------------------- /** * Queue a new transaction initialization at this partition. This will cause the * transaction to get added to this partition's lock queue. This PartitionExecutor does * not have to be this txn's base partition/ * @param ts */ public void queueSetPartitionLock(AbstractTransaction ts) { assert(ts.isInitialized()) : "Unexpected uninitialized transaction: " + ts; SetDistributedTxnMessage work = ts.getSetDistributedTxnMessage(); boolean success = this.work_queue.offer(work); assert(success) : String.format("Failed to queue %s at partition %d for %s", work, this.partitionId, ts); if (debug.val) LOG.debug(String.format("%s - Added %s to front of partition %d " + "work queue [size=%d]", ts, work.getClass().getSimpleName(), this.partitionId, this.work_queue.size())); if (hstore_conf.site.specexec_enable) this.specExecScheduler.interruptSearch(work); } /** * New work from the coordinator that this local site needs to execute (non-blocking) * This method will simply chuck the task into the work queue. * We should not be sent an InitiateTaskMessage here! * @param ts * @param task */ public void queueWork(AbstractTransaction ts, WorkFragment fragment) { assert(ts.isInitialized()) : "Unexpected uninitialized transaction: " + ts; WorkFragmentMessage work = ts.getWorkFragmentMessage(fragment); boolean success = this.work_queue.offer(work); // , true); assert(success) : String.format("Failed to queue %s at partition %d for %s", work, this.partitionId, ts); ts.markQueuedWork(this.partitionId); if (debug.val) LOG.debug(String.format("%s - Added %s to partition %d " + "work queue [size=%d]", ts, work.getClass().getSimpleName(), this.partitionId, this.work_queue.size())); if (hstore_conf.site.specexec_enable) this.specExecScheduler.interruptSearch(work); } /** * Add a new work message to our utility queue * @param work */ public void queueUtilityWork(InternalMessage work) { if (debug.val) LOG.debug(String.format("Added utility work %s to partition %d", work.getClass().getSimpleName(), this.partitionId)); this.work_queue.offer(work); } /** * Put the prepare request for the transaction into the queue * @param task * @param status The final status of the transaction */ public void queuePrepare(AbstractTransaction ts) { assert(ts.isInitialized()) : "Unexpected uninitialized transaction: " + ts; PrepareTxnMessage work = ts.getPrepareTxnMessage(); boolean success = this.work_queue.offer(work); assert(success) : String.format("Failed to queue %s at partition %d for %s", work, this.partitionId, ts); if (debug.val) LOG.debug(String.format("%s - Added %s to partition %d " + "work queue [size=%d]", ts, work.getClass().getSimpleName(), this.partitionId, this.work_queue.size())); // if (hstore_conf.site.specexec_enable) this.specExecScheduler.interruptSearch(); } /** * Put the finish request for the transaction into the queue * @param task * @param status The final status of the transaction */ public void queueFinish(AbstractTransaction ts, Status status) { assert(ts.isInitialized()) : "Unexpected uninitialized transaction: " + ts; FinishTxnMessage work = ts.getFinishTxnMessage(status); boolean success = this.work_queue.offer(work); // , true); assert(success) : String.format("Failed to queue %s at partition %d for %s", work, this.partitionId, ts); if (debug.val) LOG.debug(String.format("%s - Added %s to partition %d " + "work queue [size=%d]", ts, work.getClass().getSimpleName(), this.partitionId, this.work_queue.size())); // if (success) this.specExecScheduler.haltSearch(); } /** * Queue a new transaction invocation request at this partition * @param serializedRequest * @param catalog_proc * @param procParams * @param clientCallback * @return */ public boolean queueNewTransaction(ByteBuffer serializedRequest, long initiateTime, Procedure catalog_proc, ParameterSet procParams, RpcCallback<ClientResponseImpl> clientCallback) { boolean sysproc = catalog_proc.getSystemproc(); if (this.currentExecMode == ExecutionMode.DISABLED_REJECT && sysproc == false) return (false); InitializeRequestMessage work = new InitializeRequestMessage(serializedRequest, initiateTime, catalog_proc, procParams, clientCallback); if (debug.val) LOG.debug(String.format("Queuing %s for '%s' request on partition %d " + "[currentDtxn=%s, queueSize=%d, mode=%s]", work.getClass().getSimpleName(), catalog_proc.getName(), this.partitionId, this.currentDtxn, this.work_queue.size(), this.currentExecMode)); return (this.work_queue.offer(work)); } /** * Queue a new transaction invocation request at this partition * @param ts * @param task * @param callback */ public boolean queueStartTransaction(LocalTransaction ts) { assert(ts != null) : "Unexpected null transaction handle!"; boolean singlePartitioned = ts.isPredictSinglePartition(); boolean force = (singlePartitioned == false) || ts.isMapReduce() || ts.isSysProc(); // UPDATED 2012-07-12 // We used to have a bunch of checks to determine whether we needed // put the new request in the blocked queue or not. This required us to // acquire the exec_lock to do the check and then another lock to actually put // the request into the work_queue. Now we'll just throw it right in // the queue (checking for throttling of course) and let the main // thread sort out the mess of whether the txn should get blocked or not if (this.currentExecMode == ExecutionMode.DISABLED_REJECT) { if (debug.val) LOG.warn(String.format("%s - Not queuing txn at partition %d because current mode is %s", ts, this.partitionId, this.currentExecMode)); return (false); } StartTxnMessage work = ts.getStartTxnMessage(); if (debug.val) LOG.debug(String.format("Queuing %s for '%s' request on partition %d " + "[currentDtxn=%s, queueSize=%d, mode=%s]", work.getClass().getSimpleName(), ts.getProcedure().getName(), this.partitionId, this.currentDtxn, this.work_queue.size(), this.currentExecMode)); boolean success = this.work_queue.offer(work); // , force); if (debug.val && force && success == false) { String msg = String.format("Failed to add %s even though force flag was true!", ts); throw new ServerFaultException(msg, ts.getTransactionId()); } if (success && hstore_conf.site.specexec_enable) this.specExecScheduler.interruptSearch(work); return (success); } // --------------------------------------------------------------- // WORK QUEUE PROCESSING METHODS // --------------------------------------------------------------- /** * Process a WorkResult and update the internal state the LocalTransaction accordingly * Note that this will always be invoked by a thread other than the main execution thread * for this PartitionExecutor. That means if something comes back that's bad, we need a way * to alert the other thread so that it can act on it. * @param ts * @param result */ private void processWorkResult(LocalTransaction ts, WorkResult result) { boolean needs_profiling = (hstore_conf.site.txn_profiling && ts.profiler != null); if (debug.val) LOG.debug(String.format("Processing WorkResult for %s on partition %d [srcPartition=%d, deps=%d]", ts, this.partitionId, result.getPartitionId(), result.getDepDataCount())); // If the Fragment failed to execute, then we need to abort the Transaction // Note that we have to do this before we add the responses to the TransactionState so that // we can be sure that the VoltProcedure knows about the problem when it wakes the stored // procedure back up if (result.getStatus() != Status.OK) { if (trace.val) LOG.trace(String.format("Received non-success response %s from partition %d for %s", result.getStatus(), result.getPartitionId(), ts)); SerializableException error = null; if (needs_profiling) ts.profiler.startDeserialization(); try { ByteBuffer buffer = result.getError().asReadOnlyByteBuffer(); error = SerializableException.deserializeFromBuffer(buffer); } catch (Exception ex) { String msg = String.format("Failed to deserialize SerializableException from partition %d " + "for %s [bytes=%d]", result.getPartitionId(), ts, result.getError().size()); throw new ServerFaultException(msg, ex); } finally { if (needs_profiling) ts.profiler.stopDeserialization(); } // At this point there is no need to even deserialize the rest of the message because // we know that we're going to have to abort the transaction if (error == null) { LOG.warn(ts + " - Unexpected null SerializableException\n" + result); } else { if (debug.val) LOG.error(String.format("%s - Got error from partition %d in %s", ts, result.getPartitionId(), result.getClass().getSimpleName()), error); ts.setPendingError(error, true); } return; } if (needs_profiling) ts.profiler.startDeserialization(); for (int i = 0, cnt = result.getDepDataCount(); i < cnt; i++) { if (trace.val) LOG.trace(String.format("Storing intermediate results from partition %d for %s", result.getPartitionId(), ts)); int depId = result.getDepId(i); ByteString bs = result.getDepData(i); VoltTable vt = null; if (bs.isEmpty() == false) { FastDeserializer fd = new FastDeserializer(bs.asReadOnlyByteBuffer()); try { vt = fd.readObject(VoltTable.class); } catch (Exception ex) { throw new ServerFaultException("Failed to deserialize VoltTable from partition " + result.getPartitionId() + " for " + ts, ex); } } this.depTracker.addResult(ts, result.getPartitionId(), depId, vt); } // FOR (dependencies) if (needs_profiling) ts.profiler.stopDeserialization(); } /** * Execute a new transaction at this partition. * This will invoke the run() method define in the VoltProcedure for this txn and * then process the ClientResponse. Only the PartitionExecutor itself should be calling * this directly, since it's the only thing that knows what's going on with the world... * @param ts */ private void executeTransaction(LocalTransaction ts) { assert(ts.isInitialized()) : String.format("Trying to execute uninitialized transaction %s at partition %d", ts, this.partitionId); assert(ts.isMarkedReleased(this.partitionId)) : String.format("Transaction %s was not marked released at partition %d before being executed", ts, this.partitionId); if (trace.val) LOG.debug(String.format("%s - Attempting to start transaction on partition %d", ts, this.partitionId)); // If this is a MapReduceTransaction handle, we actually want to get the // inner LocalTransaction handle for this partition. The MapReduceTransaction // is just a placeholder if (ts instanceof MapReduceTransaction) { MapReduceTransaction mr_ts = (MapReduceTransaction)ts; ts = mr_ts.getLocalTransaction(this.partitionId); assert(ts != null) : "Unexpected null LocalTransaction handle from " + mr_ts; } ExecutionMode before_mode = this.currentExecMode; boolean predict_singlePartition = ts.isPredictSinglePartition(); // ------------------------------- // DISTRIBUTED TXN // ------------------------------- if (predict_singlePartition == false) { // If there is already a dtxn running, then we need to throw this // mofo back into the blocked txn queue // TODO: If our dtxn is on the same site as us, then at this point we know that // it is done executing the control code and is sending around 2PC messages // to commit/abort. That means that we could assume that all of the other // remote partitions are going to agree on the same outcome and we can start // speculatively executing this dtxn. After all, if we're at this point in // the PartitionExecutor then we know that we got this partition's locks // from the TransactionQueueManager. if (this.currentDtxn != null && this.currentDtxn.equals(ts) == false) { assert(this.currentDtxn.equals(ts) == false) : String.format("New DTXN %s != Current DTXN %s", ts, this.currentDtxn); // If this is a local txn, then we can finagle things a bit. if (this.currentDtxn.isExecLocal(this.partitionId)) { // It would be safe for us to speculative execute this DTXN right here // if the currentDtxn has aborted... but we can never be in this state. assert(this.currentDtxn.isAborted() == false) : // Sanity Check String.format("We want to execute %s on partition %d but aborted %s is still hanging around\n", ts, this.partitionId, this.currentDtxn, this.work_queue); // So that means we know that it committed, which doesn't necessarily mean // that it will still commit, but we'll be able to abort, rollback, and requeue // if that happens. // TODO: Right now our current dtxn marker is a single value. We may want to // switch it to a FIFO queue so that we can multiple guys hanging around. // For now we will just do the default thing and block this txn this.blockTransaction(ts); return; } // If it's not local, then we just have to block it right away else { this.blockTransaction(ts); return; } } // If there is no other DTXN right now, then we're it! else if (this.currentDtxn == null) { // || this.currentDtxn.equals(ts) == false) { this.setCurrentDtxn(ts); } // 2011-11-14: We don't want to set the execution mode here, because we know that we // can check whether we were read-only after the txn finishes this.setExecutionMode(this.currentDtxn, ExecutionMode.COMMIT_NONE); if (debug.val) LOG.debug(String.format("Marking %s as current DTXN on Partition %d [isLocal=%s, execMode=%s]", ts, this.partitionId, true, this.currentExecMode)); } // ------------------------------- // SINGLE-PARTITION TXN // ------------------------------- else { // If this is a single-partition transaction, then we need to check whether we are // being executed under speculative execution mode. We have to check this here // because it may be the case that we queued a bunch of transactions when speculative // execution was enabled, but now the transaction that was ahead of this one is finished, // so now we're just executing them regularly if (this.currentDtxn != null) { // HACK: If we are currently under DISABLED mode when we get this, then we just // need to block the transaction and return back to the queue. This is easier than // having to set all sorts of crazy locks if (this.currentExecMode == ExecutionMode.DISABLED || hstore_conf.site.specexec_enable == false) { if (debug.val) LOG.debug(String.format("%s - Blocking single-partition %s until dtxn finishes [mode=%s]", this.currentDtxn, ts, this.currentExecMode)); this.blockTransaction(ts); return; } assert(ts.getSpeculationType() != null); if (debug.val) LOG.debug(String.format("Speculatively executing %s while waiting for dtxn %s [%s]", ts, this.currentDtxn, ts.getSpeculationType())); assert(ts.isSpeculative()) : ts + " was not marked as being speculative!"; } } // If we reach this point, we know that we're about to execute our homeboy here... if (hstore_conf.site.txn_profiling && ts.profiler != null) { ts.profiler.startExec(); } if (hstore_conf.site.exec_profiling) this.profiler.numTransactions++; // Make sure the dependency tracker knows about us if (ts.hasDependencyTracker()) this.depTracker.addTransaction(ts); // Grab a new ExecutionState for this txn ExecutionState execState = this.initExecutionState(); ts.setExecutionState(execState); VoltProcedure volt_proc = this.getVoltProcedure(ts.getProcedure().getId()); assert(volt_proc != null) : "No VoltProcedure for " + ts; if (debug.val) { LOG.debug(String.format("%s - Starting execution of txn on partition %d " + "[txnMode=%s, mode=%s]", ts, this.partitionId, before_mode, this.currentExecMode)); if (trace.val) LOG.trace(String.format("Current Transaction at partition #%d\n%s", this.partitionId, ts.debug())); } if (hstore_conf.site.txn_counters) TransactionCounter.EXECUTED.inc(ts.getProcedure()); ClientResponseImpl cresponse = null; VoltProcedure previous = this.currentVoltProc; try { this.currentVoltProc = volt_proc; cresponse = volt_proc.call(ts, ts.getProcedureParameters().toArray()); // Blocking... // VoltProcedure.call() should handle any exceptions thrown by the transaction // If we get anything out here then that's bad news } catch (Throwable ex) { if (this.isShuttingDown() == false) { SQLStmt last[] = volt_proc.voltLastQueriesExecuted(); LOG.fatal("Unexpected error while executing " + ts, ex); if (last.length > 0) { LOG.fatal(String.format("Last Queries Executed [%d]: %s", last.length, Arrays.toString(last))); } LOG.fatal("LocalTransactionState Dump:\n" + ts.debug()); this.crash(ex); } } finally { this.currentVoltProc = previous; ts.resetExecutionState(); execState.finish(); this.execStates.add(execState); this.finishVoltProcedure(volt_proc); if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.startPost(); // if (cresponse.getStatus() == Status.ABORT_UNEXPECTED) { // cresponse.getException().printStackTrace(); // } } // If this is a MapReduce job, then we can just ignore the ClientResponse // and return immediately. The VoltMapReduceProcedure is responsible for storing // the result at the proper location. if (ts.isMapReduce()) { return; } else if (cresponse == null) { assert(this.isShuttingDown()) : String.format("No ClientResponse for %s???", ts); return; } // ------------------------------- // PROCESS RESPONSE AND FIGURE OUT NEXT STEP // ------------------------------- Status status = cresponse.getStatus(); if (debug.val) { LOG.debug(String.format("%s - Finished execution of transaction control code " + "[status=%s, beforeMode=%s, currentMode=%s]", ts, status, before_mode, this.currentExecMode)); if (ts.hasPendingError()) { LOG.debug(String.format("%s - Txn finished with pending error: %s", ts, ts.getPendingErrorMessage())); } } // We assume that most transactions are not speculatively executed and are successful // Therefore we don't want to grab the exec_mode lock here. if (predict_singlePartition == false || this.canProcessClientResponseNow(ts, status, before_mode)) { this.processClientResponse(ts, cresponse); } // Otherwise always queue our response, since we know that whatever thread is out there // is waiting for us to finish before it drains the queued responses else { // If the transaction aborted, then we can't execute any transaction that touch the tables // that this guy touches. But since we can't just undo this transaction without undoing // everything that came before it, we'll just disable executing all transactions until the // current distributed transaction commits if (status != Status.OK && ts.isExecReadOnly(this.partitionId) == false) { this.setExecutionMode(ts, ExecutionMode.DISABLED); int blocked = this.work_queue.drainTo(this.currentBlockedTxns); if (debug.val) { if (trace.val && blocked > 0) LOG.trace(String.format("Blocking %d transactions at partition %d because ExecutionMode is now %s", blocked, this.partitionId, this.currentExecMode)); LOG.debug(String.format("Disabling execution on partition %d because speculative %s aborted", this.partitionId, ts)); } } if (trace.val) LOG.trace(String.format("%s - Queuing ClientResponse [status=%s, origMode=%s, newMode=%s, dtxn=%s]", ts, cresponse.getStatus(), before_mode, this.currentExecMode, this.currentDtxn)); this.blockClientResponse(ts, cresponse); } } /** * Determines whether a finished transaction that executed locally can have their ClientResponse processed immediately * or if it needs to wait for the response from the outstanding multi-partition transaction for this partition * (1) This is the multi-partition transaction that everyone is waiting for * (2) The transaction was not executed under speculative execution mode * (3) The transaction does not need to wait for the multi-partition transaction to finish first * @param ts * @param status * @param before_mode * @return */ private boolean canProcessClientResponseNow(LocalTransaction ts, Status status, ExecutionMode before_mode) { if (debug.val) LOG.debug(String.format("%s - Checking whether to process %s response now at partition %d " + "[singlePartition=%s, readOnly=%s, specExecModified=%s, before=%s, current=%s]", ts, status, this.partitionId, ts.isPredictSinglePartition(), ts.isExecReadOnly(this.partitionId), this.specExecModified, before_mode, this.currentExecMode)); // Commit All if (this.currentExecMode == ExecutionMode.COMMIT_ALL) { return (true); } // SPECIAL CASE // Any user-aborted, speculative single-partition transaction should be processed immediately. else if (status == Status.ABORT_USER && ts.isSpeculative()) { return (true); } // // SPECIAL CASE // // If this txn threw a user abort, and the current outstanding dtxn is read-only // // then it's safe for us to rollback // else if (status == Status.ABORT_USER && // this.currentDtxn != null && // this.currentDtxn.isExecReadOnly(this.partitionId)) { // return (true); // } // SPECIAL CASE // Anything mispredicted should be processed right away else if (status == Status.ABORT_MISPREDICT) { return (true); } // Process successful txns based on the mode that it was executed under else if (status == Status.OK) { switch (before_mode) { case COMMIT_ALL: return (true); case COMMIT_READONLY: // Read-only speculative txns can be committed right now // TODO: Right now we're going to use the specExecModified flag to disable // sending out any results from spec execed txns that may have read from // a modified database. We should switch to a bitmap of table ids so that we // have can be more selective. // return (false); return (this.specExecModified == false && ts.isExecReadOnly(this.partitionId)); case COMMIT_NONE: { // If this txn does not conflict with the current dtxn, then we should be able // to let it commit but we can't because of the way our undo tokens work return (false); } default: throw new ServerFaultException("Unexpected execution mode: " + before_mode, ts.getTransactionId()); } // SWITCH } // // If the transaction aborted and it was read-only thus far, then we want to process it immediately // else if (status != Status.OK && ts.isExecReadOnly(this.partitionId)) { // return (true); // } assert(this.currentExecMode != ExecutionMode.COMMIT_ALL) : String.format("Queuing ClientResponse for %s when in non-specutative mode [mode=%s, status=%s]", ts, this.currentExecMode, status); return (false); } /** * Process a WorkFragment for a transaction and execute it in this partition's underlying EE. * @param ts * @param fragment * @param allParameters The array of all the ParameterSets for the current SQLStmt batch. */ private void processWorkFragment(AbstractTransaction ts, WorkFragment fragment, ParameterSet allParameters[]) { assert(this.partitionId == fragment.getPartitionId()) : String.format("Tried to execute WorkFragment %s for %s at partition %d but it was suppose " + "to be executed on partition %d", fragment.getFragmentIdList(), ts, this.partitionId, fragment.getPartitionId()); assert(ts.isMarkedPrepared(this.partitionId) == false) : String.format("Tried to execute WorkFragment %s for %s at partition %d after it was marked 2PC:PREPARE", fragment.getFragmentIdList(), ts, this.partitionId); // A txn is "local" if the Java is executing at the same partition as this one boolean is_basepartition = (ts.getBasePartition() == this.partitionId); boolean is_remote = (ts instanceof LocalTransaction == false); boolean is_prefetch = fragment.getPrefetch(); boolean is_readonly = fragment.getReadOnly(); if (debug.val) LOG.debug(String.format("%s - Executing %s [isBasePartition=%s, isRemote=%s, isPrefetch=%s, isReadOnly=%s, fragments=%s]", ts, fragment.getClass().getSimpleName(), is_basepartition, is_remote, is_prefetch, is_readonly, fragment.getFragmentIdCount())); // If this WorkFragment isn't being executed at this txn's base partition, then // we need to start a new execution round if (is_basepartition == false) { long undoToken = this.calculateNextUndoToken(ts, is_readonly); ts.initRound(this.partitionId, undoToken); ts.startRound(this.partitionId); } DependencySet result = null; Status status = Status.OK; SerializableException error = null; // Check how many fragments are not marked as ignored // If the fragment is marked as ignore then it means that it was already // sent to this partition for prefetching. We need to make sure that we remove // it from the list of fragmentIds that we need to execute. int fragmentCount = fragment.getFragmentIdCount(); for (int i = 0; i < fragmentCount; i++) { if (fragment.getStmtIgnore(i)) { fragmentCount--; } } // FOR final ParameterSet parameters[] = tmp_fragmentParams.getParameterSet(fragmentCount); assert(parameters.length == fragmentCount); // Construct data given to the EE to execute this work fragment this.tmp_EEdependencies.clear(); long fragmentIds[] = tmp_fragmentIds.getArray(fragmentCount); int fragmentOffsets[] = tmp_fragmentOffsets.getArray(fragmentCount); int outputDepIds[] = tmp_outputDepIds.getArray(fragmentCount); int inputDepIds[] = tmp_inputDepIds.getArray(fragmentCount); int offset = 0; for (int i = 0, cnt = fragment.getFragmentIdCount(); i < cnt; i++) { if (fragment.getStmtIgnore(i) == false) { fragmentIds[offset] = fragment.getFragmentId(i); fragmentOffsets[offset] = i; outputDepIds[offset] = fragment.getOutputDepId(i); inputDepIds[offset] = fragment.getInputDepId(i); parameters[offset] = allParameters[fragment.getParamIndex(i)]; this.getFragmentInputs(ts, inputDepIds[offset], this.tmp_EEdependencies); if (trace.val && ts.isSysProc() == false && is_basepartition == false) LOG.trace(String.format("%s - Offset:%d FragmentId:%d OutputDep:%d/%d InputDep:%d/%d", ts, offset, fragmentIds[offset], outputDepIds[offset], fragment.getOutputDepId(i), inputDepIds[offset], fragment.getInputDepId(i))); offset++; } } // FOR assert(offset == fragmentCount); try { result = this.executeFragmentIds(ts, ts.getLastUndoToken(this.partitionId), fragmentIds, parameters, outputDepIds, inputDepIds, this.tmp_EEdependencies); } catch (EvictedTupleAccessException ex) { // XXX: What do we do if this is not a single-partition txn? status = Status.ABORT_EVICTEDACCESS; error = ex; } catch (ConstraintFailureException ex) { status = Status.ABORT_UNEXPECTED; error = ex; } catch (SQLException ex) { status = Status.ABORT_UNEXPECTED; error = ex; } catch (EEException ex) { // this.crash(ex); status = Status.ABORT_UNEXPECTED; error = ex; } catch (Throwable ex) { status = Status.ABORT_UNEXPECTED; if (ex instanceof SerializableException) { error = (SerializableException)ex; } else { error = new SerializableException(ex); } } finally { if (error != null) { // error.printStackTrace(); LOG.warn(String.format("%s - Unexpected %s on partition %d", ts, error.getClass().getSimpleName(), this.partitionId), error); // (debug.val ? error : null)); } // Success, but without any results??? if (result == null && status == Status.OK) { String msg = String.format("The WorkFragment %s executed successfully on Partition %d but " + "result is null for %s", fragment.getFragmentIdList(), this.partitionId, ts); Exception ex = new Exception(msg); if (debug.val) LOG.warn(ex); status = Status.ABORT_UNEXPECTED; error = new SerializableException(ex); } } // For single-partition INSERT/UPDATE/DELETE queries, we don't directly // execute the SendPlanNode in order to get back the number of tuples that // were modified. So we have to rely on the output dependency ids set in the task assert(status != Status.OK || (status == Status.OK && result.size() == fragmentIds.length)) : "Got back " + result.size() + " results but was expecting " + fragmentIds.length; // Make sure that we mark the round as finished before we start sending results if (is_basepartition == false) { ts.finishRound(this.partitionId); } // ------------------------------- // PREFETCH QUERIES // ------------------------------- if (is_prefetch) { // Regardless of whether this txn is running at the same HStoreSite as this PartitionExecutor, // we always need to put the result inside of the local query cache // This is so that we can identify if we get request for a query that we have already executed // We'll only do this if it succeeded. If it failed, then we won't do anything and will // just wait until they come back to execute the query again before // we tell them that something went wrong. It's ghetto, but it's just easier this way... if (status == Status.OK) { // We're going to store the result in the base partition cache if they're // on the same HStoreSite as us if (is_remote == false) { PartitionExecutor other = this.hstore_site.getPartitionExecutor(ts.getBasePartition()); for (int i = 0, cnt = result.size(); i < cnt; i++) { if (trace.val) LOG.trace(String.format("%s - Storing %s prefetch result [params=%s]", ts, CatalogUtil.getPlanFragment(catalogContext.catalog, fragment.getFragmentId(fragmentOffsets[i])).fullName(), parameters[i])); other.addPrefetchResult((LocalTransaction)ts, fragment.getStmtCounter(fragmentOffsets[i]), fragment.getFragmentId(fragmentOffsets[i]), this.partitionId, parameters[i].hashCode(), result.dependencies[i]); } // FOR } } // Now if it's a remote transaction, we need to use the coordinator to send // them our result. Note that we want to send a single message per partition. Unlike // with the TransactionWorkRequests, we don't need to wait until all of the partitions // that are prefetching for this txn at our local HStoreSite to finish. if (is_remote) { WorkResult wr = this.buildWorkResult(ts, result, status, error); TransactionPrefetchResult.Builder builder = TransactionPrefetchResult.newBuilder() .setTransactionId(ts.getTransactionId().longValue()) .setSourcePartition(this.partitionId) .setResult(wr) .setStatus(status) .addAllFragmentId(fragment.getFragmentIdList()) .addAllStmtCounter(fragment.getStmtCounterList()); for (int i = 0, cnt = fragment.getFragmentIdCount(); i < cnt; i++) { builder.addParamHash(parameters[i].hashCode()); } if (debug.val) LOG.debug(String.format("%s - Sending back %s to partition %d [numResults=%s, status=%s]", ts, wr.getClass().getSimpleName(), ts.getBasePartition(), result.size(), status)); hstore_coordinator.transactionPrefetchResult((RemoteTransaction)ts, builder.build()); } } // ------------------------------- // LOCAL TRANSACTION // ------------------------------- else if (is_remote == false) { LocalTransaction local_ts = (LocalTransaction)ts; // If the transaction is local, store the result directly in the local TransactionState if (status == Status.OK) { if (trace.val) LOG.trace(String.format("%s - Storing %d dependency results locally for successful work fragment", ts, result.size())); assert(result.size() == outputDepIds.length); DependencyTracker otherTracker = this.hstore_site.getDependencyTracker(ts.getBasePartition()); for (int i = 0; i < outputDepIds.length; i++) { if (trace.val) LOG.trace(String.format("%s - Storing DependencyId #%d [numRows=%d]\n%s", ts, outputDepIds[i], result.dependencies[i].getRowCount(), result.dependencies[i])); try { otherTracker.addResult(local_ts, this.partitionId, outputDepIds[i], result.dependencies[i]); } catch (Throwable ex) { // ex.printStackTrace(); String msg = String.format("Failed to stored Dependency #%d for %s [idx=%d, fragmentId=%d]", outputDepIds[i], ts, i, fragmentIds[i]); LOG.error(String.format("%s - WorkFragment:%d\nExpectedIds:%s\nOutputDepIds: %s\nResultDepIds: %s\n%s", msg, fragment.hashCode(), fragment.getOutputDepIdList(), Arrays.toString(outputDepIds), Arrays.toString(result.depIds), fragment)); throw new ServerFaultException(msg, ex); } } // FOR } else { local_ts.setPendingError(error, true); } } // ------------------------------- // REMOTE TRANSACTION // ------------------------------- else { if (trace.val) LOG.trace(String.format("%s - Constructing WorkResult with %d bytes from partition %d to send " + "back to initial partition %d [status=%s]", ts, (result != null ? result.size() : null), this.partitionId, ts.getBasePartition(), status)); RpcCallback<WorkResult> callback = ((RemoteTransaction)ts).getWorkCallback(); if (callback == null) { LOG.fatal("Unable to send FragmentResponseMessage for " + ts); LOG.fatal("Orignal WorkFragment:\n" + fragment); LOG.fatal(ts.toString()); throw new ServerFaultException("No RPC callback to HStoreSite for " + ts, ts.getTransactionId()); } WorkResult response = this.buildWorkResult((RemoteTransaction)ts, result, status, error); assert(response != null); callback.run(response); } // Check whether this is the last query that we're going to get // from this transaction. If it is, then we can go ahead and prepare the txn if (is_basepartition == false && fragment.getLastFragment()) { if (debug.val) LOG.debug(String.format("%s - Invoking early 2PC:PREPARE at partition %d", ts, this.partitionId)); this.queuePrepare(ts); } } /** * Executes a WorkFragment on behalf of some remote site and returns the * resulting DependencySet * @param fragment * @return * @throws Exception */ private DependencySet executeFragmentIds(AbstractTransaction ts, long undoToken, long fragmentIds[], ParameterSet parameters[], int output_depIds[], int input_depIds[], Map<Integer, List<VoltTable>> input_deps) throws Exception { if (fragmentIds.length == 0) { LOG.warn(String.format("Got a fragment batch for %s that does not have any fragments?", ts)); return (null); } // *********************************** DEBUG *********************************** if (trace.val) { LOG.trace(String.format("%s - Getting ready to kick %d fragments to partition %d EE [undoToken=%d]", ts, fragmentIds.length, this.partitionId, (undoToken != HStoreConstants.NULL_UNDO_LOGGING_TOKEN ? undoToken : "null"))); // if (trace.val) { // LOG.trace("WorkFragmentIds: " + Arrays.toString(fragmentIds)); // Map<String, Object> m = new LinkedHashMap<String, Object>(); // for (int i = 0; i < parameters.length; i++) { // m.put("Parameter[" + i + "]", parameters[i]); // } // FOR // LOG.trace("Parameters:\n" + StringUtil.formatMaps(m)); // } } // *********************************** DEBUG *********************************** DependencySet result = null; // ------------------------------- // SYSPROC FRAGMENTS // ------------------------------- if (ts.isSysProc()) { result = this.executeSysProcFragments(ts, undoToken, fragmentIds.length, fragmentIds, parameters, output_depIds, input_depIds, input_deps); // ------------------------------- // REGULAR FRAGMENTS // ------------------------------- } else { result = this.executePlanFragments(ts, undoToken, fragmentIds.length, fragmentIds, parameters, output_depIds, input_depIds, input_deps); if (result == null) { LOG.warn(String.format("Output DependencySet for %s in %s is null?", Arrays.toString(fragmentIds), ts)); } } return (result); } /** * Execute a BatchPlan directly on this PartitionExecutor without having to covert it * to WorkFragments first. This is big speed improvement over having to queue things up * @param ts * @param plan * @return */ private VoltTable[] executeLocalPlan(LocalTransaction ts, BatchPlanner.BatchPlan plan, ParameterSet parameterSets[]) { // Start the new execution round long undoToken = this.calculateNextUndoToken(ts, plan.isReadOnly()); ts.initFirstRound(undoToken, plan.getBatchSize()); int fragmentCount = plan.getFragmentCount(); long fragmentIds[] = plan.getFragmentIds(); int output_depIds[] = plan.getOutputDependencyIds(); int input_depIds[] = plan.getInputDependencyIds(); // Mark that we touched the local partition once for each query in the batch // ts.getTouchedPartitions().put(this.partitionId, plan.getBatchSize()); // Only notify other partitions that we're done with them if we're not // a single-partition transaction if (hstore_conf.site.specexec_enable && ts.isPredictSinglePartition() == false) { //FIXME //PartitionSet new_done = ts.calculateDonePartitions(this.thresholds); //if (new_done != null && new_done.isEmpty() == false) { // LocalPrepareCallback callback = ts.getPrepareCallback(); // assert(callback.isInitialized()); // this.hstore_coordinator.transactionPrepare(ts, callback, new_done); //} } if (trace.val) LOG.trace(String.format("Txn #%d - BATCHPLAN:\n" + " fragmentIds: %s\n" + " fragmentCount: %s\n" + " output_depIds: %s\n" + " input_depIds: %s", ts.getTransactionId(), Arrays.toString(plan.getFragmentIds()), plan.getFragmentCount(), Arrays.toString(plan.getOutputDependencyIds()), Arrays.toString(plan.getInputDependencyIds()))); // NOTE: There are no dependencies that we need to pass in because the entire // batch is local to this partition. DependencySet result = null; try { result = this.executePlanFragments(ts, undoToken, fragmentCount, fragmentIds, parameterSets, output_depIds, input_depIds, null); } finally { ts.fastFinishRound(this.partitionId); } // assert(result != null) : "Unexpected null DependencySet result for " + ts; if (trace.val) LOG.trace("Output:\n" + result); return (result != null ? result.dependencies : null); } /** * Execute the given fragment tasks on this site's underlying EE * @param ts * @param undoToken * @param batchSize * @param fragmentIds * @param parameterSets * @param output_depIds * @param input_depIds * @return */ private DependencySet executeSysProcFragments(AbstractTransaction ts, long undoToken, int batchSize, long fragmentIds[], ParameterSet parameters[], int output_depIds[], int input_depIds[], Map<Integer, List<VoltTable>> input_deps) { assert(fragmentIds.length == 1); assert(fragmentIds.length == parameters.length) : String.format("%s - Fragments:%d / Parameters:%d", ts, fragmentIds.length, parameters.length); VoltSystemProcedure volt_proc = this.m_registeredSysProcPlanFragments.get(fragmentIds[0]); if (volt_proc == null) { String msg = "No sysproc handle exists for FragmentID #" + fragmentIds[0] + " :: " + this.m_registeredSysProcPlanFragments; throw new ServerFaultException(msg, ts.getTransactionId()); } // HACK: We have to set the TransactionState for sysprocs manually volt_proc.setTransactionState(ts); ts.markExecNotReadOnly(this.partitionId); DependencySet result = null; try { result = volt_proc.executePlanFragment(ts.getTransactionId(), this.tmp_EEdependencies, (int)fragmentIds[0], parameters[0], this.m_systemProcedureContext); } catch (Throwable ex) { String msg = "Unexpected error when executing system procedure"; throw new ServerFaultException(msg, ex, ts.getTransactionId()); } if (debug.val) LOG.debug(String.format("%s - Finished executing sysproc fragment for %s (#%d)%s", ts, m_registeredSysProcPlanFragments.get(fragmentIds[0]).getClass().getSimpleName(), fragmentIds[0], (trace.val ? "\n" + result : ""))); return (result); } /** * Execute the given fragment tasks on this site's underlying EE * @param ts * @param undoToken * @param batchSize * @param fragmentIds * @param parameterSets * @param output_depIds * @param input_depIds * @return */ private DependencySet executePlanFragments(AbstractTransaction ts, long undoToken, int batchSize, long fragmentIds[], ParameterSet parameterSets[], int output_depIds[], int input_depIds[], Map<Integer, List<VoltTable>> input_deps) { assert(this.ee != null) : "The EE object is null. This is bad!"; Long txn_id = ts.getTransactionId(); //LOG.info("in executePlanFragments()"); // *********************************** DEBUG *********************************** if (debug.val) { StringBuilder sb = new StringBuilder(); sb.append(String.format("%s - Executing %d fragments [lastTxnId=%d, undoToken=%d]", ts, batchSize, this.lastCommittedTxnId, undoToken)); // if (trace.val) { Map<String, Object> m = new LinkedHashMap<String, Object>(); m.put("Fragments", Arrays.toString(fragmentIds)); Map<Integer, Object> inner = new LinkedHashMap<Integer, Object>(); for (int i = 0; i < batchSize; i++) inner.put(i, parameterSets[i].toString()); m.put("Parameters", inner); if (batchSize > 0 && input_depIds[0] != HStoreConstants.NULL_DEPENDENCY_ID) { inner = new LinkedHashMap<Integer, Object>(); for (int i = 0; i < batchSize; i++) { List<VoltTable> deps = input_deps.get(input_depIds[i]); inner.put(input_depIds[i], (deps != null ? StringUtil.join("\n", deps) : "???")); } // FOR m.put("Input Dependencies", inner); } m.put("Output Dependencies", Arrays.toString(output_depIds)); sb.append("\n" + StringUtil.formatMaps(m)); // } LOG.debug(sb.toString().trim()); } // *********************************** DEBUG *********************************** // pass attached dependencies to the EE (for non-sysproc work). if (input_deps != null && input_deps.isEmpty() == false) { if (debug.val) LOG.debug(String.format("%s - Stashing %d InputDependencies at partition %d", ts, input_deps.size(), this.partitionId)); this.ee.stashWorkUnitDependencies(input_deps); } // Java-based Table Read-Write Sets boolean readonly = true; boolean speculative = ts.isSpeculative(); boolean singlePartition = ts.isPredictSinglePartition(); int tableIds[] = null; for (int i = 0; i < batchSize; i++) { boolean fragReadOnly = PlanFragmentIdGenerator.isPlanFragmentReadOnly(fragmentIds[i]); // We don't need to maintain read/write sets for non-speculative txns if (speculative || singlePartition == false) { if (fragReadOnly) { tableIds = catalogContext.getReadTableIds(Long.valueOf(fragmentIds[i])); if (tableIds != null) ts.markTableIdsRead(this.partitionId, tableIds); } else { tableIds = catalogContext.getWriteTableIds(Long.valueOf(fragmentIds[i])); if (tableIds != null) ts.markTableIdsWritten(this.partitionId, tableIds); } } readonly = readonly && fragReadOnly; } // Enable read/write set tracking if (hstore_conf.site.exec_readwrite_tracking && ts.hasExecutedWork(this.partitionId) == false) { if (trace.val) LOG.trace(String.format("%s - Enabling read/write set tracking in EE at partition %d", ts, this.partitionId)); this.ee.trackingEnable(txn_id); } // Check whether the txn has only exeuted read-only queries up to this point if (ts.isExecReadOnly(this.partitionId)) { if (readonly == false) { if (trace.val) LOG.trace(String.format("%s - Marking txn as not read-only %s", ts, Arrays.toString(fragmentIds))); ts.markExecNotReadOnly(this.partitionId); } // We can do this here because the only way that we're not read-only is if // we actually modify data at this partition ts.markExecutedWork(this.partitionId); } DependencySet result = null; boolean needs_profiling = false; if (ts.isExecLocal(this.partitionId)) { if (hstore_conf.site.txn_profiling && ((LocalTransaction)ts).profiler != null) { needs_profiling = true; ((LocalTransaction)ts).profiler.startExecEE(); } } Throwable error = null; try { assert(this.lastCommittedUndoToken < undoToken) : String.format("Trying to execute work using undoToken %d for %s but " + "it is less than the last committed undoToken %d at partition %d", undoToken, ts, this.lastCommittedUndoToken, this.partitionId); if (trace.val) LOG.trace(String.format("%s - Executing fragments %s at partition %d [undoToken=%d]", ts, Arrays.toString(fragmentIds), this.partitionId, undoToken)); result = this.ee.executeQueryPlanFragmentsAndGetDependencySet( fragmentIds, batchSize, input_depIds, output_depIds, parameterSets, batchSize, txn_id.longValue(), this.lastCommittedTxnId.longValue(), undoToken); } catch (AssertionError ex) { LOG.error("Fatal error when processing " + ts + "\n" + ts.debug()); error = ex; throw ex; } catch (EvictedTupleAccessException ex) { if (debug.val) LOG.warn("Caught EvictedTupleAccessException."); error = ex; throw ex; } catch (SerializableException ex) { if (debug.val) LOG.error(String.format("%s - Unexpected error in the ExecutionEngine on partition %d", ts, this.partitionId), ex); error = ex; throw ex; } catch (Throwable ex) { error = ex; String msg = String.format("%s - Failed to execute PlanFragments: %s", ts, Arrays.toString(fragmentIds)); throw new ServerFaultException(msg, ex); } finally { if (needs_profiling) ((LocalTransaction)ts).profiler.stopExecEE(); if (error == null && result == null) { LOG.warn(String.format("%s - Finished executing fragments but got back null results [fragmentIds=%s]", ts, Arrays.toString(fragmentIds))); } } // *********************************** DEBUG *********************************** if (debug.val) { if (result != null) { LOG.debug(String.format("%s - Finished executing fragments and got back %d results", ts, result.depIds.length)); } else { LOG.warn(String.format("%s - Finished executing fragments but got back null results? That seems bad...", ts)); } } // *********************************** DEBUG *********************************** return (result); } /** * Load a VoltTable directly into the EE at this partition. * <B>NOTE:</B> This should only be invoked by a system stored procedure. * @param txn_id * @param clusterName * @param databaseName * @param tableName * @param data * @param allowELT * @throws VoltAbortException */ public void loadTable(AbstractTransaction ts, String clusterName, String databaseName, String tableName, VoltTable data, int allowELT) throws VoltAbortException { Table table = this.catalogContext.database.getTables().getIgnoreCase(tableName); if (table == null) { throw new VoltAbortException("Table '" + tableName + "' does not exist in database " + clusterName + "." + databaseName); } if (debug.val) LOG.debug(String.format("Loading %d row(s) into %s [txnId=%d]", data.getRowCount(), table.getName(), ts.getTransactionId())); ts.markExecutedWork(this.partitionId); this.ee.loadTable(table.getRelativeIndex(), data, ts.getTransactionId(), this.lastCommittedTxnId.longValue(), ts.getLastUndoToken(this.partitionId), allowELT != 0); } /** * Load a VoltTable directly into the EE at this partition. * <B>NOTE:</B> This should only be used for testing * @param txnId * @param table * @param data * @param allowELT * @throws VoltAbortException */ protected void loadTable(Long txnId, Table table, VoltTable data, boolean allowELT) throws VoltAbortException { if (debug.val) LOG.debug(String.format("Loading %d row(s) into %s [txnId=%d]", data.getRowCount(), table.getName(), txnId)); this.ee.loadTable(table.getRelativeIndex(), data, txnId.longValue(), this.lastCommittedTxnId.longValue(), HStoreConstants.NULL_UNDO_LOGGING_TOKEN, allowELT); } /** * Execute a SQLStmt batch at this partition. This is the main entry point from * VoltProcedure for where we will execute a SQLStmt batch from a txn. * @param ts The txn handle that is executing this query batch * @param batchSize The number of SQLStmts that the txn queued up using voltQueueSQL() * @param batchStmts The SQLStmts that the txn is trying to execute * @param batchParams The input parameters for the SQLStmts * @param finalTask Whether the txn has marked this as the last batch that they will ever execute * @param forceSinglePartition Whether to force the BatchPlanner to only generate a single-partition plan * @return */ public VoltTable[] executeSQLStmtBatch(LocalTransaction ts, int batchSize, SQLStmt batchStmts[], ParameterSet batchParams[], boolean finalTask, boolean forceSinglePartition) { boolean needs_profiling = (hstore_conf.site.txn_profiling && ts.profiler != null); if (needs_profiling) { ts.profiler.addBatch(batchSize); ts.profiler.stopExecJava(); ts.profiler.startExecPlanning(); } // HACK: This is needed to handle updates on replicated tables properly // when there is only one partition in the cluster. if (catalogContext.numberOfPartitions == 1) { this.depTracker.addTransaction(ts); } if (hstore_conf.site.exec_deferrable_queries) { // TODO: Loop through batchStmts and check whether their corresponding Statement // is marked as deferrable. If so, then remove them from batchStmts and batchParams // (sliding everyone over by one in the arrays). Queue up the deferred query. // Be sure decrement batchSize after you finished processing this. // EXAMPLE: batchStmts[0].getStatement().getDeferrable() } // Calculate the hash code for this batch to see whether we already have a planner final Integer batchHashCode = VoltProcedure.getBatchHashCode(batchStmts, batchSize); BatchPlanner planner = this.batchPlanners.get(batchHashCode); if (planner == null) { // Assume fast case planner = new BatchPlanner(batchStmts, batchSize, ts.getProcedure(), this.p_estimator, forceSinglePartition); this.batchPlanners.put(batchHashCode, planner); } assert(planner != null); // At this point we have to calculate exactly what we need to do on each partition // for this batch. So somehow right now we need to fire this off to either our // local executor or to Evan's magical distributed transaction manager BatchPlanner.BatchPlan plan = planner.plan(ts.getTransactionId(), this.partitionId, ts.getPredictTouchedPartitions(), ts.getTouchedPartitions(), batchParams); assert(plan != null); if (trace.val) { LOG.trace(ts + " - Touched Partitions: " + ts.getTouchedPartitions().values()); LOG.trace(ts + " - Next BatchPlan:\n" + plan.toString()); } if (needs_profiling) ts.profiler.stopExecPlanning(); // Tell the TransactionEstimator that we're about to execute these mofos EstimatorState t_state = ts.getEstimatorState(); if (this.localTxnEstimator != null && t_state != null && t_state.isUpdatesEnabled()) { if (needs_profiling) ts.profiler.startExecEstimation(); try { this.localTxnEstimator.executeQueries(t_state, planner.getStatements(), plan.getStatementPartitions()); } finally { if (needs_profiling) ts.profiler.stopExecEstimation(); } } else if (t_state != null && t_state.shouldAllowUpdates()) { LOG.warn("Skipping estimator updates for " + ts); } // Check whether our plan was caused a mispredict // Doing it this way allows us to update the TransactionEstimator before we abort the txn if (plan.getMisprediction() != null) { MispredictionException ex = plan.getMisprediction(); ts.setPendingError(ex, false); assert(ex.getPartitions().isEmpty() == false) : "Unexpected empty PartitionSet for mispredicated txn " + ts; // Print Misprediction Debug if (hstore_conf.site.exec_mispredict_crash) { // Use a lock so that only dump out the first txn that fails synchronized (PartitionExecutor.class) { LOG.warn("\n" + EstimatorUtil.mispredictDebug(ts, planner, batchStmts, batchParams)); LOG.fatal(String.format("Crashing because site.exec_mispredict_crash is true [txn=%s]", ts)); this.crash(ex); } // SYNCH } else if (debug.val) { if (trace.val) LOG.warn("\n" + EstimatorUtil.mispredictDebug(ts, planner, batchStmts, batchParams)); LOG.debug(ts + " - Aborting and restarting mispredicted txn."); } throw ex; } // Keep track of the number of times that we've executed each query for this transaction int stmtCounters[] = this.tmp_stmtCounters.getArray(batchSize); for (int i = 0; i < batchSize; i++) { stmtCounters[i] = ts.updateStatementCounter(batchStmts[i].getStatement()); } // FOR if (ts.hasPrefetchQueries()) { PartitionSet stmtPartitions[] = plan.getStatementPartitions(); PrefetchState prefetchState = ts.getPrefetchState(); QueryTracker queryTracker = prefetchState.getExecQueryTracker(); assert(prefetchState != null); for (int i = 0; i < batchSize; i++) { // We always have to update the query tracker regardless of whether // the query was prefetched or not. This is so that we can ensure // that we execute the queries in the right order. Statement stmt = batchStmts[i].getStatement(); stmtCounters[i] = queryTracker.addQuery(stmt, stmtPartitions[i], batchParams[i]); } // FOR // FIXME PrefetchQueryUtil.checkSQLStmtBatch(this, ts, plan, batchSize, batchStmts, batchParams); } // PREFETCH VoltTable results[] = null; // FAST-PATH: Single-partition + Local // If the BatchPlan only has WorkFragments that are for this partition, then // we can use the fast-path executeLocalPlan() method if (plan.isSingledPartitionedAndLocal()) { if (trace.val) LOG.trace(String.format("%s - Sending %s directly to the ExecutionEngine at partition %d", ts, plan.getClass().getSimpleName(), this.partitionId)); // If this the finalTask flag is set to true, and we're only executing queries at this // partition, then we need to notify the other partitions that we're done with them. if (hstore_conf.site.exec_early_prepare && finalTask == true && ts.isPredictSinglePartition() == false && ts.isSysProc() == false && ts.allowEarlyPrepare() == true) { tmp_fragmentsPerPartition.clearValues(); tmp_fragmentsPerPartition.put(this.partitionId, batchSize); DonePartitionsNotification notify = this.computeDonePartitions(ts, null, tmp_fragmentsPerPartition, finalTask); if (notify != null && notify.hasSitesToNotify()) this.notifyDonePartitions(ts, notify); } // Execute the queries right away. results = this.executeLocalPlan(ts, plan, batchParams); } // DISTRIBUTED EXECUTION // Otherwise, we need to generate WorkFragments and then send the messages out // to our remote partitions using the HStoreCoordinator else { ExecutionState execState = ts.getExecutionState(); execState.tmp_partitionFragments.clear(); plan.getWorkFragmentsBuilders(ts.getTransactionId(), stmtCounters, execState.tmp_partitionFragments); if (debug.val) LOG.debug(String.format("%s - Using dispatchWorkFragments to execute %d %ss", ts, execState.tmp_partitionFragments.size(), WorkFragment.class.getSimpleName())); if (needs_profiling) { int remote_cnt = 0; PartitionSet stmtPartitions[] = plan.getStatementPartitions(); for (int i = 0; i < batchSize; i++) { if (stmtPartitions[i].get() != ts.getBasePartition()) remote_cnt++; if (trace.val) LOG.trace(String.format("%s - [%02d] stmt:%s / partitions:%s", ts, i, batchStmts[i].getStatement().getName(), stmtPartitions[i])); } // FOR if (trace.val) LOG.trace(String.format("%s - Remote Queries Count = %d", ts, remote_cnt)); ts.profiler.addRemoteQuery(remote_cnt); } // Block until we get all of our responses. results = this.dispatchWorkFragments(ts, batchSize, batchParams, execState.tmp_partitionFragments, finalTask); } if (debug.val && results == null) LOG.warn("Got back a null results array for " + ts + "\n" + plan.toString()); if (needs_profiling) ts.profiler.startExecJava(); return (results); } /** * * @param fresponse */ protected WorkResult buildWorkResult(AbstractTransaction ts, DependencySet result, Status status, SerializableException error) { WorkResult.Builder builder = WorkResult.newBuilder(); // Partition Id builder.setPartitionId(this.partitionId); // Status builder.setStatus(status); // SerializableException if (error != null) { int size = error.getSerializedSize(); BBContainer bc = this.buffer_pool.acquire(size); try { error.serializeToBuffer(bc.b); } catch (IOException ex) { String msg = "Failed to serialize error for " + ts; throw new ServerFaultException(msg, ex); } bc.b.rewind(); builder.setError(ByteString.copyFrom(bc.b)); bc.discard(); } // Push dependencies back to the remote partition that needs it if (status == Status.OK) { for (int i = 0, cnt = result.size(); i < cnt; i++) { builder.addDepId(result.depIds[i]); this.fs.clear(); try { result.dependencies[i].writeExternal(this.fs); ByteString bs = ByteString.copyFrom(this.fs.getBBContainer().b); builder.addDepData(bs); } catch (Exception ex) { throw new ServerFaultException(String.format("Failed to serialize output dependency %d for %s", result.depIds[i], ts), ex); } if (trace.val) LOG.trace(String.format("%s - Serialized Output Dependency %d\n%s", ts, result.depIds[i], result.dependencies[i])); } // FOR this.fs.getBBContainer().discard(); } return (builder.build()); } /** * This method is invoked when the PartitionExecutor wants to execute work at a remote HStoreSite. * The doneNotificationsPerSite is an array where each offset (based on SiteId) may contain * a PartitionSet of the partitions that this txn is finished with at the remote node and will * not be executing any work in the current batch. * @param ts * @param fragmentBuilders * @param parameterSets * @param doneNotificationsPerSite */ private void requestWork(LocalTransaction ts, Collection<WorkFragment.Builder> fragmentBuilders, List<ByteString> parameterSets, DonePartitionsNotification notify) { assert(fragmentBuilders.isEmpty() == false); assert(ts != null); Long txn_id = ts.getTransactionId(); if (trace.val) LOG.trace(String.format("%s - Wrapping %d %s into a %s", ts, fragmentBuilders.size(), WorkFragment.class.getSimpleName(), TransactionWorkRequest.class.getSimpleName())); // If our transaction was originally designated as a single-partitioned, then we need to make // sure that we don't touch any partition other than our local one. If we do, then we need abort // it and restart it as multi-partitioned boolean need_restart = false; boolean predict_singlepartition = ts.isPredictSinglePartition(); PartitionSet done_partitions = ts.getDonePartitions(); Estimate t_estimate = ts.getLastEstimate(); // Now we can go back through and start running all of the WorkFragments that were not blocked // waiting for an input dependency. Note that we pack all the fragments into a single // CoordinatorFragment rather than sending each WorkFragment in its own message for (WorkFragment.Builder fragmentBuilder : fragmentBuilders) { assert(this.depTracker.isBlocked(ts, fragmentBuilder) == false); final int target_partition = fragmentBuilder.getPartitionId(); final int target_site = catalogContext.getSiteIdForPartitionId(target_partition); final PartitionSet doneNotifications = (notify != null ? notify.getNotifications(target_site) : null); // Make sure that this isn't a single-partition txn trying to access a remote partition if (predict_singlepartition && target_partition != this.partitionId) { if (debug.val) LOG.debug(String.format("%s - Txn on partition %d is suppose to be " + "single-partitioned, but it wants to execute a fragment on partition %d", ts, this.partitionId, target_partition)); need_restart = true; break; } // Make sure that this txn isn't trying to access a partition that we said we were // done with earlier else if (done_partitions.contains(target_partition)) { if (debug.val) LOG.warn(String.format("%s on partition %d was marked as done on partition %d " + "but now it wants to go back for more!", ts, this.partitionId, target_partition)); need_restart = true; break; } // Make sure we at least have something to do! else if (fragmentBuilder.getFragmentIdCount() == 0) { LOG.warn(String.format("%s - Trying to send a WorkFragment request with 0 fragments", ts)); continue; } // Add in the specexec query estimate at this partition if needed if (hstore_conf.site.specexec_enable && t_estimate != null && t_estimate.hasQueryEstimate(target_partition)) { List<CountedStatement> queryEst = t_estimate.getQueryEstimate(target_partition); // if (debug.val) if (target_partition == 0) if (debug.val) LOG.debug(String.format("%s - Sending remote query estimate to partition %d " + "containing %d queries\n%s", ts, target_partition, queryEst.size(), StringUtil.join("\n", queryEst))); assert(queryEst.isEmpty() == false); QueryEstimate.Builder estBuilder = QueryEstimate.newBuilder(); for (CountedStatement countedStmt : queryEst) { estBuilder.addStmtIds(countedStmt.statement.getId()); estBuilder.addStmtCounters(countedStmt.counter); } // FOR fragmentBuilder.setFutureStatements(estBuilder); } // Get the TransactionWorkRequest.Builder for the remote HStoreSite // We will use this store our serialized input dependencies TransactionWorkRequestBuilder requestBuilder = tmp_transactionRequestBuilders[target_site]; if (requestBuilder == null) { requestBuilder = tmp_transactionRequestBuilders[target_site] = new TransactionWorkRequestBuilder(); } TransactionWorkRequest.Builder builder = requestBuilder.getBuilder(ts, doneNotifications); // Also keep track of what Statements they are executing so that we know // we need to send over the wire to them. requestBuilder.addParamIndexes(fragmentBuilder.getParamIndexList()); // Input Dependencies if (fragmentBuilder.getNeedsInput()) { if (debug.val) LOG.debug(String.format("%s - Retrieving input dependencies at partition %d", ts, this.partitionId)); tmp_removeDependenciesMap.clear(); for (int i = 0, cnt = fragmentBuilder.getInputDepIdCount(); i < cnt; i++) { this.getFragmentInputs(ts, fragmentBuilder.getInputDepId(i), tmp_removeDependenciesMap); } // FOR for (Entry<Integer, List<VoltTable>> e : tmp_removeDependenciesMap.entrySet()) { if (requestBuilder.hasInputDependencyId(e.getKey())) continue; if (debug.val) LOG.debug(String.format("%s - Attaching %d input dependencies to be sent to %s", ts, e.getValue().size(), HStoreThreadManager.formatSiteName(target_site))); for (VoltTable vt : e.getValue()) { this.fs.clear(); try { this.fs.writeObject(vt); builder.addAttachedDepId(e.getKey().intValue()); builder.addAttachedData(ByteString.copyFrom(this.fs.getBBContainer().b)); } catch (Exception ex) { String msg = String.format("Failed to serialize input dependency %d for %s", e.getKey(), ts); throw new ServerFaultException(msg, ts.getTransactionId()); } if (debug.val) LOG.debug(String.format("%s - Storing %d rows for InputDependency %d to send " + "to partition %d [bytes=%d]", ts, vt.getRowCount(), e.getKey(), fragmentBuilder.getPartitionId(), CollectionUtil.last(builder.getAttachedDataList()).size())); } // FOR requestBuilder.addInputDependencyId(e.getKey()); } // FOR this.fs.getBBContainer().discard(); } builder.addFragments(fragmentBuilder); } // FOR (tasks) // Bad mojo! We need to throw a MispredictionException so that the VoltProcedure // will catch it and we can propagate the error message all the way back to the HStoreSite if (need_restart) { if (trace.val) LOG.trace(String.format("Aborting %s because it was mispredicted", ts)); // This is kind of screwy because we don't actually want to send the touched partitions // histogram because VoltProcedure will just do it for us... throw new MispredictionException(txn_id, null); } // Stick on the ParameterSets that each site needs into the TransactionWorkRequest for (int target_site = 0; target_site < tmp_transactionRequestBuilders.length; target_site++) { TransactionWorkRequestBuilder builder = tmp_transactionRequestBuilders[target_site]; if (builder == null || builder.isDirty() == false) { continue; } assert(builder != null); builder.addParameterSets(parameterSets); // Bombs away! this.hstore_coordinator.transactionWork(ts, target_site, builder.build(), this.request_work_callback); if (debug.val) LOG.debug(String.format("%s - Sent Work request to remote site %s", ts, HStoreThreadManager.formatSiteName(target_site))); } // FOR } /** * Figure out what partitions this transaction is done with. This will only return * a PartitionSet of what partitions we think we're done with. * For each partition that we idenitfy that the txn is done with, we will check to see * whether the txn is going to execute a query at its site in this batch. If it's not, * then we will notify that HStoreSite through the HStoreCoordinator. * If the partition that it doesn't need anymore is local (i.e., it's at the same * HStoreSite that we're at right now), then we'll just pass them a quick message * to let them know that they can prepare the txn. * @param ts * @param estimate * @param fragmentsPerPartition A histogram of the number of PlanFragments the * txn will execute in this batch at each partition. * @param finalTask Whether the txn has marked this as the last batch that they will ever execute * @return A notification object that can be used to notify partitions that this txn is done with them. */ private DonePartitionsNotification computeDonePartitions(final LocalTransaction ts, final Estimate estimate, final FastIntHistogram fragmentsPerPartition, final boolean finalTask) { final PartitionSet touchedPartitions = ts.getPredictTouchedPartitions(); final PartitionSet donePartitions = ts.getDonePartitions(); // Compute the partitions that the txn will be finished with after this batch PartitionSet estDonePartitions = null; // If the finalTask flag is set to true, then the new done partitions // is every partition that this txn has locked if (finalTask) { - estDonePartitions = touchedPartitions; + estDonePartitions = new PartitionSet(touchedPartitions); } // Otherwise, we'll rely on the transaction's current estimate to figure it out. else { if (estimate == null || estimate.isValid() == false) { if (debug.val) LOG.debug(String.format("%s - Unable to compute new done partitions because there " + "is no valid estimate for the txn", ts, estimate.getClass().getSimpleName())); return (null); } estDonePartitions = estimate.getDonePartitions(this.thresholds); if (estDonePartitions == null || estDonePartitions.isEmpty()) { if (debug.val) LOG.debug(String.format("%s - There are no new done partitions identified by %s", ts, estimate.getClass().getSimpleName())); return (null); } } assert(estDonePartitions != null) : "Null done partitions for " + ts; assert(estDonePartitions.isEmpty() == false) : "Empty done partitions for " + ts; if (debug.val) LOG.debug(String.format("%s - New estimated done partitions %s%s", ts, estDonePartitions, (trace.val ? "\n"+estimate : ""))); // Note that we can actually be done with ourself, if this txn is only going to execute queries // at remote partitions. But we can't actually execute anything because this partition's only // execution thread is going to be blocked. So we always do this so that we're not sending a // useless message estDonePartitions.remove(this.partitionId); // Make sure that we only tell partitions that we actually touched, otherwise they will // be stuck waiting for a finish request that will never come! DonePartitionsNotification notify = new DonePartitionsNotification(); for (int partition : estDonePartitions.values()) { // Only mark the txn done at this partition if the Estimate says we were done // with it after executing this batch and it's a partition that we've locked. if (donePartitions.contains(partition) || touchedPartitions.contains(partition) == false) continue; if (trace.val) LOG.trace(String.format("%s - Marking partition %d as done for txn", ts, partition)); notify.donePartitions.add(partition); if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.markEarly2PCPartition(partition); // Check whether we're executing a query at this partition in this batch. // If we're not, then we need to check whether we can piggyback the "done" message // in another WorkFragment going to that partition or whether we have to // send a separate TransactionPrepareRequest if (fragmentsPerPartition.get(partition, 0) == 0) { // We need to let them know that the party is over! if (hstore_site.isLocalPartition(partition)) { // if (debug.val) LOG.info(String.format("%s - Notifying local partition %d that txn is finished it", ts, partition)); hstore_site.getPartitionExecutor(partition).queuePrepare(ts); } // Check whether we can piggyback on another WorkFragment that is going to // the same site else { Site remoteSite = catalogContext.getSiteForPartition(partition); boolean found = false; for (Partition remotePartition : remoteSite.getPartitions().values()) { if (fragmentsPerPartition.get(remotePartition.getId(), 0) != 0) { found = true; break; } } // FOR notify.addSiteNotification(remoteSite, partition, (found == false)); } } } // FOR return (notify); } /** * Send asynchronous notification messages to any remote site to tell them that we * are done with partitions that they have. * @param ts * @param notify */ private void notifyDonePartitions(LocalTransaction ts, DonePartitionsNotification notify) { // BLAST OUT NOTIFICATIONS! for (int remoteSiteId : notify._sitesToNotify) { assert(notify.notificationsPerSite[remoteSiteId] != null); if (debug.val) LOG.info(String.format("%s - Notifying %s that txn is finished with partitions %s", ts, HStoreThreadManager.formatSiteName(remoteSiteId), notify.notificationsPerSite[remoteSiteId])); hstore_coordinator.transactionPrepare(ts, ts.getPrepareCallback(), notify.notificationsPerSite[remoteSiteId]); // Make sure that we remove the PartitionSet for this site so that we don't // try to send the notifications again. notify.notificationsPerSite[remoteSiteId] = null; } // FOR } /** * Execute the given tasks and then block the current thread waiting for the list of dependency_ids to come * back from whatever it was we were suppose to do... * This is the slowest way to execute a bunch of WorkFragments and therefore should only be invoked * for batches that need to access non-local partitions * @param ts The txn handle that is executing this query batch * @param batchSize The number of SQLStmts that the txn queued up using voltQueueSQL() * @param batchParams The input parameters for the SQLStmts * @param allFragmentBuilders * @param finalTask Whether the txn has marked this as the last batch that they will ever execute * @return */ public VoltTable[] dispatchWorkFragments(final LocalTransaction ts, final int batchSize, final ParameterSet batchParams[], final Collection<WorkFragment.Builder> allFragmentBuilders, boolean finalTask) { assert(allFragmentBuilders.isEmpty() == false) : "Unexpected empty WorkFragment list for " + ts; final boolean needs_profiling = (hstore_conf.site.txn_profiling && ts.profiler != null); // *********************************** DEBUG *********************************** if (debug.val) { LOG.debug(String.format("%s - Preparing to dispatch %d messages and wait for the results [needsProfiling=%s]", ts, allFragmentBuilders.size(), needs_profiling)); if (trace.val) { StringBuilder sb = new StringBuilder(); sb.append(ts + " - WorkFragments:\n"); for (WorkFragment.Builder fragment : allFragmentBuilders) { sb.append(StringBoxUtil.box(fragment.toString()) + "\n"); } // FOR sb.append(ts + " - ParameterSets:\n"); for (ParameterSet ps : batchParams) { sb.append(ps + "\n"); } // FOR LOG.trace(sb); } } // *********************************** DEBUG *********************************** // OPTIONAL: Check to make sure that this request is valid // (1) At least one of the WorkFragments needs to be executed on a remote partition // (2) All of the PlanFragments ids in the WorkFragments match this txn's Procedure if (hstore_conf.site.exec_validate_work && ts.isSysProc() == false) { LOG.warn(String.format("%s - Checking whether all of the WorkFragments are valid", ts)); boolean has_remote = false; for (WorkFragment.Builder frag : allFragmentBuilders) { if (frag.getPartitionId() != this.partitionId) { has_remote = true; } for (int frag_id : frag.getFragmentIdList()) { PlanFragment catalog_frag = CatalogUtil.getPlanFragment(catalogContext.database, frag_id); Statement catalog_stmt = catalog_frag.getParent(); assert(catalog_stmt != null); Procedure catalog_proc = catalog_stmt.getParent(); if (catalog_proc.equals(ts.getProcedure()) == false) { LOG.warn(ts.debug() + "\n" + allFragmentBuilders + "\n---- INVALID ----\n" + frag); String msg = String.format("%s - Unexpected %s", ts, catalog_frag.fullName()); throw new ServerFaultException(msg, ts.getTransactionId()); } } } // FOR if (has_remote == false) { LOG.warn(ts.debug() + "\n" + allFragmentBuilders); String msg = ts + "Trying to execute all local single-partition queries using the slow-path!"; throw new ServerFaultException(msg, ts.getTransactionId()); } } boolean first = true; boolean serializedParams = false; CountDownLatch latch = null; boolean all_local = true; boolean is_localSite; boolean is_localPartition; boolean is_localReadOnly = true; int num_localPartition = 0; int num_localSite = 0; int num_remote = 0; int num_skipped = 0; int total = 0; Collection<WorkFragment.Builder> fragmentBuilders = allFragmentBuilders; // Make sure our txn is in our DependencyTracker if (trace.val) LOG.trace(String.format("%s - Added transaction to %s", ts, this.depTracker.getClass().getSimpleName())); this.depTracker.addTransaction(ts); // Count the number of fragments that we're going to send to each partition and // figure out whether the txn will always be read-only at this partition tmp_fragmentsPerPartition.clearValues(); for (WorkFragment.Builder fragmentBuilder : allFragmentBuilders) { int partition = fragmentBuilder.getPartitionId(); tmp_fragmentsPerPartition.put(partition); if (this.partitionId == partition && fragmentBuilder.getReadOnly() == false) { is_localReadOnly = false; } } // FOR long undoToken = this.calculateNextUndoToken(ts, is_localReadOnly); ts.initFirstRound(undoToken, batchSize); final boolean predict_singlePartition = ts.isPredictSinglePartition(); // Calculate whether we are finished with partitions now final Estimate lastEstimate = ts.getLastEstimate(); DonePartitionsNotification notify = null; if (hstore_conf.site.exec_early_prepare && ts.isSysProc() == false && ts.allowEarlyPrepare()) { notify = this.computeDonePartitions(ts, lastEstimate, tmp_fragmentsPerPartition, finalTask); if (notify != null && notify.hasSitesToNotify()) this.notifyDonePartitions(ts, notify); } // Attach the ParameterSets to our transaction handle so that anybody on this HStoreSite // can access them directly without needing to deserialize them from the WorkFragments ts.attachParameterSets(batchParams); // Now if we have some work sent out to other partitions, we need to wait until they come back // In the first part, we wait until all of our blocked WorkFragments become unblocked final BlockingDeque<Collection<WorkFragment.Builder>> queue = this.depTracker.getUnblockedWorkFragmentsQueue(ts); // Run through this loop if: // (1) We have no pending errors // (2) This is our first time in the loop (first == true) // (3) If we know that there are still messages being blocked // (4) If we know that there are still unblocked messages that we need to process // (5) The latch for this round is still greater than zero while (ts.hasPendingError() == false && (first == true || this.depTracker.stillHasWorkFragments(ts) || (latch != null && latch.getCount() > 0))) { if (trace.val) LOG.trace(String.format("%s - %s loop [first=%s, stillHasWorkFragments=%s, latch=%s]", ts, ClassUtil.getCurrentMethodName(), first, this.depTracker.stillHasWorkFragments(ts), queue.size(), latch)); // If this is the not first time through the loop, then poll the queue // to get our list of fragments if (first == false) { all_local = true; is_localSite = false; is_localPartition = false; num_localPartition = 0; num_localSite = 0; num_remote = 0; num_skipped = 0; total = 0; if (trace.val) LOG.trace(String.format("%s - Waiting for unblocked tasks on partition %d", ts, this.partitionId)); fragmentBuilders = queue.poll(); // NON-BLOCKING // If we didn't get back a list of fragments here, then we will spin through // and invoke utilityWork() to try to do something useful until what we need shows up if (needs_profiling) ts.profiler.startExecDtxnWork(); if (hstore_conf.site.exec_profiling) this.profiler.sp1_time.start(); try { while (fragmentBuilders == null) { // If there is more work that we could do, then we'll just poll the queue // without waiting so that we can go back and execute it again if we have // more time. if (this.utilityWork()) { fragmentBuilders = queue.poll(); } // Otherwise we will wait a little so that we don't spin the CPU else { fragmentBuilders = queue.poll(WORK_QUEUE_POLL_TIME, TimeUnit.MILLISECONDS); } } // WHILE } catch (InterruptedException ex) { if (this.hstore_site.isShuttingDown() == false) { LOG.error(String.format("%s - We were interrupted while waiting for blocked tasks", ts), ex); } return (null); } finally { if (needs_profiling) ts.profiler.stopExecDtxnWork(); if (hstore_conf.site.exec_profiling) this.profiler.sp1_time.stopIfStarted(); } } assert(fragmentBuilders != null); // If the list to fragments unblock is empty, then we // know that we have dispatched all of the WorkFragments for the // transaction's current SQLStmt batch. That means we can just wait // until all the results return to us. if (fragmentBuilders.isEmpty()) { if (trace.val) LOG.trace(String.format("%s - Got an empty list of WorkFragments at partition %d. " + "Blocking until dependencies arrive", ts, this.partitionId)); break; } this.tmp_localWorkFragmentBuilders.clear(); if (predict_singlePartition == false) { this.tmp_remoteFragmentBuilders.clear(); this.tmp_localSiteFragmentBuilders.clear(); } // ------------------------------- // FAST PATH: Assume everything is local // ------------------------------- if (predict_singlePartition) { for (WorkFragment.Builder fragmentBuilder : fragmentBuilders) { if (first == false || this.depTracker.addWorkFragment(ts, fragmentBuilder, batchParams)) { this.tmp_localWorkFragmentBuilders.add(fragmentBuilder); total++; num_localPartition++; } } // FOR // We have to tell the transaction handle to start the round before we send off the // WorkFragments for execution, since they might start executing locally! if (first) { ts.startRound(this.partitionId); latch = this.depTracker.getDependencyLatch(ts); } // Execute all of our WorkFragments quickly at our local ExecutionEngine for (WorkFragment.Builder fragmentBuilder : this.tmp_localWorkFragmentBuilders) { if (debug.val) LOG.debug(String.format("%s - Got unblocked %s to execute locally", ts, fragmentBuilder.getClass().getSimpleName())); assert(fragmentBuilder.getPartitionId() == this.partitionId) : String.format("Trying to process %s for %s on partition %d but it should have been " + "sent to partition %d [singlePartition=%s]\n%s", fragmentBuilder.getClass().getSimpleName(), ts, this.partitionId, fragmentBuilder.getPartitionId(), predict_singlePartition, fragmentBuilder); WorkFragment fragment = fragmentBuilder.build(); this.processWorkFragment(ts, fragment, batchParams); } // FOR } // ------------------------------- // SLOW PATH: Mixed local and remote messages // ------------------------------- else { // Look at each task and figure out whether it needs to be executed at a remote // HStoreSite or whether we can execute it at one of our local PartitionExecutors. for (WorkFragment.Builder fragmentBuilder : fragmentBuilders) { int partition = fragmentBuilder.getPartitionId(); is_localSite = hstore_site.isLocalPartition(partition); is_localPartition = (partition == this.partitionId); all_local = all_local && is_localPartition; // If this is the last WorkFragment that we're going to send to this partition for // this batch, then we will want to check whether we know that this is the last // time this txn will ever need to go to that txn. If so, then we'll want to if (notify != null && notify.donePartitions.contains(partition) && tmp_fragmentsPerPartition.dec(partition) == 0) { if (debug.val) LOG.debug(String.format("%s - Setting last fragment flag in %s for partition %d", ts, WorkFragment.class.getSimpleName(), partition)); fragmentBuilder.setLastFragment(true); } if (first == false || this.depTracker.addWorkFragment(ts, fragmentBuilder, batchParams)) { total++; // At this point we know that all the WorkFragment has been registered // in the LocalTransaction, so then it's safe for us to look to see // whether we already have a prefetched result that we need // if (prefetch && is_localPartition == false) { // boolean skip_queue = true; // for (int i = 0, cnt = fragmentBuilder.getFragmentIdCount(); i < cnt; i++) { // int fragId = fragmentBuilder.getFragmentId(i); // int paramIdx = fragmentBuilder.getParamIndex(i); // // VoltTable vt = this.queryCache.getResult(ts.getTransactionId(), // fragId, // partition, // parameters[paramIdx]); // if (vt != null) { // if (trace.val) // LOG.trace(String.format("%s - Storing cached result from partition %d for fragment %d", // ts, partition, fragId)); // this.depTracker.addResult(ts, partition, fragmentBuilder.getOutputDepId(i), vt); // } else { // skip_queue = false; // } // } // FOR // // If we were able to get cached results for all of the fragmentIds in // // this WorkFragment, then there is no need for us to send the message // // So we'll just skip queuing it up! How nice! // if (skip_queue) { // if (debug.val) // LOG.debug(String.format("%s - Using prefetch result for all fragments from partition %d", // ts, partition)); // num_skipped++; // continue; // } // } // Otherwise add it to our list of WorkFragments that we want // queue up right now if (is_localPartition) { is_localReadOnly = (is_localReadOnly && fragmentBuilder.getReadOnly()); this.tmp_localWorkFragmentBuilders.add(fragmentBuilder); num_localPartition++; } else if (is_localSite) { this.tmp_localSiteFragmentBuilders.add(fragmentBuilder); num_localSite++; } else { this.tmp_remoteFragmentBuilders.add(fragmentBuilder); num_remote++; } } } // FOR assert(total == (num_remote + num_localSite + num_localPartition + num_skipped)) : String.format("Total:%d / Remote:%d / LocalSite:%d / LocalPartition:%d / Skipped:%d", total, num_remote, num_localSite, num_localPartition, num_skipped); // We have to tell the txn to start the round before we send off the // WorkFragments for execution, since they might start executing locally! if (first) { ts.startRound(this.partitionId); latch = this.depTracker.getDependencyLatch(ts); } // Now request the fragments that aren't local // We want to push these out as soon as possible if (num_remote > 0) { // We only need to serialize the ParameterSets once if (serializedParams == false) { if (needs_profiling) ts.profiler.startSerialization(); tmp_serializedParams.clear(); for (int i = 0; i < batchParams.length; i++) { if (batchParams[i] == null) { tmp_serializedParams.add(ByteString.EMPTY); } else { this.fs.clear(); try { batchParams[i].writeExternal(this.fs); ByteString bs = ByteString.copyFrom(this.fs.getBBContainer().b); tmp_serializedParams.add(bs); } catch (Exception ex) { String msg = "Failed to serialize ParameterSet " + i + " for " + ts; throw new ServerFaultException(msg, ex, ts.getTransactionId()); } } } // FOR if (needs_profiling) ts.profiler.stopSerialization(); } if (trace.val) LOG.trace(String.format("%s - Requesting %d %s to be executed on remote partitions " + "[doneNotifications=%s]", ts, WorkFragment.class.getSimpleName(), num_remote, notify!=null)); this.requestWork(ts, tmp_remoteFragmentBuilders, tmp_serializedParams, notify); if (needs_profiling) ts.profiler.markRemoteQuery(); } // Then dispatch the task that are needed at the same HStoreSite but // at a different partition than this one if (num_localSite > 0) { if (trace.val) LOG.trace(String.format("%s - Executing %d WorkFragments on local site's partitions", ts, num_localSite)); for (WorkFragment.Builder builder : this.tmp_localSiteFragmentBuilders) { PartitionExecutor other = hstore_site.getPartitionExecutor(builder.getPartitionId()); other.queueWork(ts, builder.build()); } // FOR if (needs_profiling) ts.profiler.markRemoteQuery(); } // Then execute all of the tasks need to access the partitions at this HStoreSite // We'll dispatch the remote-partition-local-site fragments first because they're going // to need to get queued up by at the other PartitionExecutors if (num_localPartition > 0) { if (trace.val) LOG.trace(String.format("%s - Executing %d WorkFragments on local partition", ts, num_localPartition)); for (WorkFragment.Builder fragmentBuilder : this.tmp_localWorkFragmentBuilders) { this.processWorkFragment(ts, fragmentBuilder.build(), batchParams); } // FOR } } if (trace.val) LOG.trace(String.format("%s - Dispatched %d WorkFragments " + "[remoteSite=%d, localSite=%d, localPartition=%d]", ts, total, num_remote, num_localSite, num_localPartition)); first = false; } // WHILE this.fs.getBBContainer().discard(); if (trace.val) LOG.trace(String.format("%s - BREAK OUT [first=%s, stillHasWorkFragments=%s, latch=%s]", ts, first, this.depTracker.stillHasWorkFragments(ts), latch)); // assert(ts.stillHasWorkFragments() == false) : // String.format("Trying to block %s before all of its WorkFragments have been dispatched!\n%s\n%s", // ts, // StringUtil.join("** ", "\n", tempDebug), // this.getVoltProcedure(ts.getProcedureName()).getLastBatchPlan()); // Now that we know all of our WorkFragments have been dispatched, we can then // wait for all of the results to come back in. if (latch == null) latch = this.depTracker.getDependencyLatch(ts); assert(latch != null) : String.format("Unexpected null dependency latch for " + ts); if (latch.getCount() > 0) { if (debug.val) { LOG.debug(String.format("%s - All blocked messages dispatched. Waiting for %d dependencies", ts, latch.getCount())); if (trace.val) LOG.trace(ts.toString()); } boolean timeout = false; long startTime = EstTime.currentTimeMillis(); if (needs_profiling) ts.profiler.startExecDtxnWork(); if (hstore_conf.site.exec_profiling) this.profiler.sp1_time.start(); try { while (latch.getCount() > 0 && ts.hasPendingError() == false) { if (this.utilityWork() == false) { timeout = latch.await(WORK_QUEUE_POLL_TIME, TimeUnit.MILLISECONDS); if (timeout == false) break; } if ((EstTime.currentTimeMillis() - startTime) > hstore_conf.site.exec_response_timeout) { timeout = true; break; } } // WHILE } catch (InterruptedException ex) { if (this.hstore_site.isShuttingDown() == false) { LOG.error(String.format("%s - We were interrupted while waiting for results", ts), ex); } timeout = true; } catch (Throwable ex) { String msg = String.format("Fatal error for %s while waiting for results", ts); throw new ServerFaultException(msg, ex); } finally { if (needs_profiling) ts.profiler.stopExecDtxnWork(); if (hstore_conf.site.exec_profiling) this.profiler.sp1_time.stopIfStarted(); } if (timeout && this.isShuttingDown() == false) { LOG.warn(String.format("Still waiting for responses for %s after %d ms [latch=%d]\n%s", ts, hstore_conf.site.exec_response_timeout, latch.getCount(), ts.debug())); LOG.warn("Procedure Parameters:\n" + ts.getProcedureParameters()); hstore_conf.site.exec_profiling = true; LOG.warn(hstore_site.statusSnapshot()); String msg = "The query responses for " + ts + " never arrived!"; throw new ServerFaultException(msg, ts.getTransactionId()); } } // Update done partitions if (notify != null && notify.donePartitions.isEmpty() == false) { if (debug.val) LOG.debug(String.format("%s - Marking new done partitions %s", ts, notify.donePartitions)); ts.getDonePartitions().addAll(notify.donePartitions); } // IMPORTANT: Check whether the fragments failed somewhere and we got a response with an error // We will rethrow this so that it pops the stack all the way back to VoltProcedure.call() // where we can generate a message to the client if (ts.hasPendingError()) { if (debug.val) LOG.warn(String.format("%s was hit with a %s", ts, ts.getPendingError().getClass().getSimpleName())); throw ts.getPendingError(); } // IMPORTANT: Don't try to check whether we got back the right number of tables because the batch // may have hit an error and we didn't execute all of them. VoltTable results[] = null; try { results = this.depTracker.getResults(ts); } catch (AssertionError ex) { LOG.error("Failed to get final results for batch\n" + ts.debug()); throw ex; } ts.finishRound(this.partitionId); if (debug.val) { if (trace.val) LOG.trace(ts + " is now running and looking for love in all the wrong places..."); LOG.debug(String.format("%s - Returning back %d tables to VoltProcedure", ts, results.length)); } return (results); } // --------------------------------------------------------------- // COMMIT + ABORT METHODS // --------------------------------------------------------------- /** * Queue a speculatively executed transaction to send its ClientResponseImpl message */ private void blockClientResponse(LocalTransaction ts, ClientResponseImpl cresponse) { assert(ts.isPredictSinglePartition() == true) : String.format("Specutatively executed multi-partition %s [mode=%s, status=%s]", ts, this.currentExecMode, cresponse.getStatus()); assert(ts.isSpeculative() == true) : String.format("Blocking ClientResponse for non-specutative %s [mode=%s, status=%s]", ts, this.currentExecMode, cresponse.getStatus()); assert(cresponse.getStatus() != Status.ABORT_MISPREDICT) : String.format("Trying to block ClientResponse for mispredicted %s [mode=%s, status=%s]", ts, this.currentExecMode, cresponse.getStatus()); assert(this.currentExecMode != ExecutionMode.COMMIT_ALL) : String.format("Blocking ClientResponse for %s when in non-specutative mode [mode=%s, status=%s]", ts, this.currentExecMode, cresponse.getStatus()); this.specExecBlocked.push(Pair.of(ts, cresponse)); this.specExecModified = this.specExecModified && ts.isExecReadOnly(this.partitionId); if (debug.val) LOG.debug(String.format("%s - Blocking %s ClientResponse [partitions=%s, blockQueue=%d]", ts, cresponse.getStatus(), ts.getTouchedPartitions().values(), this.specExecBlocked.size())); } /** * For the given transaction's ClientResponse, figure out whether we can send it back to the client * right now or whether we need to initiate two-phase commit. * @param ts * @param cresponse */ protected void processClientResponse(LocalTransaction ts, ClientResponseImpl cresponse) { // IMPORTANT: If we executed this locally and only touched our partition, then we need to commit/abort right here // 2010-11-14: The reason why we can do this is because we will just ignore the commit // message when it shows from the Dtxn.Coordinator. We should probably double check with Evan on this... Status status = cresponse.getStatus(); if (debug.val) { LOG.debug(String.format("%s - Processing ClientResponse at partition %d " + "[status=%s, singlePartition=%s, local=%s, clientHandle=%d]", ts, this.partitionId, status, ts.isPredictSinglePartition(), ts.isExecLocal(this.partitionId), cresponse.getClientHandle())); if (trace.val) { LOG.trace(ts + " Touched Partitions: " + ts.getTouchedPartitions().values()); if (ts.isPredictSinglePartition() == false) LOG.trace(ts + " Done Partitions: " + ts.getDonePartitions()); } } // ------------------------------- // ALL: Transactions that need to be internally restarted // ------------------------------- if (status == Status.ABORT_MISPREDICT || status == Status.ABORT_SPECULATIVE || status == Status.ABORT_EVICTEDACCESS) { // If the txn was mispredicted, then we will pass the information over to the // HStoreSite so that it can re-execute the transaction. We want to do this // first so that the txn gets re-executed as soon as possible... if (debug.val) LOG.debug(String.format("%s - Restarting because transaction was hit with %s", ts, (ts.getPendingError() != null ? ts.getPendingError().getClass().getSimpleName() : ""))); // We don't want to delete the transaction here because whoever is going to requeue it for // us will need to know what partitions that the transaction touched when it executed before if (ts.isPredictSinglePartition()) { this.finishTransaction(ts, status); this.hstore_site.transactionRequeue(ts, status); } // Send a message all the partitions involved that the party is over // and that they need to abort the transaction. We don't actually care when we get the // results back because we'll start working on new txns right away. // Note that when we call transactionFinish() right here this thread will then go on // to invoke HStoreSite.transactionFinish() for us. That means when it returns we will // have successfully aborted the txn at least at all of the local partitions at this site. else { if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.startPostFinish(); LocalFinishCallback finish_callback = ts.getFinishCallback(); finish_callback.init(ts, status); finish_callback.markForRequeue(); if (hstore_conf.site.exec_profiling) this.profiler.network_time.start(); this.hstore_coordinator.transactionFinish(ts, status, finish_callback); if (hstore_conf.site.exec_profiling) this.profiler.network_time.stopIfStarted(); } } // ------------------------------- // ALL: Single-Partition Transactions // ------------------------------- else if (ts.isPredictSinglePartition()) { // Commit or abort the transaction only if we haven't done it already // This can happen when we commit speculative txns out of order if (ts.isMarkedFinished(this.partitionId) == false) { this.finishTransaction(ts, status); } // We have to mark it as loggable to prevent the response // from getting sent back to the client if (hstore_conf.site.commandlog_enable) ts.markLogEnabled(); if (hstore_conf.site.exec_profiling) this.profiler.network_time.start(); this.hstore_site.responseSend(ts, cresponse); if (hstore_conf.site.exec_profiling) this.profiler.network_time.stopIfStarted(); this.hstore_site.queueDeleteTransaction(ts.getTransactionId(), status); } // ------------------------------- // COMMIT: Distributed Transaction // ------------------------------- else if (status == Status.OK) { // We need to set the new ExecutionMode before we invoke transactionPrepare // because the LocalTransaction handle might get cleaned up immediately ExecutionMode newMode = null; if (hstore_conf.site.specexec_enable) { newMode = (ts.isExecReadOnly(this.partitionId) ? ExecutionMode.COMMIT_READONLY : ExecutionMode.COMMIT_NONE); } else { newMode = ExecutionMode.DISABLED; } this.setExecutionMode(ts, newMode); // We have to send a prepare message to all of our remote HStoreSites // We want to make sure that we don't go back to ones that we've already told PartitionSet donePartitions = ts.getDonePartitions(); PartitionSet notifyPartitions = new PartitionSet(); for (int partition : ts.getPredictTouchedPartitions().values()) { if (donePartitions.contains(partition) == false) { notifyPartitions.add(partition); } } // FOR if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.startPostPrepare(); ts.setClientResponse(cresponse); if (hstore_conf.site.exec_profiling) { this.profiler.network_time.start(); this.profiler.sp3_local_time.start(); } LocalPrepareCallback callback = ts.getPrepareCallback(); callback.init(ts, notifyPartitions); this.hstore_coordinator.transactionPrepare(ts, callback, notifyPartitions); if (hstore_conf.site.exec_profiling) this.profiler.network_time.stopIfStarted(); } // ------------------------------- // ABORT: Distributed Transaction // ------------------------------- else { // Send back the result to the client right now, since there's no way // that we're magically going to be able to recover this and get them a result // This has to come before the network messages above because this will clean-up the // LocalTransaction state information this.hstore_site.responseSend(ts, cresponse); // Send a message all the partitions involved that the party is over // and that they need to abort the transaction. We don't actually care when we get the // results back because we'll start working on new txns right away. // Note that when we call transactionFinish() right here this thread will then go on // to invoke HStoreSite.transactionFinish() for us. That means when it returns we will // have successfully aborted the txn at least at all of the local partitions at this site. if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.startPostFinish(); LocalFinishCallback callback = ts.getFinishCallback(); callback.init(ts, status); if (hstore_conf.site.exec_profiling) this.profiler.network_time.start(); try { this.hstore_coordinator.transactionFinish(ts, status, callback); } finally { if (hstore_conf.site.exec_profiling) this.profiler.network_time.stopIfStarted(); } } } /** * Enable speculative execution mode for this partition. The given transaction is * the one that we will need to wait to finish before we can release the ClientResponses * for any speculatively executed transactions. * @param txn_id * @return true if speculative execution was enabled at this partition */ private Status prepareTransaction(AbstractTransaction ts) { assert(ts != null) : "Unexpected null transaction handle at partition " + this.partitionId; assert(ts.isInitialized()) : String.format("Trying to prepare uninitialized transaction %s at partition %d", ts, this.partitionId); assert(ts.isMarkedFinished(this.partitionId) == false) : String.format("Trying to prepare %s again after it was already finished at partition %d", ts, this.partitionId); Status status = Status.OK; // Skip if we've already invoked prepared for this txn at this partition if (ts.isMarkedPrepared(this.partitionId) == false) { if (debug.val) LOG.debug(String.format("%s - Preparing to commit txn at partition %d [specBlocked=%d]", ts, this.partitionId, this.specExecBlocked.size())); ExecutionMode newMode = ExecutionMode.COMMIT_NONE; if (hstore_conf.site.exec_profiling && this.partitionId != ts.getBasePartition() && ts.needsFinish(this.partitionId)) { profiler.sp3_remote_time.start(); } if (hstore_conf.site.specexec_enable) { // Check to see if there were any conflicts with the dtxn and any of its speculative // txns at this partition. If there were, then we know that we can't commit the txn here. LocalTransaction spec_ts; for (Pair<LocalTransaction, ClientResponseImpl> pair : this.specExecBlocked) { spec_ts = pair.getFirst(); if (debug.val) LOG.debug(String.format("%s - Checking for conflicts with speculative %s at partition %d [%s]", ts, spec_ts, this.partitionId, this.specExecChecker.getClass().getSimpleName())); if (this.specExecChecker.hasConflictAfter(ts, spec_ts, this.partitionId)) { if (debug.val) LOG.debug(String.format("%s - Conflict found with speculative txn %s at partition %d", ts, spec_ts, this.partitionId)); status = Status.ABORT_RESTART; break; } } // FOR // Check whether the txn that we're waiting for is read-only. // If it is, then that means all read-only transactions can commit right away if (status == Status.OK && ts.isExecReadOnly(this.partitionId)) { if (debug.val) LOG.debug(String.format("%s - Txn is read-only at partition %d [readOnly=%s]", ts, this.partitionId, ts.isExecReadOnly(this.partitionId))); newMode = ExecutionMode.COMMIT_READONLY; } } if (this.currentDtxn != null) this.setExecutionMode(ts, newMode); } // It's ok if they try to prepare the txn twice. That might just mean that they never // got the acknowledgement back in time if they tried to send an early commit message. else if (debug.val) { LOG.debug(String.format("%s - Already marked 2PC:PREPARE at partition %d", ts, this.partitionId)); } // IMPORTANT // When we do an early 2PC-PREPARE, we won't have this callback ready // because we don't know what callback to use to send the acknowledgements // back over the network PartitionCountingCallback<AbstractTransaction> callback = ts.getPrepareCallback(); if (status == Status.OK) { if (callback.isInitialized()) { try { callback.run(this.partitionId); } catch (Throwable ex) { LOG.warn("Unexpected error for " + ts, ex); } } // But we will always mark ourselves as prepared at this partition ts.markPrepared(this.partitionId); } else { if (debug.val) LOG.debug(String.format("%s - Aborting txn from partition %d [%s]", ts, this.partitionId, status)); callback.abort(this.partitionId, status); } return (status); } /** * Internal call to abort/commit the transaction down in the execution engine * @param ts * @param commit */ private void finishTransaction(AbstractTransaction ts, Status status) { assert(ts != null) : "Unexpected null transaction handle at partition " + this.partitionId; assert(ts.isInitialized()) : String.format("Trying to commit uninitialized transaction %s at partition %d", ts, this.partitionId); assert(ts.isMarkedFinished(this.partitionId) == false) : String.format("Trying to commit %s twice at partition %d", ts, this.partitionId); // This can be null if they haven't submitted anything boolean commit = (status == Status.OK); long undoToken = (commit ? ts.getLastUndoToken(this.partitionId) : ts.getFirstUndoToken(this.partitionId)); // Only commit/abort this transaction if: // (2) We have the last undo token used by this transaction // (3) The transaction was executed with undo buffers // (4) The transaction actually submitted work to the EE // (5) The transaction modified data at this partition if (ts.needsFinish(this.partitionId) && undoToken != HStoreConstants.NULL_UNDO_LOGGING_TOKEN) { if (trace.val) LOG.trace(String.format("%s - Invoking EE to finish work for txn [%s / speculative=%s]", ts, status, ts.isSpeculative())); this.finishWorkEE(ts, undoToken, commit); } // We always need to do the following things regardless if we hit up the EE or not if (commit) this.lastCommittedTxnId = ts.getTransactionId(); if (trace.val) LOG.trace(String.format("%s - Telling queue manager that txn is finished at partition %d", ts, this.partitionId)); this.queueManager.lockQueueFinished(ts, status, this.partitionId); if (debug.val) LOG.debug(String.format("%s - Successfully %sed transaction at partition %d", ts, (commit ? "committ" : "abort"), this.partitionId)); ts.markFinished(this.partitionId); } /** * The real method that actually reaches down into the EE and commits/undos the changes * for the given token. * Unless you know what you're doing, you probably want to be calling finishTransaction() * instead of calling this directly. * @param ts * @param undoToken * @param commit */ private void finishWorkEE(AbstractTransaction ts, long undoToken, boolean commit) { assert(ts.isMarkedFinished(this.partitionId) == false) : String.format("Trying to commit %s twice at partition %d", ts, this.partitionId); // If the txn is completely read-only and they didn't use undo-logging, then // there is nothing that we need to do, except to check to make sure we aren't // trying to abort this txn if (undoToken == HStoreConstants.DISABLE_UNDO_LOGGING_TOKEN) { // SANITY CHECK: Make sure that they're not trying to undo a transaction that // modified the database but did not use undo logging if (ts.isExecReadOnly(this.partitionId) == false && commit == false) { String msg = String.format("TRYING TO ABORT TRANSACTION ON PARTITION %d WITHOUT UNDO LOGGING [undoToken=%d]", this.partitionId, undoToken); LOG.fatal(msg + "\n" + ts.debug()); this.crash(new ServerFaultException(msg, ts.getTransactionId())); } if (debug.val) LOG.debug(String.format("%s - undoToken == DISABLE_UNDO_LOGGING_TOKEN", ts)); } // COMMIT / ABORT else { boolean needs_profiling = false; if (hstore_conf.site.txn_profiling && ts.isExecLocal(this.partitionId) && ((LocalTransaction)ts).profiler != null) { needs_profiling = true; ((LocalTransaction)ts).profiler.startPostEE(); } assert(this.lastCommittedUndoToken != undoToken) : String.format("Trying to %s undoToken %d for %s twice at partition %d", (commit ? "COMMIT" : "ABORT"), undoToken, ts, this.partitionId); // COMMIT! if (commit) { if (debug.val) { LOG.debug(String.format("%s - COMMITING txn on partition %d with undoToken %d " + "[lastTxnId=%d, lastUndoToken=%d, dtxn=%s]%s", ts, this.partitionId, undoToken, this.lastCommittedTxnId, this.lastCommittedUndoToken, this.currentDtxn, (ts instanceof LocalTransaction ? " - " + ((LocalTransaction)ts).getSpeculationType() : ""))); if (this.specExecBlocked.isEmpty() == false && ts.isPredictSinglePartition() == false) { LOG.debug(String.format("%s - # of Speculatively Executed Txns: %d ", ts, this.specExecBlocked.size())); } } assert(this.lastCommittedUndoToken < undoToken) : String.format("Trying to commit undoToken %d for %s but it is less than the " + "last committed undoToken %d at partition %d\n" + "Last Committed Txn: %d", undoToken, ts, this.lastCommittedUndoToken, this.partitionId, this.lastCommittedTxnId); this.ee.releaseUndoToken(undoToken); this.lastCommittedUndoToken = undoToken; } // ABORT! else { // Evan says that txns will be aborted LIFO. This means the first txn that // we get in abortWork() will have a the greatest undoToken, which means that // it will automagically rollback all other outstanding txns. // I'm lazy/tired, so for now I'll just rollback everything I get, but in theory // we should be able to check whether our undoToken has already been rolled back if (debug.val) { LOG.debug(String.format("%s - ABORTING txn on partition %d with undoToken %d " + "[lastTxnId=%d, lastUndoToken=%d, dtxn=%s]%s", ts, this.partitionId, undoToken, this.lastCommittedTxnId, this.lastCommittedUndoToken, this.currentDtxn, (ts instanceof LocalTransaction ? " - " + ((LocalTransaction)ts).getSpeculationType() : ""))); if (this.specExecBlocked.isEmpty() == false && ts.isPredictSinglePartition() == false) { LOG.debug(String.format("%s - # of Speculatively Executed Txns: %d ", ts, this.specExecBlocked.size())); } } assert(this.lastCommittedUndoToken < undoToken) : String.format("Trying to abort undoToken %d for %s but it is less than the " + "last committed undoToken %d at partition %d " + "[lastTxnId=%d, lastUndoToken=%d, dtxn=%s]%s", undoToken, ts, this.lastCommittedUndoToken, this.partitionId, this.lastCommittedTxnId, this.lastCommittedUndoToken, this.currentDtxn, (ts instanceof LocalTransaction ? " - " + ((LocalTransaction)ts).getSpeculationType() : "")); this.ee.undoUndoToken(undoToken); } if (needs_profiling) ((LocalTransaction)ts).profiler.stopPostEE(); } } /** * Somebody told us that our partition needs to abort/commit the given transaction id. * This method should only be used for distributed transactions, because * it will do some extra work for speculative execution * @param ts - The transaction to finish up. * @param status - The final status of the transaction */ private void finishDistributedTransaction(final AbstractTransaction ts, final Status status) { if (debug.val) LOG.debug(String.format("%s - Processing finish request at partition %d " + "[status=%s, readOnly=%s]", ts, this.partitionId, status, ts.isExecReadOnly(this.partitionId))); if (this.currentDtxn == ts) { // 2012-11-22 -- Yes, today is Thanksgiving and I'm working on my database. // That's just grad student life I guess. Anyway, if you're reading this then // you know that this is an important part of the system. We have a dtxn that // we have been told is completely finished and now we need to either commit // or abort any changes that it may have made at this partition. The tricky thing // is that if we have speculative execution enabled, then we need to make sure // that we process any transactions that were executed while the dtxn was running // in the right order to ensure that we maintain serializability. // Here is the basic logic of what's about to happen: // // (1) If the dtxn is commiting, then we just need to commit the the last txn that // was executed (since this will have the largest undo token). // The EE will automatically commit all undo tokens less than that. // (2) If the dtxn is aborting, then we can commit any speculative txn that was // executed before the dtxn's first non-readonly undo token. // // Note that none of the speculative txns in the blocked queue will need to be // aborted at this point, because we will have rolled back their changes immediately // when they aborted, so that our dtxn doesn't read dirty data. if (this.specExecBlocked.isEmpty() == false) { // First thing we need to do is get the latch that will be set by any transaction // that was in the middle of being executed when we were called if (debug.val) LOG.debug(String.format("%s - Checking %d blocked speculative transactions at " + "partition %d [currentMode=%s]", ts, this.specExecBlocked.size(), this.partitionId, this.currentExecMode)); LocalTransaction spec_ts = null; ClientResponseImpl spec_cr = null; // ------------------------------- // DTXN NON-READ-ONLY ABORT // If the dtxn did not modify this partition, then everthing can commit // Otherwise, we want to commit anything that was executed before the dtxn started // ------------------------------- if (status != Status.OK && ts.isExecReadOnly(this.partitionId) == false) { // We need to get the first undo tokens for our distributed transaction long dtxnUndoToken = ts.getFirstUndoToken(this.partitionId); if (debug.val) LOG.debug(String.format("%s - Looking for speculative txns to commit before we rollback undoToken %d", ts, dtxnUndoToken)); // Queue of speculative txns that need to be committed. final Queue<Pair<LocalTransaction, ClientResponseImpl>> txnsToCommit = new LinkedList<Pair<LocalTransaction,ClientResponseImpl>>(); // Queue of speculative txns that need to be aborted + restarted final Queue<Pair<LocalTransaction, ClientResponseImpl>> txnsToRestart = new LinkedList<Pair<LocalTransaction,ClientResponseImpl>>(); long spec_token; long max_token = HStoreConstants.NULL_UNDO_LOGGING_TOKEN; LocalTransaction max_ts = null; for (Pair<LocalTransaction, ClientResponseImpl> pair : this.specExecBlocked) { boolean shouldCommit = false; spec_ts = pair.getFirst(); spec_token = spec_ts.getFirstUndoToken(this.partitionId); if (debug.val) LOG.debug(String.format("Speculative Txn %s [undoToken=%d, %s]", spec_ts, spec_token, spec_ts.getSpeculationType())); // Speculative txns should never be executed without an undo token assert(spec_token != HStoreConstants.DISABLE_UNDO_LOGGING_TOKEN); assert(spec_ts.isSpeculative()) : spec_ts + " isn't marked as speculative!"; // If the speculative undoToken is null, then this txn didn't execute // any queries. That means we can always commit it if (spec_token == HStoreConstants.NULL_UNDO_LOGGING_TOKEN) { if (debug.val) LOG.debug(String.format("Speculative Txn %s has a null undoToken at partition %d", spec_ts, this.partitionId)); shouldCommit = true; } // Otherwise, look to see if this txn was speculatively executed before the // first undo token of the distributed txn. That means we know that this guy // didn't read any modifications made by the dtxn. else if (spec_token < dtxnUndoToken) { if (debug.val) LOG.debug(String.format("Speculative Txn %s has an undoToken less than the dtxn %s " + "at partition %d [%d < %d]", spec_ts, ts, this.partitionId, spec_token, dtxnUndoToken)); shouldCommit = true; } // Ok so at this point we know that our spec txn came *after* the distributed txn // started. So we need to use our checker to see whether there is a conflict else if (this.specExecChecker.hasConflictAfter(ts, spec_ts, this.partitionId) == false) { if (debug.val) LOG.debug(String.format("Speculative Txn %s does not conflict with dtxn %s at partition %d", spec_ts, ts, this.partitionId)); shouldCommit = true; } if (shouldCommit) { txnsToCommit.add(pair); if (spec_token != HStoreConstants.NULL_UNDO_LOGGING_TOKEN && spec_token > max_token) { max_token = spec_token; max_ts = spec_ts; } } else { txnsToRestart.add(pair); } } // FOR if (debug.val) LOG.debug(String.format("%s - Found %d speculative txns at partition %d that need to be " + "committed *before* we abort this txn", ts, txnsToCommit.size(), this.partitionId)); // (1) Commit the greatest token that we've seen. This means that // all our other txns can be safely processed without needing // to go down in the EE if (max_token != HStoreConstants.NULL_UNDO_LOGGING_TOKEN) { assert(max_ts != null); this.finishWorkEE(max_ts, max_token, true); } // (2) Process all the txns that need to be committed Pair<LocalTransaction, ClientResponseImpl> pair = null; while ((pair = txnsToCommit.poll()) != null) { spec_ts = pair.getFirst(); spec_cr = pair.getSecond(); spec_ts.markFinished(this.partitionId); try { if (debug.val) LOG.debug(String.format("%s - Releasing blocked ClientResponse for %s [status=%s]", ts, spec_ts, spec_cr.getStatus())); this.processClientResponse(spec_ts, spec_cr); } catch (Throwable ex) { String msg = "Failed to complete queued response for " + spec_ts; throw new ServerFaultException(msg, ex, ts.getTransactionId()); } } // FOR // (3) Abort the distributed txn this.finishTransaction(ts, status); // (4) Restart all the other txns while ((pair = txnsToRestart.poll()) != null) { spec_ts = pair.getFirst(); spec_cr = pair.getSecond(); MispredictionException error = new MispredictionException(spec_ts.getTransactionId(), spec_ts.getTouchedPartitions()); spec_ts.setPendingError(error, false); spec_cr.setStatus(Status.ABORT_SPECULATIVE); this.processClientResponse(spec_ts, spec_cr); } // FOR } // ------------------------------- // DTXN READ-ONLY ABORT or DTXN COMMIT // ------------------------------- else { // **IMPORTANT** // If the dtxn needs to commit, then all we need to do is get the // last undoToken that we've generated (since we know that it had to // have been used either by our distributed txn or for one of our // speculative txns). // // If the read-only dtxn needs to abort, then there's nothing we need to // do, because it didn't make any changes. That means we can just // commit the last speculatively executed transaction // // Once we have this token, we can just make a direct call to the EE // to commit any changes that came before it. Note that we are using our // special 'finishWorkEE' method that does not require us to provide // the transaction that we're committing. long undoToken = this.lastUndoToken; if (debug.val) LOG.debug(String.format("%s - Last undoToken at partition %d => %d", ts, this.partitionId, undoToken)); // Bombs away! if (undoToken != this.lastCommittedUndoToken) { this.finishWorkEE(ts, undoToken, true); // IMPORTANT: Make sure that we remove the dtxn from the lock queue! // This is normally done in finishTransaction() but because we're trying // to be clever and invoke the EE directly, we have to make sure that // we call it ourselves. this.queueManager.lockQueueFinished(ts, status, this.partitionId); } // Make sure that we mark the dtxn as finished so that we don't // try to do anything with it later on. ts.markFinished(this.partitionId); // Now make sure that all of the speculative txns are processed without // committing (since we just committed any change that they could have made // up above). Pair<LocalTransaction, ClientResponseImpl> pair = null; while ((pair = this.specExecBlocked.pollFirst()) != null) { spec_ts = pair.getFirst(); spec_cr = pair.getSecond(); spec_ts.markFinished(this.partitionId); try { if (trace.val) LOG.trace(String.format("%s - Releasing blocked ClientResponse for %s [status=%s]", ts, spec_ts, spec_cr.getStatus())); this.processClientResponse(spec_ts, spec_cr); } catch (Throwable ex) { String msg = "Failed to complete queued response for " + spec_ts; throw new ServerFaultException(msg, ex, ts.getTransactionId()); } } // WHILE } this.specExecBlocked.clear(); this.specExecModified = false; if (trace.val) LOG.trace(String.format("Finished processing all queued speculative txns for dtxn %s", ts)); } // ------------------------------- // NO SPECULATIVE TXNS // ------------------------------- else { // There are no speculative txns waiting for this dtxn, // so we can just commit it right away if (debug.val) LOG.debug(String.format("%s - No speculative txns at partition %d. Just %s txn by itself", ts, this.partitionId, (status == Status.OK ? "commiting" : "aborting"))); this.finishTransaction(ts, status); } // Clear our cached query results that are specific for this transaction // this.queryCache.purgeTransaction(ts.getTransactionId()); // TODO: Remove anything in our queue for this txn // if (ts.hasQueuedWork(this.partitionId)) { // } // Check whether this is the response that the speculatively executed txns have been waiting for // We could have turned off speculative execution mode beforehand if (debug.val) LOG.debug(String.format("%s - Attempting to unmark as the current DTXN at partition %d and " + "setting execution mode to %s", ts, this.partitionId, ExecutionMode.COMMIT_ALL)); try { // Resetting the current_dtxn variable has to come *before* we change the execution mode this.resetCurrentDtxn(); this.setExecutionMode(ts, ExecutionMode.COMMIT_ALL); // Release blocked transactions this.releaseBlockedTransactions(ts); } catch (Throwable ex) { String msg = String.format("Failed to finish %s at partition %d", ts, this.partitionId); throw new ServerFaultException(msg, ex, ts.getTransactionId()); } if (hstore_conf.site.exec_profiling) { this.profiler.sp3_local_time.stopIfStarted(); this.profiler.sp3_remote_time.stopIfStarted(); } } // We were told told to finish a dtxn that is not the current one // at this partition. That's ok as long as it's aborting and not trying // to commit. else { assert(status != Status.OK) : String.format("Trying to commit %s at partition %d but the current dtxn is %s", ts, this.partitionId, this.currentDtxn); this.queueManager.lockQueueFinished(ts, status, this.partitionId); } // ------------------------------- // FINISH CALLBACKS // ------------------------------- // MapReduceTransaction if (ts instanceof MapReduceTransaction) { PartitionCountingCallback<AbstractTransaction> callback = ((MapReduceTransaction)ts).getCleanupCallback(); // We don't want to invoke this callback at the basePartition's site // because we don't want the parent txn to actually get deleted. if (this.partitionId == ts.getBasePartition()) { if (debug.val) LOG.debug(String.format("%s - Notifying %s that the txn is finished at partition %d", ts, callback.getClass().getSimpleName(), this.partitionId)); callback.run(this.partitionId); } } else { PartitionCountingCallback<AbstractTransaction> callback = ts.getFinishCallback(); if (debug.val) LOG.debug(String.format("%s - Notifying %s that the txn is finished at partition %d", ts, callback.getClass().getSimpleName(), this.partitionId)); callback.run(this.partitionId); } } private void blockTransaction(InternalTxnMessage work) { if (debug.val) LOG.debug(String.format("%s - Adding %s work to blocked queue", work.getTransaction(), work.getClass().getSimpleName())); this.currentBlockedTxns.add(work); } private void blockTransaction(LocalTransaction ts) { this.blockTransaction(new StartTxnMessage(ts)); } /** * Release all the transactions that are currently in this partition's blocked queue * into the work queue. * @param ts */ private void releaseBlockedTransactions(AbstractTransaction ts) { if (this.currentBlockedTxns.isEmpty() == false) { if (debug.val) LOG.debug(String.format("Attempting to release %d blocked transactions at partition %d because of %s", this.currentBlockedTxns.size(), this.partitionId, ts)); this.work_queue.addAll(this.currentBlockedTxns); int released = this.currentBlockedTxns.size(); this.currentBlockedTxns.clear(); if (debug.val) LOG.debug(String.format("Released %d blocked transactions at partition %d because of %s", released, this.partitionId, ts)); } assert(this.currentBlockedTxns.isEmpty()); } // --------------------------------------------------------------- // SNAPSHOT METHODS // --------------------------------------------------------------- /** * Do snapshot work exclusively until there is no more. Also blocks * until the syncing and closing of snapshot data targets has completed. */ public void initiateSnapshots(Deque<SnapshotTableTask> tasks) { m_snapshotter.initiateSnapshots(ee, tasks); } public Collection<Exception> completeSnapshotWork() throws InterruptedException { return m_snapshotter.completeSnapshotWork(ee); } // --------------------------------------------------------------- // SHUTDOWN METHODS // --------------------------------------------------------------- /** * Cause this PartitionExecutor to make the entire HStore cluster shutdown * This won't return! */ public synchronized void crash(Throwable ex) { String msg = String.format("PartitionExecutor for Partition #%d is crashing", this.partitionId); if (ex == null) LOG.warn(msg); else LOG.warn(msg, ex); assert(this.hstore_coordinator != null); this.hstore_coordinator.shutdownClusterBlocking(ex); } @Override public boolean isShuttingDown() { return (this.hstore_site.isShuttingDown()); // shutdown_state == State.PREPARE_SHUTDOWN || this.shutdown_state == State.SHUTDOWN); } @Override public void prepareShutdown(boolean error) { this.shutdown_state = ShutdownState.PREPARE_SHUTDOWN; } /** * Somebody from the outside wants us to shutdown */ public synchronized void shutdown() { if (this.shutdown_state == ShutdownState.SHUTDOWN) { if (debug.val) LOG.debug(String.format("Partition #%d told to shutdown again. Ignoring...", this.partitionId)); return; } this.shutdown_state = ShutdownState.SHUTDOWN; if (debug.val) LOG.debug(String.format("Shutting down PartitionExecutor for Partition #%d", this.partitionId)); // Clear the queue this.work_queue.clear(); // Knock out this ma if (this.m_snapshotter != null) this.m_snapshotter.shutdown(); // Make sure we shutdown our threadpool // this.thread_pool.shutdownNow(); if (this.self != null) this.self.interrupt(); if (this.shutdown_latch != null) { try { this.shutdown_latch.acquire(); } catch (InterruptedException ex) { // Ignore } catch (Exception ex) { LOG.fatal("Unexpected error while shutting down", ex); } } } // ---------------------------------------------------------------------------- // DEBUG METHODS // ---------------------------------------------------------------------------- @Override public String toString() { return String.format("%s{%s}", this.getClass().getSimpleName(), HStoreThreadManager.formatPartitionName(siteId, partitionId)); } public class Debug implements DebugContext { public VoltProcedure getVoltProcedure(String procName) { Procedure proc = catalogContext.procedures.getIgnoreCase(procName); return (PartitionExecutor.this.getVoltProcedure(proc.getId())); } public SpecExecScheduler getSpecExecScheduler() { return (PartitionExecutor.this.specExecScheduler); } public AbstractConflictChecker getSpecExecConflictChecker() { return (PartitionExecutor.this.specExecChecker); } public Collection<BatchPlanner> getBatchPlanners() { return (PartitionExecutor.this.batchPlanners.values()); } public PartitionExecutorProfiler getProfiler() { return (PartitionExecutor.this.profiler); } public Thread getExecutionThread() { return (PartitionExecutor.this.self); } public Queue<InternalMessage> getWorkQueue() { return (PartitionExecutor.this.work_queue); } public void setExecutionMode(AbstractTransaction ts, ExecutionMode newMode) { PartitionExecutor.this.setExecutionMode(ts, newMode); } public ExecutionMode getExecutionMode() { return (PartitionExecutor.this.currentExecMode); } public Long getLastExecutedTxnId() { return (PartitionExecutor.this.lastExecutedTxnId); } public Long getLastCommittedTxnId() { return (PartitionExecutor.this.lastCommittedTxnId); } public long getLastCommittedIndoToken() { return (PartitionExecutor.this.lastCommittedUndoToken); } /** * Get the VoltProcedure handle of the current running txn. This could be null. * <B>FOR TESTING ONLY</B> */ public VoltProcedure getCurrentVoltProcedure() { return (PartitionExecutor.this.currentVoltProc); } /** * Get the txnId of the current distributed transaction at this partition * <B>FOR TESTING ONLY</B> */ public AbstractTransaction getCurrentDtxn() { return (PartitionExecutor.this.currentDtxn); } /** * Get the txnId of the current distributed transaction at this partition * <B>FOR TESTING ONLY</B> */ public Long getCurrentDtxnId() { Long ret = null; // This is a race condition, so we'll just ignore any errors if (PartitionExecutor.this.currentDtxn != null) { try { ret = PartitionExecutor.this.currentDtxn.getTransactionId(); } catch (NullPointerException ex) { // IGNORE } } return (ret); } public Long getCurrentTxnId() { return (PartitionExecutor.this.currentTxnId); } public int getBlockedWorkCount() { return (PartitionExecutor.this.currentBlockedTxns.size()); } /** * Return the number of spec exec txns have completed but are waiting * for the distributed txn to finish at this partition */ public int getBlockedSpecExecCount() { return (PartitionExecutor.this.specExecBlocked.size()); } public int getWorkQueueSize() { return (PartitionExecutor.this.work_queue.size()); } public void updateMemory() { PartitionExecutor.this.updateMemoryStats(EstTime.currentTimeMillis()); } /** * Replace the ConflictChecker. This should only be used for testing * @param checker */ protected void setConflictChecker(AbstractConflictChecker checker) { LOG.warn(String.format("Replacing original checker %s with %s at partition %d", specExecChecker.getClass().getSimpleName(), checker.getClass().getSimpleName(), partitionId)); specExecChecker = checker; specExecScheduler.getDebugContext().setConflictChecker(checker); } } private Debug cachedDebugContext; public Debug getDebugContext() { if (this.cachedDebugContext == null) { // We don't care if we're thread-safe here... this.cachedDebugContext = new Debug(); } return this.cachedDebugContext; } }
true
true
private void getFragmentInputs(AbstractTransaction ts, int input_dep_id, Map<Integer, List<VoltTable>> inputs) { if (input_dep_id == HStoreConstants.NULL_DEPENDENCY_ID) return; if (trace.val) LOG.trace(String.format("%s - Attempting to retrieve input dependencies for DependencyId #%d", ts, input_dep_id)); // If the Transaction is on the same HStoreSite, then all the // input dependencies will be internal and can be retrieved locally if (ts instanceof LocalTransaction) { DependencyTracker txnTracker = null; if (ts.getBasePartition() != this.partitionId) { txnTracker = hstore_site.getDependencyTracker(ts.getBasePartition()); } else { txnTracker = this.depTracker; } List<VoltTable> deps = txnTracker.getInternalDependency((LocalTransaction)ts, input_dep_id); assert(deps != null); assert(inputs.containsKey(input_dep_id) == false); inputs.put(input_dep_id, deps); if (trace.val) LOG.trace(String.format("%s - Retrieved %d INTERNAL VoltTables for DependencyId #%d", ts, deps.size(), input_dep_id, (trace.val ? "\n" + deps : ""))); } // Otherwise they will be "attached" inputs to the RemoteTransaction handle // We should really try to merge these two concepts into a single function call else if (ts.getAttachedInputDependencies().containsKey(input_dep_id)) { List<VoltTable> deps = ts.getAttachedInputDependencies().get(input_dep_id); List<VoltTable> pDeps = null; // We have to copy the tables if we have debugging enabled if (trace.val) { // this.firstPartition == false) { pDeps = new ArrayList<VoltTable>(); for (VoltTable vt : deps) { ByteBuffer buffer = vt.getTableDataReference(); byte arr[] = new byte[vt.getUnderlyingBufferSize()]; buffer.get(arr, 0, arr.length); pDeps.add(new VoltTable(ByteBuffer.wrap(arr), true)); } } else { pDeps = deps; } inputs.put(input_dep_id, pDeps); if (trace.val) LOG.trace(String.format("%s - Retrieved %d ATTACHED VoltTables for DependencyId #%d in %s", ts, deps.size(), input_dep_id)); } } /** * Set the given AbstractTransaction handle as the current distributed txn * that is running at this partition. Note that this will check to make sure * that no other txn is marked as the currentDtxn. * @param ts */ private void setCurrentDtxn(AbstractTransaction ts) { // There can never be another current dtxn still unfinished at this partition! assert(this.currentBlockedTxns.isEmpty()) : String.format("Concurrent multi-partition transactions at partition %d: " + "Orig[%s] <=> New[%s] / BlockedQueue:%d", this.partitionId, this.currentDtxn, ts, this.currentBlockedTxns.size()); assert(this.currentDtxn == null) : String.format("Concurrent multi-partition transactions at partition %d: " + "Orig[%s] <=> New[%s] / BlockedQueue:%d", this.partitionId, this.currentDtxn, ts, this.currentBlockedTxns.size()); // Check whether we should check for speculative txns to execute whenever this // dtxn is idle at this partition this.currentDtxn = ts; if (hstore_conf.site.specexec_enable && ts.isSysProc() == false && this.specExecScheduler.isDisabled() == false) { this.specExecIgnoreCurrent = this.specExecChecker.shouldIgnoreTransaction(ts); } else { this.specExecIgnoreCurrent = true; } if (debug.val) { LOG.debug(String.format("Set %s as the current DTXN for partition %d [specExecIgnore=%s, previous=%s]", ts, this.partitionId, this.specExecIgnoreCurrent, this.lastDtxnDebug)); this.lastDtxnDebug = this.currentDtxn.toString(); } if (hstore_conf.site.exec_profiling && ts.getBasePartition() != this.partitionId) { profiler.sp2_time.start(); } } /** * Reset the current dtxn for this partition */ private void resetCurrentDtxn() { assert(this.currentDtxn != null) : "Trying to reset the currentDtxn when it is already null"; if (debug.val) LOG.debug(String.format("Resetting current DTXN for partition %d to null [previous=%s]", this.partitionId, this.lastDtxnDebug)); this.currentDtxn = null; } /** * Store a new prefetch result for a transaction * @param txnId * @param fragmentId * @param partitionId * @param params * @param result */ public void addPrefetchResult(LocalTransaction ts, int stmtCounter, int fragmentId, int partitionId, int paramsHash, VoltTable result) { if (debug.val) LOG.debug(String.format("%s - Adding prefetch result for %s with %d rows from partition %d " + "[stmtCounter=%d / paramsHash=%d]", ts, CatalogUtil.getPlanFragment(catalogContext.catalog, fragmentId).fullName(), result.getRowCount(), partitionId, stmtCounter, paramsHash)); this.depTracker.addPrefetchResult(ts, stmtCounter, fragmentId, partitionId, paramsHash, result); } // --------------------------------------------------------------- // PartitionExecutor API // --------------------------------------------------------------- /** * Queue a new transaction initialization at this partition. This will cause the * transaction to get added to this partition's lock queue. This PartitionExecutor does * not have to be this txn's base partition/ * @param ts */ public void queueSetPartitionLock(AbstractTransaction ts) { assert(ts.isInitialized()) : "Unexpected uninitialized transaction: " + ts; SetDistributedTxnMessage work = ts.getSetDistributedTxnMessage(); boolean success = this.work_queue.offer(work); assert(success) : String.format("Failed to queue %s at partition %d for %s", work, this.partitionId, ts); if (debug.val) LOG.debug(String.format("%s - Added %s to front of partition %d " + "work queue [size=%d]", ts, work.getClass().getSimpleName(), this.partitionId, this.work_queue.size())); if (hstore_conf.site.specexec_enable) this.specExecScheduler.interruptSearch(work); } /** * New work from the coordinator that this local site needs to execute (non-blocking) * This method will simply chuck the task into the work queue. * We should not be sent an InitiateTaskMessage here! * @param ts * @param task */ public void queueWork(AbstractTransaction ts, WorkFragment fragment) { assert(ts.isInitialized()) : "Unexpected uninitialized transaction: " + ts; WorkFragmentMessage work = ts.getWorkFragmentMessage(fragment); boolean success = this.work_queue.offer(work); // , true); assert(success) : String.format("Failed to queue %s at partition %d for %s", work, this.partitionId, ts); ts.markQueuedWork(this.partitionId); if (debug.val) LOG.debug(String.format("%s - Added %s to partition %d " + "work queue [size=%d]", ts, work.getClass().getSimpleName(), this.partitionId, this.work_queue.size())); if (hstore_conf.site.specexec_enable) this.specExecScheduler.interruptSearch(work); } /** * Add a new work message to our utility queue * @param work */ public void queueUtilityWork(InternalMessage work) { if (debug.val) LOG.debug(String.format("Added utility work %s to partition %d", work.getClass().getSimpleName(), this.partitionId)); this.work_queue.offer(work); } /** * Put the prepare request for the transaction into the queue * @param task * @param status The final status of the transaction */ public void queuePrepare(AbstractTransaction ts) { assert(ts.isInitialized()) : "Unexpected uninitialized transaction: " + ts; PrepareTxnMessage work = ts.getPrepareTxnMessage(); boolean success = this.work_queue.offer(work); assert(success) : String.format("Failed to queue %s at partition %d for %s", work, this.partitionId, ts); if (debug.val) LOG.debug(String.format("%s - Added %s to partition %d " + "work queue [size=%d]", ts, work.getClass().getSimpleName(), this.partitionId, this.work_queue.size())); // if (hstore_conf.site.specexec_enable) this.specExecScheduler.interruptSearch(); } /** * Put the finish request for the transaction into the queue * @param task * @param status The final status of the transaction */ public void queueFinish(AbstractTransaction ts, Status status) { assert(ts.isInitialized()) : "Unexpected uninitialized transaction: " + ts; FinishTxnMessage work = ts.getFinishTxnMessage(status); boolean success = this.work_queue.offer(work); // , true); assert(success) : String.format("Failed to queue %s at partition %d for %s", work, this.partitionId, ts); if (debug.val) LOG.debug(String.format("%s - Added %s to partition %d " + "work queue [size=%d]", ts, work.getClass().getSimpleName(), this.partitionId, this.work_queue.size())); // if (success) this.specExecScheduler.haltSearch(); } /** * Queue a new transaction invocation request at this partition * @param serializedRequest * @param catalog_proc * @param procParams * @param clientCallback * @return */ public boolean queueNewTransaction(ByteBuffer serializedRequest, long initiateTime, Procedure catalog_proc, ParameterSet procParams, RpcCallback<ClientResponseImpl> clientCallback) { boolean sysproc = catalog_proc.getSystemproc(); if (this.currentExecMode == ExecutionMode.DISABLED_REJECT && sysproc == false) return (false); InitializeRequestMessage work = new InitializeRequestMessage(serializedRequest, initiateTime, catalog_proc, procParams, clientCallback); if (debug.val) LOG.debug(String.format("Queuing %s for '%s' request on partition %d " + "[currentDtxn=%s, queueSize=%d, mode=%s]", work.getClass().getSimpleName(), catalog_proc.getName(), this.partitionId, this.currentDtxn, this.work_queue.size(), this.currentExecMode)); return (this.work_queue.offer(work)); } /** * Queue a new transaction invocation request at this partition * @param ts * @param task * @param callback */ public boolean queueStartTransaction(LocalTransaction ts) { assert(ts != null) : "Unexpected null transaction handle!"; boolean singlePartitioned = ts.isPredictSinglePartition(); boolean force = (singlePartitioned == false) || ts.isMapReduce() || ts.isSysProc(); // UPDATED 2012-07-12 // We used to have a bunch of checks to determine whether we needed // put the new request in the blocked queue or not. This required us to // acquire the exec_lock to do the check and then another lock to actually put // the request into the work_queue. Now we'll just throw it right in // the queue (checking for throttling of course) and let the main // thread sort out the mess of whether the txn should get blocked or not if (this.currentExecMode == ExecutionMode.DISABLED_REJECT) { if (debug.val) LOG.warn(String.format("%s - Not queuing txn at partition %d because current mode is %s", ts, this.partitionId, this.currentExecMode)); return (false); } StartTxnMessage work = ts.getStartTxnMessage(); if (debug.val) LOG.debug(String.format("Queuing %s for '%s' request on partition %d " + "[currentDtxn=%s, queueSize=%d, mode=%s]", work.getClass().getSimpleName(), ts.getProcedure().getName(), this.partitionId, this.currentDtxn, this.work_queue.size(), this.currentExecMode)); boolean success = this.work_queue.offer(work); // , force); if (debug.val && force && success == false) { String msg = String.format("Failed to add %s even though force flag was true!", ts); throw new ServerFaultException(msg, ts.getTransactionId()); } if (success && hstore_conf.site.specexec_enable) this.specExecScheduler.interruptSearch(work); return (success); } // --------------------------------------------------------------- // WORK QUEUE PROCESSING METHODS // --------------------------------------------------------------- /** * Process a WorkResult and update the internal state the LocalTransaction accordingly * Note that this will always be invoked by a thread other than the main execution thread * for this PartitionExecutor. That means if something comes back that's bad, we need a way * to alert the other thread so that it can act on it. * @param ts * @param result */ private void processWorkResult(LocalTransaction ts, WorkResult result) { boolean needs_profiling = (hstore_conf.site.txn_profiling && ts.profiler != null); if (debug.val) LOG.debug(String.format("Processing WorkResult for %s on partition %d [srcPartition=%d, deps=%d]", ts, this.partitionId, result.getPartitionId(), result.getDepDataCount())); // If the Fragment failed to execute, then we need to abort the Transaction // Note that we have to do this before we add the responses to the TransactionState so that // we can be sure that the VoltProcedure knows about the problem when it wakes the stored // procedure back up if (result.getStatus() != Status.OK) { if (trace.val) LOG.trace(String.format("Received non-success response %s from partition %d for %s", result.getStatus(), result.getPartitionId(), ts)); SerializableException error = null; if (needs_profiling) ts.profiler.startDeserialization(); try { ByteBuffer buffer = result.getError().asReadOnlyByteBuffer(); error = SerializableException.deserializeFromBuffer(buffer); } catch (Exception ex) { String msg = String.format("Failed to deserialize SerializableException from partition %d " + "for %s [bytes=%d]", result.getPartitionId(), ts, result.getError().size()); throw new ServerFaultException(msg, ex); } finally { if (needs_profiling) ts.profiler.stopDeserialization(); } // At this point there is no need to even deserialize the rest of the message because // we know that we're going to have to abort the transaction if (error == null) { LOG.warn(ts + " - Unexpected null SerializableException\n" + result); } else { if (debug.val) LOG.error(String.format("%s - Got error from partition %d in %s", ts, result.getPartitionId(), result.getClass().getSimpleName()), error); ts.setPendingError(error, true); } return; } if (needs_profiling) ts.profiler.startDeserialization(); for (int i = 0, cnt = result.getDepDataCount(); i < cnt; i++) { if (trace.val) LOG.trace(String.format("Storing intermediate results from partition %d for %s", result.getPartitionId(), ts)); int depId = result.getDepId(i); ByteString bs = result.getDepData(i); VoltTable vt = null; if (bs.isEmpty() == false) { FastDeserializer fd = new FastDeserializer(bs.asReadOnlyByteBuffer()); try { vt = fd.readObject(VoltTable.class); } catch (Exception ex) { throw new ServerFaultException("Failed to deserialize VoltTable from partition " + result.getPartitionId() + " for " + ts, ex); } } this.depTracker.addResult(ts, result.getPartitionId(), depId, vt); } // FOR (dependencies) if (needs_profiling) ts.profiler.stopDeserialization(); } /** * Execute a new transaction at this partition. * This will invoke the run() method define in the VoltProcedure for this txn and * then process the ClientResponse. Only the PartitionExecutor itself should be calling * this directly, since it's the only thing that knows what's going on with the world... * @param ts */ private void executeTransaction(LocalTransaction ts) { assert(ts.isInitialized()) : String.format("Trying to execute uninitialized transaction %s at partition %d", ts, this.partitionId); assert(ts.isMarkedReleased(this.partitionId)) : String.format("Transaction %s was not marked released at partition %d before being executed", ts, this.partitionId); if (trace.val) LOG.debug(String.format("%s - Attempting to start transaction on partition %d", ts, this.partitionId)); // If this is a MapReduceTransaction handle, we actually want to get the // inner LocalTransaction handle for this partition. The MapReduceTransaction // is just a placeholder if (ts instanceof MapReduceTransaction) { MapReduceTransaction mr_ts = (MapReduceTransaction)ts; ts = mr_ts.getLocalTransaction(this.partitionId); assert(ts != null) : "Unexpected null LocalTransaction handle from " + mr_ts; } ExecutionMode before_mode = this.currentExecMode; boolean predict_singlePartition = ts.isPredictSinglePartition(); // ------------------------------- // DISTRIBUTED TXN // ------------------------------- if (predict_singlePartition == false) { // If there is already a dtxn running, then we need to throw this // mofo back into the blocked txn queue // TODO: If our dtxn is on the same site as us, then at this point we know that // it is done executing the control code and is sending around 2PC messages // to commit/abort. That means that we could assume that all of the other // remote partitions are going to agree on the same outcome and we can start // speculatively executing this dtxn. After all, if we're at this point in // the PartitionExecutor then we know that we got this partition's locks // from the TransactionQueueManager. if (this.currentDtxn != null && this.currentDtxn.equals(ts) == false) { assert(this.currentDtxn.equals(ts) == false) : String.format("New DTXN %s != Current DTXN %s", ts, this.currentDtxn); // If this is a local txn, then we can finagle things a bit. if (this.currentDtxn.isExecLocal(this.partitionId)) { // It would be safe for us to speculative execute this DTXN right here // if the currentDtxn has aborted... but we can never be in this state. assert(this.currentDtxn.isAborted() == false) : // Sanity Check String.format("We want to execute %s on partition %d but aborted %s is still hanging around\n", ts, this.partitionId, this.currentDtxn, this.work_queue); // So that means we know that it committed, which doesn't necessarily mean // that it will still commit, but we'll be able to abort, rollback, and requeue // if that happens. // TODO: Right now our current dtxn marker is a single value. We may want to // switch it to a FIFO queue so that we can multiple guys hanging around. // For now we will just do the default thing and block this txn this.blockTransaction(ts); return; } // If it's not local, then we just have to block it right away else { this.blockTransaction(ts); return; } } // If there is no other DTXN right now, then we're it! else if (this.currentDtxn == null) { // || this.currentDtxn.equals(ts) == false) { this.setCurrentDtxn(ts); } // 2011-11-14: We don't want to set the execution mode here, because we know that we // can check whether we were read-only after the txn finishes this.setExecutionMode(this.currentDtxn, ExecutionMode.COMMIT_NONE); if (debug.val) LOG.debug(String.format("Marking %s as current DTXN on Partition %d [isLocal=%s, execMode=%s]", ts, this.partitionId, true, this.currentExecMode)); } // ------------------------------- // SINGLE-PARTITION TXN // ------------------------------- else { // If this is a single-partition transaction, then we need to check whether we are // being executed under speculative execution mode. We have to check this here // because it may be the case that we queued a bunch of transactions when speculative // execution was enabled, but now the transaction that was ahead of this one is finished, // so now we're just executing them regularly if (this.currentDtxn != null) { // HACK: If we are currently under DISABLED mode when we get this, then we just // need to block the transaction and return back to the queue. This is easier than // having to set all sorts of crazy locks if (this.currentExecMode == ExecutionMode.DISABLED || hstore_conf.site.specexec_enable == false) { if (debug.val) LOG.debug(String.format("%s - Blocking single-partition %s until dtxn finishes [mode=%s]", this.currentDtxn, ts, this.currentExecMode)); this.blockTransaction(ts); return; } assert(ts.getSpeculationType() != null); if (debug.val) LOG.debug(String.format("Speculatively executing %s while waiting for dtxn %s [%s]", ts, this.currentDtxn, ts.getSpeculationType())); assert(ts.isSpeculative()) : ts + " was not marked as being speculative!"; } } // If we reach this point, we know that we're about to execute our homeboy here... if (hstore_conf.site.txn_profiling && ts.profiler != null) { ts.profiler.startExec(); } if (hstore_conf.site.exec_profiling) this.profiler.numTransactions++; // Make sure the dependency tracker knows about us if (ts.hasDependencyTracker()) this.depTracker.addTransaction(ts); // Grab a new ExecutionState for this txn ExecutionState execState = this.initExecutionState(); ts.setExecutionState(execState); VoltProcedure volt_proc = this.getVoltProcedure(ts.getProcedure().getId()); assert(volt_proc != null) : "No VoltProcedure for " + ts; if (debug.val) { LOG.debug(String.format("%s - Starting execution of txn on partition %d " + "[txnMode=%s, mode=%s]", ts, this.partitionId, before_mode, this.currentExecMode)); if (trace.val) LOG.trace(String.format("Current Transaction at partition #%d\n%s", this.partitionId, ts.debug())); } if (hstore_conf.site.txn_counters) TransactionCounter.EXECUTED.inc(ts.getProcedure()); ClientResponseImpl cresponse = null; VoltProcedure previous = this.currentVoltProc; try { this.currentVoltProc = volt_proc; cresponse = volt_proc.call(ts, ts.getProcedureParameters().toArray()); // Blocking... // VoltProcedure.call() should handle any exceptions thrown by the transaction // If we get anything out here then that's bad news } catch (Throwable ex) { if (this.isShuttingDown() == false) { SQLStmt last[] = volt_proc.voltLastQueriesExecuted(); LOG.fatal("Unexpected error while executing " + ts, ex); if (last.length > 0) { LOG.fatal(String.format("Last Queries Executed [%d]: %s", last.length, Arrays.toString(last))); } LOG.fatal("LocalTransactionState Dump:\n" + ts.debug()); this.crash(ex); } } finally { this.currentVoltProc = previous; ts.resetExecutionState(); execState.finish(); this.execStates.add(execState); this.finishVoltProcedure(volt_proc); if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.startPost(); // if (cresponse.getStatus() == Status.ABORT_UNEXPECTED) { // cresponse.getException().printStackTrace(); // } } // If this is a MapReduce job, then we can just ignore the ClientResponse // and return immediately. The VoltMapReduceProcedure is responsible for storing // the result at the proper location. if (ts.isMapReduce()) { return; } else if (cresponse == null) { assert(this.isShuttingDown()) : String.format("No ClientResponse for %s???", ts); return; } // ------------------------------- // PROCESS RESPONSE AND FIGURE OUT NEXT STEP // ------------------------------- Status status = cresponse.getStatus(); if (debug.val) { LOG.debug(String.format("%s - Finished execution of transaction control code " + "[status=%s, beforeMode=%s, currentMode=%s]", ts, status, before_mode, this.currentExecMode)); if (ts.hasPendingError()) { LOG.debug(String.format("%s - Txn finished with pending error: %s", ts, ts.getPendingErrorMessage())); } } // We assume that most transactions are not speculatively executed and are successful // Therefore we don't want to grab the exec_mode lock here. if (predict_singlePartition == false || this.canProcessClientResponseNow(ts, status, before_mode)) { this.processClientResponse(ts, cresponse); } // Otherwise always queue our response, since we know that whatever thread is out there // is waiting for us to finish before it drains the queued responses else { // If the transaction aborted, then we can't execute any transaction that touch the tables // that this guy touches. But since we can't just undo this transaction without undoing // everything that came before it, we'll just disable executing all transactions until the // current distributed transaction commits if (status != Status.OK && ts.isExecReadOnly(this.partitionId) == false) { this.setExecutionMode(ts, ExecutionMode.DISABLED); int blocked = this.work_queue.drainTo(this.currentBlockedTxns); if (debug.val) { if (trace.val && blocked > 0) LOG.trace(String.format("Blocking %d transactions at partition %d because ExecutionMode is now %s", blocked, this.partitionId, this.currentExecMode)); LOG.debug(String.format("Disabling execution on partition %d because speculative %s aborted", this.partitionId, ts)); } } if (trace.val) LOG.trace(String.format("%s - Queuing ClientResponse [status=%s, origMode=%s, newMode=%s, dtxn=%s]", ts, cresponse.getStatus(), before_mode, this.currentExecMode, this.currentDtxn)); this.blockClientResponse(ts, cresponse); } } /** * Determines whether a finished transaction that executed locally can have their ClientResponse processed immediately * or if it needs to wait for the response from the outstanding multi-partition transaction for this partition * (1) This is the multi-partition transaction that everyone is waiting for * (2) The transaction was not executed under speculative execution mode * (3) The transaction does not need to wait for the multi-partition transaction to finish first * @param ts * @param status * @param before_mode * @return */ private boolean canProcessClientResponseNow(LocalTransaction ts, Status status, ExecutionMode before_mode) { if (debug.val) LOG.debug(String.format("%s - Checking whether to process %s response now at partition %d " + "[singlePartition=%s, readOnly=%s, specExecModified=%s, before=%s, current=%s]", ts, status, this.partitionId, ts.isPredictSinglePartition(), ts.isExecReadOnly(this.partitionId), this.specExecModified, before_mode, this.currentExecMode)); // Commit All if (this.currentExecMode == ExecutionMode.COMMIT_ALL) { return (true); } // SPECIAL CASE // Any user-aborted, speculative single-partition transaction should be processed immediately. else if (status == Status.ABORT_USER && ts.isSpeculative()) { return (true); } // // SPECIAL CASE // // If this txn threw a user abort, and the current outstanding dtxn is read-only // // then it's safe for us to rollback // else if (status == Status.ABORT_USER && // this.currentDtxn != null && // this.currentDtxn.isExecReadOnly(this.partitionId)) { // return (true); // } // SPECIAL CASE // Anything mispredicted should be processed right away else if (status == Status.ABORT_MISPREDICT) { return (true); } // Process successful txns based on the mode that it was executed under else if (status == Status.OK) { switch (before_mode) { case COMMIT_ALL: return (true); case COMMIT_READONLY: // Read-only speculative txns can be committed right now // TODO: Right now we're going to use the specExecModified flag to disable // sending out any results from spec execed txns that may have read from // a modified database. We should switch to a bitmap of table ids so that we // have can be more selective. // return (false); return (this.specExecModified == false && ts.isExecReadOnly(this.partitionId)); case COMMIT_NONE: { // If this txn does not conflict with the current dtxn, then we should be able // to let it commit but we can't because of the way our undo tokens work return (false); } default: throw new ServerFaultException("Unexpected execution mode: " + before_mode, ts.getTransactionId()); } // SWITCH } // // If the transaction aborted and it was read-only thus far, then we want to process it immediately // else if (status != Status.OK && ts.isExecReadOnly(this.partitionId)) { // return (true); // } assert(this.currentExecMode != ExecutionMode.COMMIT_ALL) : String.format("Queuing ClientResponse for %s when in non-specutative mode [mode=%s, status=%s]", ts, this.currentExecMode, status); return (false); } /** * Process a WorkFragment for a transaction and execute it in this partition's underlying EE. * @param ts * @param fragment * @param allParameters The array of all the ParameterSets for the current SQLStmt batch. */ private void processWorkFragment(AbstractTransaction ts, WorkFragment fragment, ParameterSet allParameters[]) { assert(this.partitionId == fragment.getPartitionId()) : String.format("Tried to execute WorkFragment %s for %s at partition %d but it was suppose " + "to be executed on partition %d", fragment.getFragmentIdList(), ts, this.partitionId, fragment.getPartitionId()); assert(ts.isMarkedPrepared(this.partitionId) == false) : String.format("Tried to execute WorkFragment %s for %s at partition %d after it was marked 2PC:PREPARE", fragment.getFragmentIdList(), ts, this.partitionId); // A txn is "local" if the Java is executing at the same partition as this one boolean is_basepartition = (ts.getBasePartition() == this.partitionId); boolean is_remote = (ts instanceof LocalTransaction == false); boolean is_prefetch = fragment.getPrefetch(); boolean is_readonly = fragment.getReadOnly(); if (debug.val) LOG.debug(String.format("%s - Executing %s [isBasePartition=%s, isRemote=%s, isPrefetch=%s, isReadOnly=%s, fragments=%s]", ts, fragment.getClass().getSimpleName(), is_basepartition, is_remote, is_prefetch, is_readonly, fragment.getFragmentIdCount())); // If this WorkFragment isn't being executed at this txn's base partition, then // we need to start a new execution round if (is_basepartition == false) { long undoToken = this.calculateNextUndoToken(ts, is_readonly); ts.initRound(this.partitionId, undoToken); ts.startRound(this.partitionId); } DependencySet result = null; Status status = Status.OK; SerializableException error = null; // Check how many fragments are not marked as ignored // If the fragment is marked as ignore then it means that it was already // sent to this partition for prefetching. We need to make sure that we remove // it from the list of fragmentIds that we need to execute. int fragmentCount = fragment.getFragmentIdCount(); for (int i = 0; i < fragmentCount; i++) { if (fragment.getStmtIgnore(i)) { fragmentCount--; } } // FOR final ParameterSet parameters[] = tmp_fragmentParams.getParameterSet(fragmentCount); assert(parameters.length == fragmentCount); // Construct data given to the EE to execute this work fragment this.tmp_EEdependencies.clear(); long fragmentIds[] = tmp_fragmentIds.getArray(fragmentCount); int fragmentOffsets[] = tmp_fragmentOffsets.getArray(fragmentCount); int outputDepIds[] = tmp_outputDepIds.getArray(fragmentCount); int inputDepIds[] = tmp_inputDepIds.getArray(fragmentCount); int offset = 0; for (int i = 0, cnt = fragment.getFragmentIdCount(); i < cnt; i++) { if (fragment.getStmtIgnore(i) == false) { fragmentIds[offset] = fragment.getFragmentId(i); fragmentOffsets[offset] = i; outputDepIds[offset] = fragment.getOutputDepId(i); inputDepIds[offset] = fragment.getInputDepId(i); parameters[offset] = allParameters[fragment.getParamIndex(i)]; this.getFragmentInputs(ts, inputDepIds[offset], this.tmp_EEdependencies); if (trace.val && ts.isSysProc() == false && is_basepartition == false) LOG.trace(String.format("%s - Offset:%d FragmentId:%d OutputDep:%d/%d InputDep:%d/%d", ts, offset, fragmentIds[offset], outputDepIds[offset], fragment.getOutputDepId(i), inputDepIds[offset], fragment.getInputDepId(i))); offset++; } } // FOR assert(offset == fragmentCount); try { result = this.executeFragmentIds(ts, ts.getLastUndoToken(this.partitionId), fragmentIds, parameters, outputDepIds, inputDepIds, this.tmp_EEdependencies); } catch (EvictedTupleAccessException ex) { // XXX: What do we do if this is not a single-partition txn? status = Status.ABORT_EVICTEDACCESS; error = ex; } catch (ConstraintFailureException ex) { status = Status.ABORT_UNEXPECTED; error = ex; } catch (SQLException ex) { status = Status.ABORT_UNEXPECTED; error = ex; } catch (EEException ex) { // this.crash(ex); status = Status.ABORT_UNEXPECTED; error = ex; } catch (Throwable ex) { status = Status.ABORT_UNEXPECTED; if (ex instanceof SerializableException) { error = (SerializableException)ex; } else { error = new SerializableException(ex); } } finally { if (error != null) { // error.printStackTrace(); LOG.warn(String.format("%s - Unexpected %s on partition %d", ts, error.getClass().getSimpleName(), this.partitionId), error); // (debug.val ? error : null)); } // Success, but without any results??? if (result == null && status == Status.OK) { String msg = String.format("The WorkFragment %s executed successfully on Partition %d but " + "result is null for %s", fragment.getFragmentIdList(), this.partitionId, ts); Exception ex = new Exception(msg); if (debug.val) LOG.warn(ex); status = Status.ABORT_UNEXPECTED; error = new SerializableException(ex); } } // For single-partition INSERT/UPDATE/DELETE queries, we don't directly // execute the SendPlanNode in order to get back the number of tuples that // were modified. So we have to rely on the output dependency ids set in the task assert(status != Status.OK || (status == Status.OK && result.size() == fragmentIds.length)) : "Got back " + result.size() + " results but was expecting " + fragmentIds.length; // Make sure that we mark the round as finished before we start sending results if (is_basepartition == false) { ts.finishRound(this.partitionId); } // ------------------------------- // PREFETCH QUERIES // ------------------------------- if (is_prefetch) { // Regardless of whether this txn is running at the same HStoreSite as this PartitionExecutor, // we always need to put the result inside of the local query cache // This is so that we can identify if we get request for a query that we have already executed // We'll only do this if it succeeded. If it failed, then we won't do anything and will // just wait until they come back to execute the query again before // we tell them that something went wrong. It's ghetto, but it's just easier this way... if (status == Status.OK) { // We're going to store the result in the base partition cache if they're // on the same HStoreSite as us if (is_remote == false) { PartitionExecutor other = this.hstore_site.getPartitionExecutor(ts.getBasePartition()); for (int i = 0, cnt = result.size(); i < cnt; i++) { if (trace.val) LOG.trace(String.format("%s - Storing %s prefetch result [params=%s]", ts, CatalogUtil.getPlanFragment(catalogContext.catalog, fragment.getFragmentId(fragmentOffsets[i])).fullName(), parameters[i])); other.addPrefetchResult((LocalTransaction)ts, fragment.getStmtCounter(fragmentOffsets[i]), fragment.getFragmentId(fragmentOffsets[i]), this.partitionId, parameters[i].hashCode(), result.dependencies[i]); } // FOR } } // Now if it's a remote transaction, we need to use the coordinator to send // them our result. Note that we want to send a single message per partition. Unlike // with the TransactionWorkRequests, we don't need to wait until all of the partitions // that are prefetching for this txn at our local HStoreSite to finish. if (is_remote) { WorkResult wr = this.buildWorkResult(ts, result, status, error); TransactionPrefetchResult.Builder builder = TransactionPrefetchResult.newBuilder() .setTransactionId(ts.getTransactionId().longValue()) .setSourcePartition(this.partitionId) .setResult(wr) .setStatus(status) .addAllFragmentId(fragment.getFragmentIdList()) .addAllStmtCounter(fragment.getStmtCounterList()); for (int i = 0, cnt = fragment.getFragmentIdCount(); i < cnt; i++) { builder.addParamHash(parameters[i].hashCode()); } if (debug.val) LOG.debug(String.format("%s - Sending back %s to partition %d [numResults=%s, status=%s]", ts, wr.getClass().getSimpleName(), ts.getBasePartition(), result.size(), status)); hstore_coordinator.transactionPrefetchResult((RemoteTransaction)ts, builder.build()); } } // ------------------------------- // LOCAL TRANSACTION // ------------------------------- else if (is_remote == false) { LocalTransaction local_ts = (LocalTransaction)ts; // If the transaction is local, store the result directly in the local TransactionState if (status == Status.OK) { if (trace.val) LOG.trace(String.format("%s - Storing %d dependency results locally for successful work fragment", ts, result.size())); assert(result.size() == outputDepIds.length); DependencyTracker otherTracker = this.hstore_site.getDependencyTracker(ts.getBasePartition()); for (int i = 0; i < outputDepIds.length; i++) { if (trace.val) LOG.trace(String.format("%s - Storing DependencyId #%d [numRows=%d]\n%s", ts, outputDepIds[i], result.dependencies[i].getRowCount(), result.dependencies[i])); try { otherTracker.addResult(local_ts, this.partitionId, outputDepIds[i], result.dependencies[i]); } catch (Throwable ex) { // ex.printStackTrace(); String msg = String.format("Failed to stored Dependency #%d for %s [idx=%d, fragmentId=%d]", outputDepIds[i], ts, i, fragmentIds[i]); LOG.error(String.format("%s - WorkFragment:%d\nExpectedIds:%s\nOutputDepIds: %s\nResultDepIds: %s\n%s", msg, fragment.hashCode(), fragment.getOutputDepIdList(), Arrays.toString(outputDepIds), Arrays.toString(result.depIds), fragment)); throw new ServerFaultException(msg, ex); } } // FOR } else { local_ts.setPendingError(error, true); } } // ------------------------------- // REMOTE TRANSACTION // ------------------------------- else { if (trace.val) LOG.trace(String.format("%s - Constructing WorkResult with %d bytes from partition %d to send " + "back to initial partition %d [status=%s]", ts, (result != null ? result.size() : null), this.partitionId, ts.getBasePartition(), status)); RpcCallback<WorkResult> callback = ((RemoteTransaction)ts).getWorkCallback(); if (callback == null) { LOG.fatal("Unable to send FragmentResponseMessage for " + ts); LOG.fatal("Orignal WorkFragment:\n" + fragment); LOG.fatal(ts.toString()); throw new ServerFaultException("No RPC callback to HStoreSite for " + ts, ts.getTransactionId()); } WorkResult response = this.buildWorkResult((RemoteTransaction)ts, result, status, error); assert(response != null); callback.run(response); } // Check whether this is the last query that we're going to get // from this transaction. If it is, then we can go ahead and prepare the txn if (is_basepartition == false && fragment.getLastFragment()) { if (debug.val) LOG.debug(String.format("%s - Invoking early 2PC:PREPARE at partition %d", ts, this.partitionId)); this.queuePrepare(ts); } } /** * Executes a WorkFragment on behalf of some remote site and returns the * resulting DependencySet * @param fragment * @return * @throws Exception */ private DependencySet executeFragmentIds(AbstractTransaction ts, long undoToken, long fragmentIds[], ParameterSet parameters[], int output_depIds[], int input_depIds[], Map<Integer, List<VoltTable>> input_deps) throws Exception { if (fragmentIds.length == 0) { LOG.warn(String.format("Got a fragment batch for %s that does not have any fragments?", ts)); return (null); } // *********************************** DEBUG *********************************** if (trace.val) { LOG.trace(String.format("%s - Getting ready to kick %d fragments to partition %d EE [undoToken=%d]", ts, fragmentIds.length, this.partitionId, (undoToken != HStoreConstants.NULL_UNDO_LOGGING_TOKEN ? undoToken : "null"))); // if (trace.val) { // LOG.trace("WorkFragmentIds: " + Arrays.toString(fragmentIds)); // Map<String, Object> m = new LinkedHashMap<String, Object>(); // for (int i = 0; i < parameters.length; i++) { // m.put("Parameter[" + i + "]", parameters[i]); // } // FOR // LOG.trace("Parameters:\n" + StringUtil.formatMaps(m)); // } } // *********************************** DEBUG *********************************** DependencySet result = null; // ------------------------------- // SYSPROC FRAGMENTS // ------------------------------- if (ts.isSysProc()) { result = this.executeSysProcFragments(ts, undoToken, fragmentIds.length, fragmentIds, parameters, output_depIds, input_depIds, input_deps); // ------------------------------- // REGULAR FRAGMENTS // ------------------------------- } else { result = this.executePlanFragments(ts, undoToken, fragmentIds.length, fragmentIds, parameters, output_depIds, input_depIds, input_deps); if (result == null) { LOG.warn(String.format("Output DependencySet for %s in %s is null?", Arrays.toString(fragmentIds), ts)); } } return (result); } /** * Execute a BatchPlan directly on this PartitionExecutor without having to covert it * to WorkFragments first. This is big speed improvement over having to queue things up * @param ts * @param plan * @return */ private VoltTable[] executeLocalPlan(LocalTransaction ts, BatchPlanner.BatchPlan plan, ParameterSet parameterSets[]) { // Start the new execution round long undoToken = this.calculateNextUndoToken(ts, plan.isReadOnly()); ts.initFirstRound(undoToken, plan.getBatchSize()); int fragmentCount = plan.getFragmentCount(); long fragmentIds[] = plan.getFragmentIds(); int output_depIds[] = plan.getOutputDependencyIds(); int input_depIds[] = plan.getInputDependencyIds(); // Mark that we touched the local partition once for each query in the batch // ts.getTouchedPartitions().put(this.partitionId, plan.getBatchSize()); // Only notify other partitions that we're done with them if we're not // a single-partition transaction if (hstore_conf.site.specexec_enable && ts.isPredictSinglePartition() == false) { //FIXME //PartitionSet new_done = ts.calculateDonePartitions(this.thresholds); //if (new_done != null && new_done.isEmpty() == false) { // LocalPrepareCallback callback = ts.getPrepareCallback(); // assert(callback.isInitialized()); // this.hstore_coordinator.transactionPrepare(ts, callback, new_done); //} } if (trace.val) LOG.trace(String.format("Txn #%d - BATCHPLAN:\n" + " fragmentIds: %s\n" + " fragmentCount: %s\n" + " output_depIds: %s\n" + " input_depIds: %s", ts.getTransactionId(), Arrays.toString(plan.getFragmentIds()), plan.getFragmentCount(), Arrays.toString(plan.getOutputDependencyIds()), Arrays.toString(plan.getInputDependencyIds()))); // NOTE: There are no dependencies that we need to pass in because the entire // batch is local to this partition. DependencySet result = null; try { result = this.executePlanFragments(ts, undoToken, fragmentCount, fragmentIds, parameterSets, output_depIds, input_depIds, null); } finally { ts.fastFinishRound(this.partitionId); } // assert(result != null) : "Unexpected null DependencySet result for " + ts; if (trace.val) LOG.trace("Output:\n" + result); return (result != null ? result.dependencies : null); } /** * Execute the given fragment tasks on this site's underlying EE * @param ts * @param undoToken * @param batchSize * @param fragmentIds * @param parameterSets * @param output_depIds * @param input_depIds * @return */ private DependencySet executeSysProcFragments(AbstractTransaction ts, long undoToken, int batchSize, long fragmentIds[], ParameterSet parameters[], int output_depIds[], int input_depIds[], Map<Integer, List<VoltTable>> input_deps) { assert(fragmentIds.length == 1); assert(fragmentIds.length == parameters.length) : String.format("%s - Fragments:%d / Parameters:%d", ts, fragmentIds.length, parameters.length); VoltSystemProcedure volt_proc = this.m_registeredSysProcPlanFragments.get(fragmentIds[0]); if (volt_proc == null) { String msg = "No sysproc handle exists for FragmentID #" + fragmentIds[0] + " :: " + this.m_registeredSysProcPlanFragments; throw new ServerFaultException(msg, ts.getTransactionId()); } // HACK: We have to set the TransactionState for sysprocs manually volt_proc.setTransactionState(ts); ts.markExecNotReadOnly(this.partitionId); DependencySet result = null; try { result = volt_proc.executePlanFragment(ts.getTransactionId(), this.tmp_EEdependencies, (int)fragmentIds[0], parameters[0], this.m_systemProcedureContext); } catch (Throwable ex) { String msg = "Unexpected error when executing system procedure"; throw new ServerFaultException(msg, ex, ts.getTransactionId()); } if (debug.val) LOG.debug(String.format("%s - Finished executing sysproc fragment for %s (#%d)%s", ts, m_registeredSysProcPlanFragments.get(fragmentIds[0]).getClass().getSimpleName(), fragmentIds[0], (trace.val ? "\n" + result : ""))); return (result); } /** * Execute the given fragment tasks on this site's underlying EE * @param ts * @param undoToken * @param batchSize * @param fragmentIds * @param parameterSets * @param output_depIds * @param input_depIds * @return */ private DependencySet executePlanFragments(AbstractTransaction ts, long undoToken, int batchSize, long fragmentIds[], ParameterSet parameterSets[], int output_depIds[], int input_depIds[], Map<Integer, List<VoltTable>> input_deps) { assert(this.ee != null) : "The EE object is null. This is bad!"; Long txn_id = ts.getTransactionId(); //LOG.info("in executePlanFragments()"); // *********************************** DEBUG *********************************** if (debug.val) { StringBuilder sb = new StringBuilder(); sb.append(String.format("%s - Executing %d fragments [lastTxnId=%d, undoToken=%d]", ts, batchSize, this.lastCommittedTxnId, undoToken)); // if (trace.val) { Map<String, Object> m = new LinkedHashMap<String, Object>(); m.put("Fragments", Arrays.toString(fragmentIds)); Map<Integer, Object> inner = new LinkedHashMap<Integer, Object>(); for (int i = 0; i < batchSize; i++) inner.put(i, parameterSets[i].toString()); m.put("Parameters", inner); if (batchSize > 0 && input_depIds[0] != HStoreConstants.NULL_DEPENDENCY_ID) { inner = new LinkedHashMap<Integer, Object>(); for (int i = 0; i < batchSize; i++) { List<VoltTable> deps = input_deps.get(input_depIds[i]); inner.put(input_depIds[i], (deps != null ? StringUtil.join("\n", deps) : "???")); } // FOR m.put("Input Dependencies", inner); } m.put("Output Dependencies", Arrays.toString(output_depIds)); sb.append("\n" + StringUtil.formatMaps(m)); // } LOG.debug(sb.toString().trim()); } // *********************************** DEBUG *********************************** // pass attached dependencies to the EE (for non-sysproc work). if (input_deps != null && input_deps.isEmpty() == false) { if (debug.val) LOG.debug(String.format("%s - Stashing %d InputDependencies at partition %d", ts, input_deps.size(), this.partitionId)); this.ee.stashWorkUnitDependencies(input_deps); } // Java-based Table Read-Write Sets boolean readonly = true; boolean speculative = ts.isSpeculative(); boolean singlePartition = ts.isPredictSinglePartition(); int tableIds[] = null; for (int i = 0; i < batchSize; i++) { boolean fragReadOnly = PlanFragmentIdGenerator.isPlanFragmentReadOnly(fragmentIds[i]); // We don't need to maintain read/write sets for non-speculative txns if (speculative || singlePartition == false) { if (fragReadOnly) { tableIds = catalogContext.getReadTableIds(Long.valueOf(fragmentIds[i])); if (tableIds != null) ts.markTableIdsRead(this.partitionId, tableIds); } else { tableIds = catalogContext.getWriteTableIds(Long.valueOf(fragmentIds[i])); if (tableIds != null) ts.markTableIdsWritten(this.partitionId, tableIds); } } readonly = readonly && fragReadOnly; } // Enable read/write set tracking if (hstore_conf.site.exec_readwrite_tracking && ts.hasExecutedWork(this.partitionId) == false) { if (trace.val) LOG.trace(String.format("%s - Enabling read/write set tracking in EE at partition %d", ts, this.partitionId)); this.ee.trackingEnable(txn_id); } // Check whether the txn has only exeuted read-only queries up to this point if (ts.isExecReadOnly(this.partitionId)) { if (readonly == false) { if (trace.val) LOG.trace(String.format("%s - Marking txn as not read-only %s", ts, Arrays.toString(fragmentIds))); ts.markExecNotReadOnly(this.partitionId); } // We can do this here because the only way that we're not read-only is if // we actually modify data at this partition ts.markExecutedWork(this.partitionId); } DependencySet result = null; boolean needs_profiling = false; if (ts.isExecLocal(this.partitionId)) { if (hstore_conf.site.txn_profiling && ((LocalTransaction)ts).profiler != null) { needs_profiling = true; ((LocalTransaction)ts).profiler.startExecEE(); } } Throwable error = null; try { assert(this.lastCommittedUndoToken < undoToken) : String.format("Trying to execute work using undoToken %d for %s but " + "it is less than the last committed undoToken %d at partition %d", undoToken, ts, this.lastCommittedUndoToken, this.partitionId); if (trace.val) LOG.trace(String.format("%s - Executing fragments %s at partition %d [undoToken=%d]", ts, Arrays.toString(fragmentIds), this.partitionId, undoToken)); result = this.ee.executeQueryPlanFragmentsAndGetDependencySet( fragmentIds, batchSize, input_depIds, output_depIds, parameterSets, batchSize, txn_id.longValue(), this.lastCommittedTxnId.longValue(), undoToken); } catch (AssertionError ex) { LOG.error("Fatal error when processing " + ts + "\n" + ts.debug()); error = ex; throw ex; } catch (EvictedTupleAccessException ex) { if (debug.val) LOG.warn("Caught EvictedTupleAccessException."); error = ex; throw ex; } catch (SerializableException ex) { if (debug.val) LOG.error(String.format("%s - Unexpected error in the ExecutionEngine on partition %d", ts, this.partitionId), ex); error = ex; throw ex; } catch (Throwable ex) { error = ex; String msg = String.format("%s - Failed to execute PlanFragments: %s", ts, Arrays.toString(fragmentIds)); throw new ServerFaultException(msg, ex); } finally { if (needs_profiling) ((LocalTransaction)ts).profiler.stopExecEE(); if (error == null && result == null) { LOG.warn(String.format("%s - Finished executing fragments but got back null results [fragmentIds=%s]", ts, Arrays.toString(fragmentIds))); } } // *********************************** DEBUG *********************************** if (debug.val) { if (result != null) { LOG.debug(String.format("%s - Finished executing fragments and got back %d results", ts, result.depIds.length)); } else { LOG.warn(String.format("%s - Finished executing fragments but got back null results? That seems bad...", ts)); } } // *********************************** DEBUG *********************************** return (result); } /** * Load a VoltTable directly into the EE at this partition. * <B>NOTE:</B> This should only be invoked by a system stored procedure. * @param txn_id * @param clusterName * @param databaseName * @param tableName * @param data * @param allowELT * @throws VoltAbortException */ public void loadTable(AbstractTransaction ts, String clusterName, String databaseName, String tableName, VoltTable data, int allowELT) throws VoltAbortException { Table table = this.catalogContext.database.getTables().getIgnoreCase(tableName); if (table == null) { throw new VoltAbortException("Table '" + tableName + "' does not exist in database " + clusterName + "." + databaseName); } if (debug.val) LOG.debug(String.format("Loading %d row(s) into %s [txnId=%d]", data.getRowCount(), table.getName(), ts.getTransactionId())); ts.markExecutedWork(this.partitionId); this.ee.loadTable(table.getRelativeIndex(), data, ts.getTransactionId(), this.lastCommittedTxnId.longValue(), ts.getLastUndoToken(this.partitionId), allowELT != 0); } /** * Load a VoltTable directly into the EE at this partition. * <B>NOTE:</B> This should only be used for testing * @param txnId * @param table * @param data * @param allowELT * @throws VoltAbortException */ protected void loadTable(Long txnId, Table table, VoltTable data, boolean allowELT) throws VoltAbortException { if (debug.val) LOG.debug(String.format("Loading %d row(s) into %s [txnId=%d]", data.getRowCount(), table.getName(), txnId)); this.ee.loadTable(table.getRelativeIndex(), data, txnId.longValue(), this.lastCommittedTxnId.longValue(), HStoreConstants.NULL_UNDO_LOGGING_TOKEN, allowELT); } /** * Execute a SQLStmt batch at this partition. This is the main entry point from * VoltProcedure for where we will execute a SQLStmt batch from a txn. * @param ts The txn handle that is executing this query batch * @param batchSize The number of SQLStmts that the txn queued up using voltQueueSQL() * @param batchStmts The SQLStmts that the txn is trying to execute * @param batchParams The input parameters for the SQLStmts * @param finalTask Whether the txn has marked this as the last batch that they will ever execute * @param forceSinglePartition Whether to force the BatchPlanner to only generate a single-partition plan * @return */ public VoltTable[] executeSQLStmtBatch(LocalTransaction ts, int batchSize, SQLStmt batchStmts[], ParameterSet batchParams[], boolean finalTask, boolean forceSinglePartition) { boolean needs_profiling = (hstore_conf.site.txn_profiling && ts.profiler != null); if (needs_profiling) { ts.profiler.addBatch(batchSize); ts.profiler.stopExecJava(); ts.profiler.startExecPlanning(); } // HACK: This is needed to handle updates on replicated tables properly // when there is only one partition in the cluster. if (catalogContext.numberOfPartitions == 1) { this.depTracker.addTransaction(ts); } if (hstore_conf.site.exec_deferrable_queries) { // TODO: Loop through batchStmts and check whether their corresponding Statement // is marked as deferrable. If so, then remove them from batchStmts and batchParams // (sliding everyone over by one in the arrays). Queue up the deferred query. // Be sure decrement batchSize after you finished processing this. // EXAMPLE: batchStmts[0].getStatement().getDeferrable() } // Calculate the hash code for this batch to see whether we already have a planner final Integer batchHashCode = VoltProcedure.getBatchHashCode(batchStmts, batchSize); BatchPlanner planner = this.batchPlanners.get(batchHashCode); if (planner == null) { // Assume fast case planner = new BatchPlanner(batchStmts, batchSize, ts.getProcedure(), this.p_estimator, forceSinglePartition); this.batchPlanners.put(batchHashCode, planner); } assert(planner != null); // At this point we have to calculate exactly what we need to do on each partition // for this batch. So somehow right now we need to fire this off to either our // local executor or to Evan's magical distributed transaction manager BatchPlanner.BatchPlan plan = planner.plan(ts.getTransactionId(), this.partitionId, ts.getPredictTouchedPartitions(), ts.getTouchedPartitions(), batchParams); assert(plan != null); if (trace.val) { LOG.trace(ts + " - Touched Partitions: " + ts.getTouchedPartitions().values()); LOG.trace(ts + " - Next BatchPlan:\n" + plan.toString()); } if (needs_profiling) ts.profiler.stopExecPlanning(); // Tell the TransactionEstimator that we're about to execute these mofos EstimatorState t_state = ts.getEstimatorState(); if (this.localTxnEstimator != null && t_state != null && t_state.isUpdatesEnabled()) { if (needs_profiling) ts.profiler.startExecEstimation(); try { this.localTxnEstimator.executeQueries(t_state, planner.getStatements(), plan.getStatementPartitions()); } finally { if (needs_profiling) ts.profiler.stopExecEstimation(); } } else if (t_state != null && t_state.shouldAllowUpdates()) { LOG.warn("Skipping estimator updates for " + ts); } // Check whether our plan was caused a mispredict // Doing it this way allows us to update the TransactionEstimator before we abort the txn if (plan.getMisprediction() != null) { MispredictionException ex = plan.getMisprediction(); ts.setPendingError(ex, false); assert(ex.getPartitions().isEmpty() == false) : "Unexpected empty PartitionSet for mispredicated txn " + ts; // Print Misprediction Debug if (hstore_conf.site.exec_mispredict_crash) { // Use a lock so that only dump out the first txn that fails synchronized (PartitionExecutor.class) { LOG.warn("\n" + EstimatorUtil.mispredictDebug(ts, planner, batchStmts, batchParams)); LOG.fatal(String.format("Crashing because site.exec_mispredict_crash is true [txn=%s]", ts)); this.crash(ex); } // SYNCH } else if (debug.val) { if (trace.val) LOG.warn("\n" + EstimatorUtil.mispredictDebug(ts, planner, batchStmts, batchParams)); LOG.debug(ts + " - Aborting and restarting mispredicted txn."); } throw ex; } // Keep track of the number of times that we've executed each query for this transaction int stmtCounters[] = this.tmp_stmtCounters.getArray(batchSize); for (int i = 0; i < batchSize; i++) { stmtCounters[i] = ts.updateStatementCounter(batchStmts[i].getStatement()); } // FOR if (ts.hasPrefetchQueries()) { PartitionSet stmtPartitions[] = plan.getStatementPartitions(); PrefetchState prefetchState = ts.getPrefetchState(); QueryTracker queryTracker = prefetchState.getExecQueryTracker(); assert(prefetchState != null); for (int i = 0; i < batchSize; i++) { // We always have to update the query tracker regardless of whether // the query was prefetched or not. This is so that we can ensure // that we execute the queries in the right order. Statement stmt = batchStmts[i].getStatement(); stmtCounters[i] = queryTracker.addQuery(stmt, stmtPartitions[i], batchParams[i]); } // FOR // FIXME PrefetchQueryUtil.checkSQLStmtBatch(this, ts, plan, batchSize, batchStmts, batchParams); } // PREFETCH VoltTable results[] = null; // FAST-PATH: Single-partition + Local // If the BatchPlan only has WorkFragments that are for this partition, then // we can use the fast-path executeLocalPlan() method if (plan.isSingledPartitionedAndLocal()) { if (trace.val) LOG.trace(String.format("%s - Sending %s directly to the ExecutionEngine at partition %d", ts, plan.getClass().getSimpleName(), this.partitionId)); // If this the finalTask flag is set to true, and we're only executing queries at this // partition, then we need to notify the other partitions that we're done with them. if (hstore_conf.site.exec_early_prepare && finalTask == true && ts.isPredictSinglePartition() == false && ts.isSysProc() == false && ts.allowEarlyPrepare() == true) { tmp_fragmentsPerPartition.clearValues(); tmp_fragmentsPerPartition.put(this.partitionId, batchSize); DonePartitionsNotification notify = this.computeDonePartitions(ts, null, tmp_fragmentsPerPartition, finalTask); if (notify != null && notify.hasSitesToNotify()) this.notifyDonePartitions(ts, notify); } // Execute the queries right away. results = this.executeLocalPlan(ts, plan, batchParams); } // DISTRIBUTED EXECUTION // Otherwise, we need to generate WorkFragments and then send the messages out // to our remote partitions using the HStoreCoordinator else { ExecutionState execState = ts.getExecutionState(); execState.tmp_partitionFragments.clear(); plan.getWorkFragmentsBuilders(ts.getTransactionId(), stmtCounters, execState.tmp_partitionFragments); if (debug.val) LOG.debug(String.format("%s - Using dispatchWorkFragments to execute %d %ss", ts, execState.tmp_partitionFragments.size(), WorkFragment.class.getSimpleName())); if (needs_profiling) { int remote_cnt = 0; PartitionSet stmtPartitions[] = plan.getStatementPartitions(); for (int i = 0; i < batchSize; i++) { if (stmtPartitions[i].get() != ts.getBasePartition()) remote_cnt++; if (trace.val) LOG.trace(String.format("%s - [%02d] stmt:%s / partitions:%s", ts, i, batchStmts[i].getStatement().getName(), stmtPartitions[i])); } // FOR if (trace.val) LOG.trace(String.format("%s - Remote Queries Count = %d", ts, remote_cnt)); ts.profiler.addRemoteQuery(remote_cnt); } // Block until we get all of our responses. results = this.dispatchWorkFragments(ts, batchSize, batchParams, execState.tmp_partitionFragments, finalTask); } if (debug.val && results == null) LOG.warn("Got back a null results array for " + ts + "\n" + plan.toString()); if (needs_profiling) ts.profiler.startExecJava(); return (results); } /** * * @param fresponse */ protected WorkResult buildWorkResult(AbstractTransaction ts, DependencySet result, Status status, SerializableException error) { WorkResult.Builder builder = WorkResult.newBuilder(); // Partition Id builder.setPartitionId(this.partitionId); // Status builder.setStatus(status); // SerializableException if (error != null) { int size = error.getSerializedSize(); BBContainer bc = this.buffer_pool.acquire(size); try { error.serializeToBuffer(bc.b); } catch (IOException ex) { String msg = "Failed to serialize error for " + ts; throw new ServerFaultException(msg, ex); } bc.b.rewind(); builder.setError(ByteString.copyFrom(bc.b)); bc.discard(); } // Push dependencies back to the remote partition that needs it if (status == Status.OK) { for (int i = 0, cnt = result.size(); i < cnt; i++) { builder.addDepId(result.depIds[i]); this.fs.clear(); try { result.dependencies[i].writeExternal(this.fs); ByteString bs = ByteString.copyFrom(this.fs.getBBContainer().b); builder.addDepData(bs); } catch (Exception ex) { throw new ServerFaultException(String.format("Failed to serialize output dependency %d for %s", result.depIds[i], ts), ex); } if (trace.val) LOG.trace(String.format("%s - Serialized Output Dependency %d\n%s", ts, result.depIds[i], result.dependencies[i])); } // FOR this.fs.getBBContainer().discard(); } return (builder.build()); } /** * This method is invoked when the PartitionExecutor wants to execute work at a remote HStoreSite. * The doneNotificationsPerSite is an array where each offset (based on SiteId) may contain * a PartitionSet of the partitions that this txn is finished with at the remote node and will * not be executing any work in the current batch. * @param ts * @param fragmentBuilders * @param parameterSets * @param doneNotificationsPerSite */ private void requestWork(LocalTransaction ts, Collection<WorkFragment.Builder> fragmentBuilders, List<ByteString> parameterSets, DonePartitionsNotification notify) { assert(fragmentBuilders.isEmpty() == false); assert(ts != null); Long txn_id = ts.getTransactionId(); if (trace.val) LOG.trace(String.format("%s - Wrapping %d %s into a %s", ts, fragmentBuilders.size(), WorkFragment.class.getSimpleName(), TransactionWorkRequest.class.getSimpleName())); // If our transaction was originally designated as a single-partitioned, then we need to make // sure that we don't touch any partition other than our local one. If we do, then we need abort // it and restart it as multi-partitioned boolean need_restart = false; boolean predict_singlepartition = ts.isPredictSinglePartition(); PartitionSet done_partitions = ts.getDonePartitions(); Estimate t_estimate = ts.getLastEstimate(); // Now we can go back through and start running all of the WorkFragments that were not blocked // waiting for an input dependency. Note that we pack all the fragments into a single // CoordinatorFragment rather than sending each WorkFragment in its own message for (WorkFragment.Builder fragmentBuilder : fragmentBuilders) { assert(this.depTracker.isBlocked(ts, fragmentBuilder) == false); final int target_partition = fragmentBuilder.getPartitionId(); final int target_site = catalogContext.getSiteIdForPartitionId(target_partition); final PartitionSet doneNotifications = (notify != null ? notify.getNotifications(target_site) : null); // Make sure that this isn't a single-partition txn trying to access a remote partition if (predict_singlepartition && target_partition != this.partitionId) { if (debug.val) LOG.debug(String.format("%s - Txn on partition %d is suppose to be " + "single-partitioned, but it wants to execute a fragment on partition %d", ts, this.partitionId, target_partition)); need_restart = true; break; } // Make sure that this txn isn't trying to access a partition that we said we were // done with earlier else if (done_partitions.contains(target_partition)) { if (debug.val) LOG.warn(String.format("%s on partition %d was marked as done on partition %d " + "but now it wants to go back for more!", ts, this.partitionId, target_partition)); need_restart = true; break; } // Make sure we at least have something to do! else if (fragmentBuilder.getFragmentIdCount() == 0) { LOG.warn(String.format("%s - Trying to send a WorkFragment request with 0 fragments", ts)); continue; } // Add in the specexec query estimate at this partition if needed if (hstore_conf.site.specexec_enable && t_estimate != null && t_estimate.hasQueryEstimate(target_partition)) { List<CountedStatement> queryEst = t_estimate.getQueryEstimate(target_partition); // if (debug.val) if (target_partition == 0) if (debug.val) LOG.debug(String.format("%s - Sending remote query estimate to partition %d " + "containing %d queries\n%s", ts, target_partition, queryEst.size(), StringUtil.join("\n", queryEst))); assert(queryEst.isEmpty() == false); QueryEstimate.Builder estBuilder = QueryEstimate.newBuilder(); for (CountedStatement countedStmt : queryEst) { estBuilder.addStmtIds(countedStmt.statement.getId()); estBuilder.addStmtCounters(countedStmt.counter); } // FOR fragmentBuilder.setFutureStatements(estBuilder); } // Get the TransactionWorkRequest.Builder for the remote HStoreSite // We will use this store our serialized input dependencies TransactionWorkRequestBuilder requestBuilder = tmp_transactionRequestBuilders[target_site]; if (requestBuilder == null) { requestBuilder = tmp_transactionRequestBuilders[target_site] = new TransactionWorkRequestBuilder(); } TransactionWorkRequest.Builder builder = requestBuilder.getBuilder(ts, doneNotifications); // Also keep track of what Statements they are executing so that we know // we need to send over the wire to them. requestBuilder.addParamIndexes(fragmentBuilder.getParamIndexList()); // Input Dependencies if (fragmentBuilder.getNeedsInput()) { if (debug.val) LOG.debug(String.format("%s - Retrieving input dependencies at partition %d", ts, this.partitionId)); tmp_removeDependenciesMap.clear(); for (int i = 0, cnt = fragmentBuilder.getInputDepIdCount(); i < cnt; i++) { this.getFragmentInputs(ts, fragmentBuilder.getInputDepId(i), tmp_removeDependenciesMap); } // FOR for (Entry<Integer, List<VoltTable>> e : tmp_removeDependenciesMap.entrySet()) { if (requestBuilder.hasInputDependencyId(e.getKey())) continue; if (debug.val) LOG.debug(String.format("%s - Attaching %d input dependencies to be sent to %s", ts, e.getValue().size(), HStoreThreadManager.formatSiteName(target_site))); for (VoltTable vt : e.getValue()) { this.fs.clear(); try { this.fs.writeObject(vt); builder.addAttachedDepId(e.getKey().intValue()); builder.addAttachedData(ByteString.copyFrom(this.fs.getBBContainer().b)); } catch (Exception ex) { String msg = String.format("Failed to serialize input dependency %d for %s", e.getKey(), ts); throw new ServerFaultException(msg, ts.getTransactionId()); } if (debug.val) LOG.debug(String.format("%s - Storing %d rows for InputDependency %d to send " + "to partition %d [bytes=%d]", ts, vt.getRowCount(), e.getKey(), fragmentBuilder.getPartitionId(), CollectionUtil.last(builder.getAttachedDataList()).size())); } // FOR requestBuilder.addInputDependencyId(e.getKey()); } // FOR this.fs.getBBContainer().discard(); } builder.addFragments(fragmentBuilder); } // FOR (tasks) // Bad mojo! We need to throw a MispredictionException so that the VoltProcedure // will catch it and we can propagate the error message all the way back to the HStoreSite if (need_restart) { if (trace.val) LOG.trace(String.format("Aborting %s because it was mispredicted", ts)); // This is kind of screwy because we don't actually want to send the touched partitions // histogram because VoltProcedure will just do it for us... throw new MispredictionException(txn_id, null); } // Stick on the ParameterSets that each site needs into the TransactionWorkRequest for (int target_site = 0; target_site < tmp_transactionRequestBuilders.length; target_site++) { TransactionWorkRequestBuilder builder = tmp_transactionRequestBuilders[target_site]; if (builder == null || builder.isDirty() == false) { continue; } assert(builder != null); builder.addParameterSets(parameterSets); // Bombs away! this.hstore_coordinator.transactionWork(ts, target_site, builder.build(), this.request_work_callback); if (debug.val) LOG.debug(String.format("%s - Sent Work request to remote site %s", ts, HStoreThreadManager.formatSiteName(target_site))); } // FOR } /** * Figure out what partitions this transaction is done with. This will only return * a PartitionSet of what partitions we think we're done with. * For each partition that we idenitfy that the txn is done with, we will check to see * whether the txn is going to execute a query at its site in this batch. If it's not, * then we will notify that HStoreSite through the HStoreCoordinator. * If the partition that it doesn't need anymore is local (i.e., it's at the same * HStoreSite that we're at right now), then we'll just pass them a quick message * to let them know that they can prepare the txn. * @param ts * @param estimate * @param fragmentsPerPartition A histogram of the number of PlanFragments the * txn will execute in this batch at each partition. * @param finalTask Whether the txn has marked this as the last batch that they will ever execute * @return A notification object that can be used to notify partitions that this txn is done with them. */ private DonePartitionsNotification computeDonePartitions(final LocalTransaction ts, final Estimate estimate, final FastIntHistogram fragmentsPerPartition, final boolean finalTask) { final PartitionSet touchedPartitions = ts.getPredictTouchedPartitions(); final PartitionSet donePartitions = ts.getDonePartitions(); // Compute the partitions that the txn will be finished with after this batch PartitionSet estDonePartitions = null; // If the finalTask flag is set to true, then the new done partitions // is every partition that this txn has locked if (finalTask) { estDonePartitions = touchedPartitions; } // Otherwise, we'll rely on the transaction's current estimate to figure it out. else { if (estimate == null || estimate.isValid() == false) { if (debug.val) LOG.debug(String.format("%s - Unable to compute new done partitions because there " + "is no valid estimate for the txn", ts, estimate.getClass().getSimpleName())); return (null); } estDonePartitions = estimate.getDonePartitions(this.thresholds); if (estDonePartitions == null || estDonePartitions.isEmpty()) { if (debug.val) LOG.debug(String.format("%s - There are no new done partitions identified by %s", ts, estimate.getClass().getSimpleName())); return (null); } } assert(estDonePartitions != null) : "Null done partitions for " + ts; assert(estDonePartitions.isEmpty() == false) : "Empty done partitions for " + ts; if (debug.val) LOG.debug(String.format("%s - New estimated done partitions %s%s", ts, estDonePartitions, (trace.val ? "\n"+estimate : ""))); // Note that we can actually be done with ourself, if this txn is only going to execute queries // at remote partitions. But we can't actually execute anything because this partition's only // execution thread is going to be blocked. So we always do this so that we're not sending a // useless message estDonePartitions.remove(this.partitionId); // Make sure that we only tell partitions that we actually touched, otherwise they will // be stuck waiting for a finish request that will never come! DonePartitionsNotification notify = new DonePartitionsNotification(); for (int partition : estDonePartitions.values()) { // Only mark the txn done at this partition if the Estimate says we were done // with it after executing this batch and it's a partition that we've locked. if (donePartitions.contains(partition) || touchedPartitions.contains(partition) == false) continue; if (trace.val) LOG.trace(String.format("%s - Marking partition %d as done for txn", ts, partition)); notify.donePartitions.add(partition); if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.markEarly2PCPartition(partition); // Check whether we're executing a query at this partition in this batch. // If we're not, then we need to check whether we can piggyback the "done" message // in another WorkFragment going to that partition or whether we have to // send a separate TransactionPrepareRequest if (fragmentsPerPartition.get(partition, 0) == 0) { // We need to let them know that the party is over! if (hstore_site.isLocalPartition(partition)) { // if (debug.val) LOG.info(String.format("%s - Notifying local partition %d that txn is finished it", ts, partition)); hstore_site.getPartitionExecutor(partition).queuePrepare(ts); } // Check whether we can piggyback on another WorkFragment that is going to // the same site else { Site remoteSite = catalogContext.getSiteForPartition(partition); boolean found = false; for (Partition remotePartition : remoteSite.getPartitions().values()) { if (fragmentsPerPartition.get(remotePartition.getId(), 0) != 0) { found = true; break; } } // FOR notify.addSiteNotification(remoteSite, partition, (found == false)); } } } // FOR return (notify); } /** * Send asynchronous notification messages to any remote site to tell them that we * are done with partitions that they have. * @param ts * @param notify */ private void notifyDonePartitions(LocalTransaction ts, DonePartitionsNotification notify) { // BLAST OUT NOTIFICATIONS! for (int remoteSiteId : notify._sitesToNotify) { assert(notify.notificationsPerSite[remoteSiteId] != null); if (debug.val) LOG.info(String.format("%s - Notifying %s that txn is finished with partitions %s", ts, HStoreThreadManager.formatSiteName(remoteSiteId), notify.notificationsPerSite[remoteSiteId])); hstore_coordinator.transactionPrepare(ts, ts.getPrepareCallback(), notify.notificationsPerSite[remoteSiteId]); // Make sure that we remove the PartitionSet for this site so that we don't // try to send the notifications again. notify.notificationsPerSite[remoteSiteId] = null; } // FOR } /** * Execute the given tasks and then block the current thread waiting for the list of dependency_ids to come * back from whatever it was we were suppose to do... * This is the slowest way to execute a bunch of WorkFragments and therefore should only be invoked * for batches that need to access non-local partitions * @param ts The txn handle that is executing this query batch * @param batchSize The number of SQLStmts that the txn queued up using voltQueueSQL() * @param batchParams The input parameters for the SQLStmts * @param allFragmentBuilders * @param finalTask Whether the txn has marked this as the last batch that they will ever execute * @return */ public VoltTable[] dispatchWorkFragments(final LocalTransaction ts, final int batchSize, final ParameterSet batchParams[], final Collection<WorkFragment.Builder> allFragmentBuilders, boolean finalTask) { assert(allFragmentBuilders.isEmpty() == false) : "Unexpected empty WorkFragment list for " + ts; final boolean needs_profiling = (hstore_conf.site.txn_profiling && ts.profiler != null); // *********************************** DEBUG *********************************** if (debug.val) { LOG.debug(String.format("%s - Preparing to dispatch %d messages and wait for the results [needsProfiling=%s]", ts, allFragmentBuilders.size(), needs_profiling)); if (trace.val) { StringBuilder sb = new StringBuilder(); sb.append(ts + " - WorkFragments:\n"); for (WorkFragment.Builder fragment : allFragmentBuilders) { sb.append(StringBoxUtil.box(fragment.toString()) + "\n"); } // FOR sb.append(ts + " - ParameterSets:\n"); for (ParameterSet ps : batchParams) { sb.append(ps + "\n"); } // FOR LOG.trace(sb); } } // *********************************** DEBUG *********************************** // OPTIONAL: Check to make sure that this request is valid // (1) At least one of the WorkFragments needs to be executed on a remote partition // (2) All of the PlanFragments ids in the WorkFragments match this txn's Procedure if (hstore_conf.site.exec_validate_work && ts.isSysProc() == false) { LOG.warn(String.format("%s - Checking whether all of the WorkFragments are valid", ts)); boolean has_remote = false; for (WorkFragment.Builder frag : allFragmentBuilders) { if (frag.getPartitionId() != this.partitionId) { has_remote = true; } for (int frag_id : frag.getFragmentIdList()) { PlanFragment catalog_frag = CatalogUtil.getPlanFragment(catalogContext.database, frag_id); Statement catalog_stmt = catalog_frag.getParent(); assert(catalog_stmt != null); Procedure catalog_proc = catalog_stmt.getParent(); if (catalog_proc.equals(ts.getProcedure()) == false) { LOG.warn(ts.debug() + "\n" + allFragmentBuilders + "\n---- INVALID ----\n" + frag); String msg = String.format("%s - Unexpected %s", ts, catalog_frag.fullName()); throw new ServerFaultException(msg, ts.getTransactionId()); } } } // FOR if (has_remote == false) { LOG.warn(ts.debug() + "\n" + allFragmentBuilders); String msg = ts + "Trying to execute all local single-partition queries using the slow-path!"; throw new ServerFaultException(msg, ts.getTransactionId()); } } boolean first = true; boolean serializedParams = false; CountDownLatch latch = null; boolean all_local = true; boolean is_localSite; boolean is_localPartition; boolean is_localReadOnly = true; int num_localPartition = 0; int num_localSite = 0; int num_remote = 0; int num_skipped = 0; int total = 0; Collection<WorkFragment.Builder> fragmentBuilders = allFragmentBuilders; // Make sure our txn is in our DependencyTracker if (trace.val) LOG.trace(String.format("%s - Added transaction to %s", ts, this.depTracker.getClass().getSimpleName())); this.depTracker.addTransaction(ts); // Count the number of fragments that we're going to send to each partition and // figure out whether the txn will always be read-only at this partition tmp_fragmentsPerPartition.clearValues(); for (WorkFragment.Builder fragmentBuilder : allFragmentBuilders) { int partition = fragmentBuilder.getPartitionId(); tmp_fragmentsPerPartition.put(partition); if (this.partitionId == partition && fragmentBuilder.getReadOnly() == false) { is_localReadOnly = false; } } // FOR long undoToken = this.calculateNextUndoToken(ts, is_localReadOnly); ts.initFirstRound(undoToken, batchSize); final boolean predict_singlePartition = ts.isPredictSinglePartition(); // Calculate whether we are finished with partitions now final Estimate lastEstimate = ts.getLastEstimate(); DonePartitionsNotification notify = null; if (hstore_conf.site.exec_early_prepare && ts.isSysProc() == false && ts.allowEarlyPrepare()) { notify = this.computeDonePartitions(ts, lastEstimate, tmp_fragmentsPerPartition, finalTask); if (notify != null && notify.hasSitesToNotify()) this.notifyDonePartitions(ts, notify); } // Attach the ParameterSets to our transaction handle so that anybody on this HStoreSite // can access them directly without needing to deserialize them from the WorkFragments ts.attachParameterSets(batchParams); // Now if we have some work sent out to other partitions, we need to wait until they come back // In the first part, we wait until all of our blocked WorkFragments become unblocked final BlockingDeque<Collection<WorkFragment.Builder>> queue = this.depTracker.getUnblockedWorkFragmentsQueue(ts); // Run through this loop if: // (1) We have no pending errors // (2) This is our first time in the loop (first == true) // (3) If we know that there are still messages being blocked // (4) If we know that there are still unblocked messages that we need to process // (5) The latch for this round is still greater than zero while (ts.hasPendingError() == false && (first == true || this.depTracker.stillHasWorkFragments(ts) || (latch != null && latch.getCount() > 0))) { if (trace.val) LOG.trace(String.format("%s - %s loop [first=%s, stillHasWorkFragments=%s, latch=%s]", ts, ClassUtil.getCurrentMethodName(), first, this.depTracker.stillHasWorkFragments(ts), queue.size(), latch)); // If this is the not first time through the loop, then poll the queue // to get our list of fragments if (first == false) { all_local = true; is_localSite = false; is_localPartition = false; num_localPartition = 0; num_localSite = 0; num_remote = 0; num_skipped = 0; total = 0; if (trace.val) LOG.trace(String.format("%s - Waiting for unblocked tasks on partition %d", ts, this.partitionId)); fragmentBuilders = queue.poll(); // NON-BLOCKING // If we didn't get back a list of fragments here, then we will spin through // and invoke utilityWork() to try to do something useful until what we need shows up if (needs_profiling) ts.profiler.startExecDtxnWork(); if (hstore_conf.site.exec_profiling) this.profiler.sp1_time.start(); try { while (fragmentBuilders == null) { // If there is more work that we could do, then we'll just poll the queue // without waiting so that we can go back and execute it again if we have // more time. if (this.utilityWork()) { fragmentBuilders = queue.poll(); } // Otherwise we will wait a little so that we don't spin the CPU else { fragmentBuilders = queue.poll(WORK_QUEUE_POLL_TIME, TimeUnit.MILLISECONDS); } } // WHILE } catch (InterruptedException ex) { if (this.hstore_site.isShuttingDown() == false) { LOG.error(String.format("%s - We were interrupted while waiting for blocked tasks", ts), ex); } return (null); } finally { if (needs_profiling) ts.profiler.stopExecDtxnWork(); if (hstore_conf.site.exec_profiling) this.profiler.sp1_time.stopIfStarted(); } } assert(fragmentBuilders != null); // If the list to fragments unblock is empty, then we // know that we have dispatched all of the WorkFragments for the // transaction's current SQLStmt batch. That means we can just wait // until all the results return to us. if (fragmentBuilders.isEmpty()) { if (trace.val) LOG.trace(String.format("%s - Got an empty list of WorkFragments at partition %d. " + "Blocking until dependencies arrive", ts, this.partitionId)); break; } this.tmp_localWorkFragmentBuilders.clear(); if (predict_singlePartition == false) { this.tmp_remoteFragmentBuilders.clear(); this.tmp_localSiteFragmentBuilders.clear(); } // ------------------------------- // FAST PATH: Assume everything is local // ------------------------------- if (predict_singlePartition) { for (WorkFragment.Builder fragmentBuilder : fragmentBuilders) { if (first == false || this.depTracker.addWorkFragment(ts, fragmentBuilder, batchParams)) { this.tmp_localWorkFragmentBuilders.add(fragmentBuilder); total++; num_localPartition++; } } // FOR // We have to tell the transaction handle to start the round before we send off the // WorkFragments for execution, since they might start executing locally! if (first) { ts.startRound(this.partitionId); latch = this.depTracker.getDependencyLatch(ts); } // Execute all of our WorkFragments quickly at our local ExecutionEngine for (WorkFragment.Builder fragmentBuilder : this.tmp_localWorkFragmentBuilders) { if (debug.val) LOG.debug(String.format("%s - Got unblocked %s to execute locally", ts, fragmentBuilder.getClass().getSimpleName())); assert(fragmentBuilder.getPartitionId() == this.partitionId) : String.format("Trying to process %s for %s on partition %d but it should have been " + "sent to partition %d [singlePartition=%s]\n%s", fragmentBuilder.getClass().getSimpleName(), ts, this.partitionId, fragmentBuilder.getPartitionId(), predict_singlePartition, fragmentBuilder); WorkFragment fragment = fragmentBuilder.build(); this.processWorkFragment(ts, fragment, batchParams); } // FOR } // ------------------------------- // SLOW PATH: Mixed local and remote messages // ------------------------------- else { // Look at each task and figure out whether it needs to be executed at a remote // HStoreSite or whether we can execute it at one of our local PartitionExecutors. for (WorkFragment.Builder fragmentBuilder : fragmentBuilders) { int partition = fragmentBuilder.getPartitionId(); is_localSite = hstore_site.isLocalPartition(partition); is_localPartition = (partition == this.partitionId); all_local = all_local && is_localPartition; // If this is the last WorkFragment that we're going to send to this partition for // this batch, then we will want to check whether we know that this is the last // time this txn will ever need to go to that txn. If so, then we'll want to if (notify != null && notify.donePartitions.contains(partition) && tmp_fragmentsPerPartition.dec(partition) == 0) { if (debug.val) LOG.debug(String.format("%s - Setting last fragment flag in %s for partition %d", ts, WorkFragment.class.getSimpleName(), partition)); fragmentBuilder.setLastFragment(true); } if (first == false || this.depTracker.addWorkFragment(ts, fragmentBuilder, batchParams)) { total++; // At this point we know that all the WorkFragment has been registered // in the LocalTransaction, so then it's safe for us to look to see // whether we already have a prefetched result that we need // if (prefetch && is_localPartition == false) { // boolean skip_queue = true; // for (int i = 0, cnt = fragmentBuilder.getFragmentIdCount(); i < cnt; i++) { // int fragId = fragmentBuilder.getFragmentId(i); // int paramIdx = fragmentBuilder.getParamIndex(i); // // VoltTable vt = this.queryCache.getResult(ts.getTransactionId(), // fragId, // partition, // parameters[paramIdx]); // if (vt != null) { // if (trace.val) // LOG.trace(String.format("%s - Storing cached result from partition %d for fragment %d", // ts, partition, fragId)); // this.depTracker.addResult(ts, partition, fragmentBuilder.getOutputDepId(i), vt); // } else { // skip_queue = false; // } // } // FOR // // If we were able to get cached results for all of the fragmentIds in // // this WorkFragment, then there is no need for us to send the message // // So we'll just skip queuing it up! How nice! // if (skip_queue) { // if (debug.val) // LOG.debug(String.format("%s - Using prefetch result for all fragments from partition %d", // ts, partition)); // num_skipped++; // continue; // } // } // Otherwise add it to our list of WorkFragments that we want // queue up right now if (is_localPartition) { is_localReadOnly = (is_localReadOnly && fragmentBuilder.getReadOnly()); this.tmp_localWorkFragmentBuilders.add(fragmentBuilder); num_localPartition++; } else if (is_localSite) { this.tmp_localSiteFragmentBuilders.add(fragmentBuilder); num_localSite++; } else { this.tmp_remoteFragmentBuilders.add(fragmentBuilder); num_remote++; } } } // FOR assert(total == (num_remote + num_localSite + num_localPartition + num_skipped)) : String.format("Total:%d / Remote:%d / LocalSite:%d / LocalPartition:%d / Skipped:%d", total, num_remote, num_localSite, num_localPartition, num_skipped); // We have to tell the txn to start the round before we send off the // WorkFragments for execution, since they might start executing locally! if (first) { ts.startRound(this.partitionId); latch = this.depTracker.getDependencyLatch(ts); } // Now request the fragments that aren't local // We want to push these out as soon as possible if (num_remote > 0) { // We only need to serialize the ParameterSets once if (serializedParams == false) { if (needs_profiling) ts.profiler.startSerialization(); tmp_serializedParams.clear(); for (int i = 0; i < batchParams.length; i++) { if (batchParams[i] == null) { tmp_serializedParams.add(ByteString.EMPTY); } else { this.fs.clear(); try { batchParams[i].writeExternal(this.fs); ByteString bs = ByteString.copyFrom(this.fs.getBBContainer().b); tmp_serializedParams.add(bs); } catch (Exception ex) { String msg = "Failed to serialize ParameterSet " + i + " for " + ts; throw new ServerFaultException(msg, ex, ts.getTransactionId()); } } } // FOR if (needs_profiling) ts.profiler.stopSerialization(); } if (trace.val) LOG.trace(String.format("%s - Requesting %d %s to be executed on remote partitions " + "[doneNotifications=%s]", ts, WorkFragment.class.getSimpleName(), num_remote, notify!=null)); this.requestWork(ts, tmp_remoteFragmentBuilders, tmp_serializedParams, notify); if (needs_profiling) ts.profiler.markRemoteQuery(); } // Then dispatch the task that are needed at the same HStoreSite but // at a different partition than this one if (num_localSite > 0) { if (trace.val) LOG.trace(String.format("%s - Executing %d WorkFragments on local site's partitions", ts, num_localSite)); for (WorkFragment.Builder builder : this.tmp_localSiteFragmentBuilders) { PartitionExecutor other = hstore_site.getPartitionExecutor(builder.getPartitionId()); other.queueWork(ts, builder.build()); } // FOR if (needs_profiling) ts.profiler.markRemoteQuery(); } // Then execute all of the tasks need to access the partitions at this HStoreSite // We'll dispatch the remote-partition-local-site fragments first because they're going // to need to get queued up by at the other PartitionExecutors if (num_localPartition > 0) { if (trace.val) LOG.trace(String.format("%s - Executing %d WorkFragments on local partition", ts, num_localPartition)); for (WorkFragment.Builder fragmentBuilder : this.tmp_localWorkFragmentBuilders) { this.processWorkFragment(ts, fragmentBuilder.build(), batchParams); } // FOR } } if (trace.val) LOG.trace(String.format("%s - Dispatched %d WorkFragments " + "[remoteSite=%d, localSite=%d, localPartition=%d]", ts, total, num_remote, num_localSite, num_localPartition)); first = false; } // WHILE this.fs.getBBContainer().discard(); if (trace.val) LOG.trace(String.format("%s - BREAK OUT [first=%s, stillHasWorkFragments=%s, latch=%s]", ts, first, this.depTracker.stillHasWorkFragments(ts), latch)); // assert(ts.stillHasWorkFragments() == false) : // String.format("Trying to block %s before all of its WorkFragments have been dispatched!\n%s\n%s", // ts, // StringUtil.join("** ", "\n", tempDebug), // this.getVoltProcedure(ts.getProcedureName()).getLastBatchPlan()); // Now that we know all of our WorkFragments have been dispatched, we can then // wait for all of the results to come back in. if (latch == null) latch = this.depTracker.getDependencyLatch(ts); assert(latch != null) : String.format("Unexpected null dependency latch for " + ts); if (latch.getCount() > 0) { if (debug.val) { LOG.debug(String.format("%s - All blocked messages dispatched. Waiting for %d dependencies", ts, latch.getCount())); if (trace.val) LOG.trace(ts.toString()); } boolean timeout = false; long startTime = EstTime.currentTimeMillis(); if (needs_profiling) ts.profiler.startExecDtxnWork(); if (hstore_conf.site.exec_profiling) this.profiler.sp1_time.start(); try { while (latch.getCount() > 0 && ts.hasPendingError() == false) { if (this.utilityWork() == false) { timeout = latch.await(WORK_QUEUE_POLL_TIME, TimeUnit.MILLISECONDS); if (timeout == false) break; } if ((EstTime.currentTimeMillis() - startTime) > hstore_conf.site.exec_response_timeout) { timeout = true; break; } } // WHILE } catch (InterruptedException ex) { if (this.hstore_site.isShuttingDown() == false) { LOG.error(String.format("%s - We were interrupted while waiting for results", ts), ex); } timeout = true; } catch (Throwable ex) { String msg = String.format("Fatal error for %s while waiting for results", ts); throw new ServerFaultException(msg, ex); } finally { if (needs_profiling) ts.profiler.stopExecDtxnWork(); if (hstore_conf.site.exec_profiling) this.profiler.sp1_time.stopIfStarted(); } if (timeout && this.isShuttingDown() == false) { LOG.warn(String.format("Still waiting for responses for %s after %d ms [latch=%d]\n%s", ts, hstore_conf.site.exec_response_timeout, latch.getCount(), ts.debug())); LOG.warn("Procedure Parameters:\n" + ts.getProcedureParameters()); hstore_conf.site.exec_profiling = true; LOG.warn(hstore_site.statusSnapshot()); String msg = "The query responses for " + ts + " never arrived!"; throw new ServerFaultException(msg, ts.getTransactionId()); } } // Update done partitions if (notify != null && notify.donePartitions.isEmpty() == false) { if (debug.val) LOG.debug(String.format("%s - Marking new done partitions %s", ts, notify.donePartitions)); ts.getDonePartitions().addAll(notify.donePartitions); } // IMPORTANT: Check whether the fragments failed somewhere and we got a response with an error // We will rethrow this so that it pops the stack all the way back to VoltProcedure.call() // where we can generate a message to the client if (ts.hasPendingError()) { if (debug.val) LOG.warn(String.format("%s was hit with a %s", ts, ts.getPendingError().getClass().getSimpleName())); throw ts.getPendingError(); } // IMPORTANT: Don't try to check whether we got back the right number of tables because the batch // may have hit an error and we didn't execute all of them. VoltTable results[] = null; try { results = this.depTracker.getResults(ts); } catch (AssertionError ex) { LOG.error("Failed to get final results for batch\n" + ts.debug()); throw ex; } ts.finishRound(this.partitionId); if (debug.val) { if (trace.val) LOG.trace(ts + " is now running and looking for love in all the wrong places..."); LOG.debug(String.format("%s - Returning back %d tables to VoltProcedure", ts, results.length)); } return (results); } // --------------------------------------------------------------- // COMMIT + ABORT METHODS // --------------------------------------------------------------- /** * Queue a speculatively executed transaction to send its ClientResponseImpl message */ private void blockClientResponse(LocalTransaction ts, ClientResponseImpl cresponse) { assert(ts.isPredictSinglePartition() == true) : String.format("Specutatively executed multi-partition %s [mode=%s, status=%s]", ts, this.currentExecMode, cresponse.getStatus()); assert(ts.isSpeculative() == true) : String.format("Blocking ClientResponse for non-specutative %s [mode=%s, status=%s]", ts, this.currentExecMode, cresponse.getStatus()); assert(cresponse.getStatus() != Status.ABORT_MISPREDICT) : String.format("Trying to block ClientResponse for mispredicted %s [mode=%s, status=%s]", ts, this.currentExecMode, cresponse.getStatus()); assert(this.currentExecMode != ExecutionMode.COMMIT_ALL) : String.format("Blocking ClientResponse for %s when in non-specutative mode [mode=%s, status=%s]", ts, this.currentExecMode, cresponse.getStatus()); this.specExecBlocked.push(Pair.of(ts, cresponse)); this.specExecModified = this.specExecModified && ts.isExecReadOnly(this.partitionId); if (debug.val) LOG.debug(String.format("%s - Blocking %s ClientResponse [partitions=%s, blockQueue=%d]", ts, cresponse.getStatus(), ts.getTouchedPartitions().values(), this.specExecBlocked.size())); } /** * For the given transaction's ClientResponse, figure out whether we can send it back to the client * right now or whether we need to initiate two-phase commit. * @param ts * @param cresponse */ protected void processClientResponse(LocalTransaction ts, ClientResponseImpl cresponse) { // IMPORTANT: If we executed this locally and only touched our partition, then we need to commit/abort right here // 2010-11-14: The reason why we can do this is because we will just ignore the commit // message when it shows from the Dtxn.Coordinator. We should probably double check with Evan on this... Status status = cresponse.getStatus(); if (debug.val) { LOG.debug(String.format("%s - Processing ClientResponse at partition %d " + "[status=%s, singlePartition=%s, local=%s, clientHandle=%d]", ts, this.partitionId, status, ts.isPredictSinglePartition(), ts.isExecLocal(this.partitionId), cresponse.getClientHandle())); if (trace.val) { LOG.trace(ts + " Touched Partitions: " + ts.getTouchedPartitions().values()); if (ts.isPredictSinglePartition() == false) LOG.trace(ts + " Done Partitions: " + ts.getDonePartitions()); } } // ------------------------------- // ALL: Transactions that need to be internally restarted // ------------------------------- if (status == Status.ABORT_MISPREDICT || status == Status.ABORT_SPECULATIVE || status == Status.ABORT_EVICTEDACCESS) { // If the txn was mispredicted, then we will pass the information over to the // HStoreSite so that it can re-execute the transaction. We want to do this // first so that the txn gets re-executed as soon as possible... if (debug.val) LOG.debug(String.format("%s - Restarting because transaction was hit with %s", ts, (ts.getPendingError() != null ? ts.getPendingError().getClass().getSimpleName() : ""))); // We don't want to delete the transaction here because whoever is going to requeue it for // us will need to know what partitions that the transaction touched when it executed before if (ts.isPredictSinglePartition()) { this.finishTransaction(ts, status); this.hstore_site.transactionRequeue(ts, status); } // Send a message all the partitions involved that the party is over // and that they need to abort the transaction. We don't actually care when we get the // results back because we'll start working on new txns right away. // Note that when we call transactionFinish() right here this thread will then go on // to invoke HStoreSite.transactionFinish() for us. That means when it returns we will // have successfully aborted the txn at least at all of the local partitions at this site. else { if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.startPostFinish(); LocalFinishCallback finish_callback = ts.getFinishCallback(); finish_callback.init(ts, status); finish_callback.markForRequeue(); if (hstore_conf.site.exec_profiling) this.profiler.network_time.start(); this.hstore_coordinator.transactionFinish(ts, status, finish_callback); if (hstore_conf.site.exec_profiling) this.profiler.network_time.stopIfStarted(); } } // ------------------------------- // ALL: Single-Partition Transactions // ------------------------------- else if (ts.isPredictSinglePartition()) { // Commit or abort the transaction only if we haven't done it already // This can happen when we commit speculative txns out of order if (ts.isMarkedFinished(this.partitionId) == false) { this.finishTransaction(ts, status); } // We have to mark it as loggable to prevent the response // from getting sent back to the client if (hstore_conf.site.commandlog_enable) ts.markLogEnabled(); if (hstore_conf.site.exec_profiling) this.profiler.network_time.start(); this.hstore_site.responseSend(ts, cresponse); if (hstore_conf.site.exec_profiling) this.profiler.network_time.stopIfStarted(); this.hstore_site.queueDeleteTransaction(ts.getTransactionId(), status); } // ------------------------------- // COMMIT: Distributed Transaction // ------------------------------- else if (status == Status.OK) { // We need to set the new ExecutionMode before we invoke transactionPrepare // because the LocalTransaction handle might get cleaned up immediately ExecutionMode newMode = null; if (hstore_conf.site.specexec_enable) { newMode = (ts.isExecReadOnly(this.partitionId) ? ExecutionMode.COMMIT_READONLY : ExecutionMode.COMMIT_NONE); } else { newMode = ExecutionMode.DISABLED; } this.setExecutionMode(ts, newMode); // We have to send a prepare message to all of our remote HStoreSites // We want to make sure that we don't go back to ones that we've already told PartitionSet donePartitions = ts.getDonePartitions(); PartitionSet notifyPartitions = new PartitionSet(); for (int partition : ts.getPredictTouchedPartitions().values()) { if (donePartitions.contains(partition) == false) { notifyPartitions.add(partition); } } // FOR if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.startPostPrepare(); ts.setClientResponse(cresponse); if (hstore_conf.site.exec_profiling) { this.profiler.network_time.start(); this.profiler.sp3_local_time.start(); } LocalPrepareCallback callback = ts.getPrepareCallback(); callback.init(ts, notifyPartitions); this.hstore_coordinator.transactionPrepare(ts, callback, notifyPartitions); if (hstore_conf.site.exec_profiling) this.profiler.network_time.stopIfStarted(); } // ------------------------------- // ABORT: Distributed Transaction // ------------------------------- else { // Send back the result to the client right now, since there's no way // that we're magically going to be able to recover this and get them a result // This has to come before the network messages above because this will clean-up the // LocalTransaction state information this.hstore_site.responseSend(ts, cresponse); // Send a message all the partitions involved that the party is over // and that they need to abort the transaction. We don't actually care when we get the // results back because we'll start working on new txns right away. // Note that when we call transactionFinish() right here this thread will then go on // to invoke HStoreSite.transactionFinish() for us. That means when it returns we will // have successfully aborted the txn at least at all of the local partitions at this site. if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.startPostFinish(); LocalFinishCallback callback = ts.getFinishCallback(); callback.init(ts, status); if (hstore_conf.site.exec_profiling) this.profiler.network_time.start(); try { this.hstore_coordinator.transactionFinish(ts, status, callback); } finally { if (hstore_conf.site.exec_profiling) this.profiler.network_time.stopIfStarted(); } } } /** * Enable speculative execution mode for this partition. The given transaction is * the one that we will need to wait to finish before we can release the ClientResponses * for any speculatively executed transactions. * @param txn_id * @return true if speculative execution was enabled at this partition */ private Status prepareTransaction(AbstractTransaction ts) { assert(ts != null) : "Unexpected null transaction handle at partition " + this.partitionId; assert(ts.isInitialized()) : String.format("Trying to prepare uninitialized transaction %s at partition %d", ts, this.partitionId); assert(ts.isMarkedFinished(this.partitionId) == false) : String.format("Trying to prepare %s again after it was already finished at partition %d", ts, this.partitionId); Status status = Status.OK; // Skip if we've already invoked prepared for this txn at this partition if (ts.isMarkedPrepared(this.partitionId) == false) { if (debug.val) LOG.debug(String.format("%s - Preparing to commit txn at partition %d [specBlocked=%d]", ts, this.partitionId, this.specExecBlocked.size())); ExecutionMode newMode = ExecutionMode.COMMIT_NONE; if (hstore_conf.site.exec_profiling && this.partitionId != ts.getBasePartition() && ts.needsFinish(this.partitionId)) { profiler.sp3_remote_time.start(); } if (hstore_conf.site.specexec_enable) { // Check to see if there were any conflicts with the dtxn and any of its speculative // txns at this partition. If there were, then we know that we can't commit the txn here. LocalTransaction spec_ts; for (Pair<LocalTransaction, ClientResponseImpl> pair : this.specExecBlocked) { spec_ts = pair.getFirst(); if (debug.val) LOG.debug(String.format("%s - Checking for conflicts with speculative %s at partition %d [%s]", ts, spec_ts, this.partitionId, this.specExecChecker.getClass().getSimpleName())); if (this.specExecChecker.hasConflictAfter(ts, spec_ts, this.partitionId)) { if (debug.val) LOG.debug(String.format("%s - Conflict found with speculative txn %s at partition %d", ts, spec_ts, this.partitionId)); status = Status.ABORT_RESTART; break; } } // FOR // Check whether the txn that we're waiting for is read-only. // If it is, then that means all read-only transactions can commit right away if (status == Status.OK && ts.isExecReadOnly(this.partitionId)) { if (debug.val) LOG.debug(String.format("%s - Txn is read-only at partition %d [readOnly=%s]", ts, this.partitionId, ts.isExecReadOnly(this.partitionId))); newMode = ExecutionMode.COMMIT_READONLY; } } if (this.currentDtxn != null) this.setExecutionMode(ts, newMode); } // It's ok if they try to prepare the txn twice. That might just mean that they never // got the acknowledgement back in time if they tried to send an early commit message. else if (debug.val) { LOG.debug(String.format("%s - Already marked 2PC:PREPARE at partition %d", ts, this.partitionId)); } // IMPORTANT // When we do an early 2PC-PREPARE, we won't have this callback ready // because we don't know what callback to use to send the acknowledgements // back over the network PartitionCountingCallback<AbstractTransaction> callback = ts.getPrepareCallback(); if (status == Status.OK) { if (callback.isInitialized()) { try { callback.run(this.partitionId); } catch (Throwable ex) { LOG.warn("Unexpected error for " + ts, ex); } } // But we will always mark ourselves as prepared at this partition ts.markPrepared(this.partitionId); } else { if (debug.val) LOG.debug(String.format("%s - Aborting txn from partition %d [%s]", ts, this.partitionId, status)); callback.abort(this.partitionId, status); } return (status); } /** * Internal call to abort/commit the transaction down in the execution engine * @param ts * @param commit */ private void finishTransaction(AbstractTransaction ts, Status status) { assert(ts != null) : "Unexpected null transaction handle at partition " + this.partitionId; assert(ts.isInitialized()) : String.format("Trying to commit uninitialized transaction %s at partition %d", ts, this.partitionId); assert(ts.isMarkedFinished(this.partitionId) == false) : String.format("Trying to commit %s twice at partition %d", ts, this.partitionId); // This can be null if they haven't submitted anything boolean commit = (status == Status.OK); long undoToken = (commit ? ts.getLastUndoToken(this.partitionId) : ts.getFirstUndoToken(this.partitionId)); // Only commit/abort this transaction if: // (2) We have the last undo token used by this transaction // (3) The transaction was executed with undo buffers // (4) The transaction actually submitted work to the EE // (5) The transaction modified data at this partition if (ts.needsFinish(this.partitionId) && undoToken != HStoreConstants.NULL_UNDO_LOGGING_TOKEN) { if (trace.val) LOG.trace(String.format("%s - Invoking EE to finish work for txn [%s / speculative=%s]", ts, status, ts.isSpeculative())); this.finishWorkEE(ts, undoToken, commit); } // We always need to do the following things regardless if we hit up the EE or not if (commit) this.lastCommittedTxnId = ts.getTransactionId(); if (trace.val) LOG.trace(String.format("%s - Telling queue manager that txn is finished at partition %d", ts, this.partitionId)); this.queueManager.lockQueueFinished(ts, status, this.partitionId); if (debug.val) LOG.debug(String.format("%s - Successfully %sed transaction at partition %d", ts, (commit ? "committ" : "abort"), this.partitionId)); ts.markFinished(this.partitionId); } /** * The real method that actually reaches down into the EE and commits/undos the changes * for the given token. * Unless you know what you're doing, you probably want to be calling finishTransaction() * instead of calling this directly. * @param ts * @param undoToken * @param commit */ private void finishWorkEE(AbstractTransaction ts, long undoToken, boolean commit) { assert(ts.isMarkedFinished(this.partitionId) == false) : String.format("Trying to commit %s twice at partition %d", ts, this.partitionId); // If the txn is completely read-only and they didn't use undo-logging, then // there is nothing that we need to do, except to check to make sure we aren't // trying to abort this txn if (undoToken == HStoreConstants.DISABLE_UNDO_LOGGING_TOKEN) { // SANITY CHECK: Make sure that they're not trying to undo a transaction that // modified the database but did not use undo logging if (ts.isExecReadOnly(this.partitionId) == false && commit == false) { String msg = String.format("TRYING TO ABORT TRANSACTION ON PARTITION %d WITHOUT UNDO LOGGING [undoToken=%d]", this.partitionId, undoToken); LOG.fatal(msg + "\n" + ts.debug()); this.crash(new ServerFaultException(msg, ts.getTransactionId())); } if (debug.val) LOG.debug(String.format("%s - undoToken == DISABLE_UNDO_LOGGING_TOKEN", ts)); } // COMMIT / ABORT else { boolean needs_profiling = false; if (hstore_conf.site.txn_profiling && ts.isExecLocal(this.partitionId) && ((LocalTransaction)ts).profiler != null) { needs_profiling = true; ((LocalTransaction)ts).profiler.startPostEE(); } assert(this.lastCommittedUndoToken != undoToken) : String.format("Trying to %s undoToken %d for %s twice at partition %d", (commit ? "COMMIT" : "ABORT"), undoToken, ts, this.partitionId); // COMMIT! if (commit) { if (debug.val) { LOG.debug(String.format("%s - COMMITING txn on partition %d with undoToken %d " + "[lastTxnId=%d, lastUndoToken=%d, dtxn=%s]%s", ts, this.partitionId, undoToken, this.lastCommittedTxnId, this.lastCommittedUndoToken, this.currentDtxn, (ts instanceof LocalTransaction ? " - " + ((LocalTransaction)ts).getSpeculationType() : ""))); if (this.specExecBlocked.isEmpty() == false && ts.isPredictSinglePartition() == false) { LOG.debug(String.format("%s - # of Speculatively Executed Txns: %d ", ts, this.specExecBlocked.size())); } } assert(this.lastCommittedUndoToken < undoToken) : String.format("Trying to commit undoToken %d for %s but it is less than the " + "last committed undoToken %d at partition %d\n" + "Last Committed Txn: %d", undoToken, ts, this.lastCommittedUndoToken, this.partitionId, this.lastCommittedTxnId); this.ee.releaseUndoToken(undoToken); this.lastCommittedUndoToken = undoToken; } // ABORT! else { // Evan says that txns will be aborted LIFO. This means the first txn that // we get in abortWork() will have a the greatest undoToken, which means that // it will automagically rollback all other outstanding txns. // I'm lazy/tired, so for now I'll just rollback everything I get, but in theory // we should be able to check whether our undoToken has already been rolled back if (debug.val) { LOG.debug(String.format("%s - ABORTING txn on partition %d with undoToken %d " + "[lastTxnId=%d, lastUndoToken=%d, dtxn=%s]%s", ts, this.partitionId, undoToken, this.lastCommittedTxnId, this.lastCommittedUndoToken, this.currentDtxn, (ts instanceof LocalTransaction ? " - " + ((LocalTransaction)ts).getSpeculationType() : ""))); if (this.specExecBlocked.isEmpty() == false && ts.isPredictSinglePartition() == false) { LOG.debug(String.format("%s - # of Speculatively Executed Txns: %d ", ts, this.specExecBlocked.size())); } } assert(this.lastCommittedUndoToken < undoToken) : String.format("Trying to abort undoToken %d for %s but it is less than the " + "last committed undoToken %d at partition %d " + "[lastTxnId=%d, lastUndoToken=%d, dtxn=%s]%s", undoToken, ts, this.lastCommittedUndoToken, this.partitionId, this.lastCommittedTxnId, this.lastCommittedUndoToken, this.currentDtxn, (ts instanceof LocalTransaction ? " - " + ((LocalTransaction)ts).getSpeculationType() : "")); this.ee.undoUndoToken(undoToken); } if (needs_profiling) ((LocalTransaction)ts).profiler.stopPostEE(); } } /** * Somebody told us that our partition needs to abort/commit the given transaction id. * This method should only be used for distributed transactions, because * it will do some extra work for speculative execution * @param ts - The transaction to finish up. * @param status - The final status of the transaction */ private void finishDistributedTransaction(final AbstractTransaction ts, final Status status) { if (debug.val) LOG.debug(String.format("%s - Processing finish request at partition %d " + "[status=%s, readOnly=%s]", ts, this.partitionId, status, ts.isExecReadOnly(this.partitionId))); if (this.currentDtxn == ts) { // 2012-11-22 -- Yes, today is Thanksgiving and I'm working on my database. // That's just grad student life I guess. Anyway, if you're reading this then // you know that this is an important part of the system. We have a dtxn that // we have been told is completely finished and now we need to either commit // or abort any changes that it may have made at this partition. The tricky thing // is that if we have speculative execution enabled, then we need to make sure // that we process any transactions that were executed while the dtxn was running // in the right order to ensure that we maintain serializability. // Here is the basic logic of what's about to happen: // // (1) If the dtxn is commiting, then we just need to commit the the last txn that // was executed (since this will have the largest undo token). // The EE will automatically commit all undo tokens less than that. // (2) If the dtxn is aborting, then we can commit any speculative txn that was // executed before the dtxn's first non-readonly undo token. // // Note that none of the speculative txns in the blocked queue will need to be // aborted at this point, because we will have rolled back their changes immediately // when they aborted, so that our dtxn doesn't read dirty data. if (this.specExecBlocked.isEmpty() == false) { // First thing we need to do is get the latch that will be set by any transaction // that was in the middle of being executed when we were called if (debug.val) LOG.debug(String.format("%s - Checking %d blocked speculative transactions at " + "partition %d [currentMode=%s]", ts, this.specExecBlocked.size(), this.partitionId, this.currentExecMode)); LocalTransaction spec_ts = null; ClientResponseImpl spec_cr = null; // ------------------------------- // DTXN NON-READ-ONLY ABORT // If the dtxn did not modify this partition, then everthing can commit // Otherwise, we want to commit anything that was executed before the dtxn started // ------------------------------- if (status != Status.OK && ts.isExecReadOnly(this.partitionId) == false) { // We need to get the first undo tokens for our distributed transaction long dtxnUndoToken = ts.getFirstUndoToken(this.partitionId); if (debug.val) LOG.debug(String.format("%s - Looking for speculative txns to commit before we rollback undoToken %d", ts, dtxnUndoToken)); // Queue of speculative txns that need to be committed. final Queue<Pair<LocalTransaction, ClientResponseImpl>> txnsToCommit = new LinkedList<Pair<LocalTransaction,ClientResponseImpl>>(); // Queue of speculative txns that need to be aborted + restarted final Queue<Pair<LocalTransaction, ClientResponseImpl>> txnsToRestart = new LinkedList<Pair<LocalTransaction,ClientResponseImpl>>(); long spec_token; long max_token = HStoreConstants.NULL_UNDO_LOGGING_TOKEN; LocalTransaction max_ts = null; for (Pair<LocalTransaction, ClientResponseImpl> pair : this.specExecBlocked) { boolean shouldCommit = false; spec_ts = pair.getFirst(); spec_token = spec_ts.getFirstUndoToken(this.partitionId); if (debug.val) LOG.debug(String.format("Speculative Txn %s [undoToken=%d, %s]", spec_ts, spec_token, spec_ts.getSpeculationType())); // Speculative txns should never be executed without an undo token assert(spec_token != HStoreConstants.DISABLE_UNDO_LOGGING_TOKEN); assert(spec_ts.isSpeculative()) : spec_ts + " isn't marked as speculative!"; // If the speculative undoToken is null, then this txn didn't execute // any queries. That means we can always commit it if (spec_token == HStoreConstants.NULL_UNDO_LOGGING_TOKEN) { if (debug.val) LOG.debug(String.format("Speculative Txn %s has a null undoToken at partition %d", spec_ts, this.partitionId)); shouldCommit = true; } // Otherwise, look to see if this txn was speculatively executed before the // first undo token of the distributed txn. That means we know that this guy // didn't read any modifications made by the dtxn. else if (spec_token < dtxnUndoToken) { if (debug.val) LOG.debug(String.format("Speculative Txn %s has an undoToken less than the dtxn %s " + "at partition %d [%d < %d]", spec_ts, ts, this.partitionId, spec_token, dtxnUndoToken)); shouldCommit = true; } // Ok so at this point we know that our spec txn came *after* the distributed txn // started. So we need to use our checker to see whether there is a conflict else if (this.specExecChecker.hasConflictAfter(ts, spec_ts, this.partitionId) == false) { if (debug.val) LOG.debug(String.format("Speculative Txn %s does not conflict with dtxn %s at partition %d", spec_ts, ts, this.partitionId)); shouldCommit = true; } if (shouldCommit) { txnsToCommit.add(pair); if (spec_token != HStoreConstants.NULL_UNDO_LOGGING_TOKEN && spec_token > max_token) { max_token = spec_token; max_ts = spec_ts; } } else { txnsToRestart.add(pair); } } // FOR if (debug.val) LOG.debug(String.format("%s - Found %d speculative txns at partition %d that need to be " + "committed *before* we abort this txn", ts, txnsToCommit.size(), this.partitionId)); // (1) Commit the greatest token that we've seen. This means that // all our other txns can be safely processed without needing // to go down in the EE if (max_token != HStoreConstants.NULL_UNDO_LOGGING_TOKEN) { assert(max_ts != null); this.finishWorkEE(max_ts, max_token, true); } // (2) Process all the txns that need to be committed Pair<LocalTransaction, ClientResponseImpl> pair = null; while ((pair = txnsToCommit.poll()) != null) { spec_ts = pair.getFirst(); spec_cr = pair.getSecond(); spec_ts.markFinished(this.partitionId); try { if (debug.val) LOG.debug(String.format("%s - Releasing blocked ClientResponse for %s [status=%s]", ts, spec_ts, spec_cr.getStatus())); this.processClientResponse(spec_ts, spec_cr); } catch (Throwable ex) { String msg = "Failed to complete queued response for " + spec_ts; throw new ServerFaultException(msg, ex, ts.getTransactionId()); } } // FOR // (3) Abort the distributed txn this.finishTransaction(ts, status); // (4) Restart all the other txns while ((pair = txnsToRestart.poll()) != null) { spec_ts = pair.getFirst(); spec_cr = pair.getSecond(); MispredictionException error = new MispredictionException(spec_ts.getTransactionId(), spec_ts.getTouchedPartitions()); spec_ts.setPendingError(error, false); spec_cr.setStatus(Status.ABORT_SPECULATIVE); this.processClientResponse(spec_ts, spec_cr); } // FOR } // ------------------------------- // DTXN READ-ONLY ABORT or DTXN COMMIT // ------------------------------- else { // **IMPORTANT** // If the dtxn needs to commit, then all we need to do is get the // last undoToken that we've generated (since we know that it had to // have been used either by our distributed txn or for one of our // speculative txns). // // If the read-only dtxn needs to abort, then there's nothing we need to // do, because it didn't make any changes. That means we can just // commit the last speculatively executed transaction // // Once we have this token, we can just make a direct call to the EE // to commit any changes that came before it. Note that we are using our // special 'finishWorkEE' method that does not require us to provide // the transaction that we're committing. long undoToken = this.lastUndoToken; if (debug.val) LOG.debug(String.format("%s - Last undoToken at partition %d => %d", ts, this.partitionId, undoToken)); // Bombs away! if (undoToken != this.lastCommittedUndoToken) { this.finishWorkEE(ts, undoToken, true); // IMPORTANT: Make sure that we remove the dtxn from the lock queue! // This is normally done in finishTransaction() but because we're trying // to be clever and invoke the EE directly, we have to make sure that // we call it ourselves. this.queueManager.lockQueueFinished(ts, status, this.partitionId); } // Make sure that we mark the dtxn as finished so that we don't // try to do anything with it later on. ts.markFinished(this.partitionId); // Now make sure that all of the speculative txns are processed without // committing (since we just committed any change that they could have made // up above). Pair<LocalTransaction, ClientResponseImpl> pair = null; while ((pair = this.specExecBlocked.pollFirst()) != null) { spec_ts = pair.getFirst(); spec_cr = pair.getSecond(); spec_ts.markFinished(this.partitionId); try { if (trace.val) LOG.trace(String.format("%s - Releasing blocked ClientResponse for %s [status=%s]", ts, spec_ts, spec_cr.getStatus())); this.processClientResponse(spec_ts, spec_cr); } catch (Throwable ex) { String msg = "Failed to complete queued response for " + spec_ts; throw new ServerFaultException(msg, ex, ts.getTransactionId()); } } // WHILE } this.specExecBlocked.clear(); this.specExecModified = false; if (trace.val) LOG.trace(String.format("Finished processing all queued speculative txns for dtxn %s", ts)); } // ------------------------------- // NO SPECULATIVE TXNS // ------------------------------- else { // There are no speculative txns waiting for this dtxn, // so we can just commit it right away if (debug.val) LOG.debug(String.format("%s - No speculative txns at partition %d. Just %s txn by itself", ts, this.partitionId, (status == Status.OK ? "commiting" : "aborting"))); this.finishTransaction(ts, status); } // Clear our cached query results that are specific for this transaction // this.queryCache.purgeTransaction(ts.getTransactionId()); // TODO: Remove anything in our queue for this txn // if (ts.hasQueuedWork(this.partitionId)) { // } // Check whether this is the response that the speculatively executed txns have been waiting for // We could have turned off speculative execution mode beforehand if (debug.val) LOG.debug(String.format("%s - Attempting to unmark as the current DTXN at partition %d and " + "setting execution mode to %s", ts, this.partitionId, ExecutionMode.COMMIT_ALL)); try { // Resetting the current_dtxn variable has to come *before* we change the execution mode this.resetCurrentDtxn(); this.setExecutionMode(ts, ExecutionMode.COMMIT_ALL); // Release blocked transactions this.releaseBlockedTransactions(ts); } catch (Throwable ex) { String msg = String.format("Failed to finish %s at partition %d", ts, this.partitionId); throw new ServerFaultException(msg, ex, ts.getTransactionId()); } if (hstore_conf.site.exec_profiling) { this.profiler.sp3_local_time.stopIfStarted(); this.profiler.sp3_remote_time.stopIfStarted(); } } // We were told told to finish a dtxn that is not the current one // at this partition. That's ok as long as it's aborting and not trying // to commit. else { assert(status != Status.OK) : String.format("Trying to commit %s at partition %d but the current dtxn is %s", ts, this.partitionId, this.currentDtxn); this.queueManager.lockQueueFinished(ts, status, this.partitionId); } // ------------------------------- // FINISH CALLBACKS // ------------------------------- // MapReduceTransaction if (ts instanceof MapReduceTransaction) { PartitionCountingCallback<AbstractTransaction> callback = ((MapReduceTransaction)ts).getCleanupCallback(); // We don't want to invoke this callback at the basePartition's site // because we don't want the parent txn to actually get deleted. if (this.partitionId == ts.getBasePartition()) { if (debug.val) LOG.debug(String.format("%s - Notifying %s that the txn is finished at partition %d", ts, callback.getClass().getSimpleName(), this.partitionId)); callback.run(this.partitionId); } } else { PartitionCountingCallback<AbstractTransaction> callback = ts.getFinishCallback(); if (debug.val) LOG.debug(String.format("%s - Notifying %s that the txn is finished at partition %d", ts, callback.getClass().getSimpleName(), this.partitionId)); callback.run(this.partitionId); } } private void blockTransaction(InternalTxnMessage work) { if (debug.val) LOG.debug(String.format("%s - Adding %s work to blocked queue", work.getTransaction(), work.getClass().getSimpleName())); this.currentBlockedTxns.add(work); } private void blockTransaction(LocalTransaction ts) { this.blockTransaction(new StartTxnMessage(ts)); } /** * Release all the transactions that are currently in this partition's blocked queue * into the work queue. * @param ts */ private void releaseBlockedTransactions(AbstractTransaction ts) { if (this.currentBlockedTxns.isEmpty() == false) { if (debug.val) LOG.debug(String.format("Attempting to release %d blocked transactions at partition %d because of %s", this.currentBlockedTxns.size(), this.partitionId, ts)); this.work_queue.addAll(this.currentBlockedTxns); int released = this.currentBlockedTxns.size(); this.currentBlockedTxns.clear(); if (debug.val) LOG.debug(String.format("Released %d blocked transactions at partition %d because of %s", released, this.partitionId, ts)); } assert(this.currentBlockedTxns.isEmpty()); } // --------------------------------------------------------------- // SNAPSHOT METHODS // --------------------------------------------------------------- /** * Do snapshot work exclusively until there is no more. Also blocks * until the syncing and closing of snapshot data targets has completed. */ public void initiateSnapshots(Deque<SnapshotTableTask> tasks) { m_snapshotter.initiateSnapshots(ee, tasks); } public Collection<Exception> completeSnapshotWork() throws InterruptedException { return m_snapshotter.completeSnapshotWork(ee); } // --------------------------------------------------------------- // SHUTDOWN METHODS // --------------------------------------------------------------- /** * Cause this PartitionExecutor to make the entire HStore cluster shutdown * This won't return! */ public synchronized void crash(Throwable ex) { String msg = String.format("PartitionExecutor for Partition #%d is crashing", this.partitionId); if (ex == null) LOG.warn(msg); else LOG.warn(msg, ex); assert(this.hstore_coordinator != null); this.hstore_coordinator.shutdownClusterBlocking(ex); } @Override public boolean isShuttingDown() { return (this.hstore_site.isShuttingDown()); // shutdown_state == State.PREPARE_SHUTDOWN || this.shutdown_state == State.SHUTDOWN); } @Override public void prepareShutdown(boolean error) { this.shutdown_state = ShutdownState.PREPARE_SHUTDOWN; } /** * Somebody from the outside wants us to shutdown */ public synchronized void shutdown() { if (this.shutdown_state == ShutdownState.SHUTDOWN) { if (debug.val) LOG.debug(String.format("Partition #%d told to shutdown again. Ignoring...", this.partitionId)); return; } this.shutdown_state = ShutdownState.SHUTDOWN; if (debug.val) LOG.debug(String.format("Shutting down PartitionExecutor for Partition #%d", this.partitionId)); // Clear the queue this.work_queue.clear(); // Knock out this ma if (this.m_snapshotter != null) this.m_snapshotter.shutdown(); // Make sure we shutdown our threadpool // this.thread_pool.shutdownNow(); if (this.self != null) this.self.interrupt(); if (this.shutdown_latch != null) { try { this.shutdown_latch.acquire(); } catch (InterruptedException ex) { // Ignore } catch (Exception ex) { LOG.fatal("Unexpected error while shutting down", ex); } } } // ---------------------------------------------------------------------------- // DEBUG METHODS // ---------------------------------------------------------------------------- @Override public String toString() { return String.format("%s{%s}", this.getClass().getSimpleName(), HStoreThreadManager.formatPartitionName(siteId, partitionId)); } public class Debug implements DebugContext { public VoltProcedure getVoltProcedure(String procName) { Procedure proc = catalogContext.procedures.getIgnoreCase(procName); return (PartitionExecutor.this.getVoltProcedure(proc.getId())); } public SpecExecScheduler getSpecExecScheduler() { return (PartitionExecutor.this.specExecScheduler); } public AbstractConflictChecker getSpecExecConflictChecker() { return (PartitionExecutor.this.specExecChecker); } public Collection<BatchPlanner> getBatchPlanners() { return (PartitionExecutor.this.batchPlanners.values()); } public PartitionExecutorProfiler getProfiler() { return (PartitionExecutor.this.profiler); } public Thread getExecutionThread() { return (PartitionExecutor.this.self); } public Queue<InternalMessage> getWorkQueue() { return (PartitionExecutor.this.work_queue); } public void setExecutionMode(AbstractTransaction ts, ExecutionMode newMode) { PartitionExecutor.this.setExecutionMode(ts, newMode); } public ExecutionMode getExecutionMode() { return (PartitionExecutor.this.currentExecMode); } public Long getLastExecutedTxnId() { return (PartitionExecutor.this.lastExecutedTxnId); } public Long getLastCommittedTxnId() { return (PartitionExecutor.this.lastCommittedTxnId); } public long getLastCommittedIndoToken() { return (PartitionExecutor.this.lastCommittedUndoToken); } /** * Get the VoltProcedure handle of the current running txn. This could be null. * <B>FOR TESTING ONLY</B> */ public VoltProcedure getCurrentVoltProcedure() { return (PartitionExecutor.this.currentVoltProc); } /** * Get the txnId of the current distributed transaction at this partition * <B>FOR TESTING ONLY</B> */ public AbstractTransaction getCurrentDtxn() { return (PartitionExecutor.this.currentDtxn); } /** * Get the txnId of the current distributed transaction at this partition * <B>FOR TESTING ONLY</B> */ public Long getCurrentDtxnId() { Long ret = null; // This is a race condition, so we'll just ignore any errors if (PartitionExecutor.this.currentDtxn != null) { try { ret = PartitionExecutor.this.currentDtxn.getTransactionId(); } catch (NullPointerException ex) { // IGNORE } } return (ret); } public Long getCurrentTxnId() { return (PartitionExecutor.this.currentTxnId); } public int getBlockedWorkCount() { return (PartitionExecutor.this.currentBlockedTxns.size()); } /** * Return the number of spec exec txns have completed but are waiting * for the distributed txn to finish at this partition */ public int getBlockedSpecExecCount() { return (PartitionExecutor.this.specExecBlocked.size()); } public int getWorkQueueSize() { return (PartitionExecutor.this.work_queue.size()); } public void updateMemory() { PartitionExecutor.this.updateMemoryStats(EstTime.currentTimeMillis()); } /** * Replace the ConflictChecker. This should only be used for testing * @param checker */ protected void setConflictChecker(AbstractConflictChecker checker) { LOG.warn(String.format("Replacing original checker %s with %s at partition %d", specExecChecker.getClass().getSimpleName(), checker.getClass().getSimpleName(), partitionId)); specExecChecker = checker; specExecScheduler.getDebugContext().setConflictChecker(checker); } } private Debug cachedDebugContext; public Debug getDebugContext() { if (this.cachedDebugContext == null) { // We don't care if we're thread-safe here... this.cachedDebugContext = new Debug(); } return this.cachedDebugContext; } }
private void getFragmentInputs(AbstractTransaction ts, int input_dep_id, Map<Integer, List<VoltTable>> inputs) { if (input_dep_id == HStoreConstants.NULL_DEPENDENCY_ID) return; if (trace.val) LOG.trace(String.format("%s - Attempting to retrieve input dependencies for DependencyId #%d", ts, input_dep_id)); // If the Transaction is on the same HStoreSite, then all the // input dependencies will be internal and can be retrieved locally if (ts instanceof LocalTransaction) { DependencyTracker txnTracker = null; if (ts.getBasePartition() != this.partitionId) { txnTracker = hstore_site.getDependencyTracker(ts.getBasePartition()); } else { txnTracker = this.depTracker; } List<VoltTable> deps = txnTracker.getInternalDependency((LocalTransaction)ts, input_dep_id); assert(deps != null); assert(inputs.containsKey(input_dep_id) == false); inputs.put(input_dep_id, deps); if (trace.val) LOG.trace(String.format("%s - Retrieved %d INTERNAL VoltTables for DependencyId #%d", ts, deps.size(), input_dep_id, (trace.val ? "\n" + deps : ""))); } // Otherwise they will be "attached" inputs to the RemoteTransaction handle // We should really try to merge these two concepts into a single function call else if (ts.getAttachedInputDependencies().containsKey(input_dep_id)) { List<VoltTable> deps = ts.getAttachedInputDependencies().get(input_dep_id); List<VoltTable> pDeps = null; // We have to copy the tables if we have debugging enabled if (trace.val) { // this.firstPartition == false) { pDeps = new ArrayList<VoltTable>(); for (VoltTable vt : deps) { ByteBuffer buffer = vt.getTableDataReference(); byte arr[] = new byte[vt.getUnderlyingBufferSize()]; buffer.get(arr, 0, arr.length); pDeps.add(new VoltTable(ByteBuffer.wrap(arr), true)); } } else { pDeps = deps; } inputs.put(input_dep_id, pDeps); if (trace.val) LOG.trace(String.format("%s - Retrieved %d ATTACHED VoltTables for DependencyId #%d in %s", ts, deps.size(), input_dep_id)); } } /** * Set the given AbstractTransaction handle as the current distributed txn * that is running at this partition. Note that this will check to make sure * that no other txn is marked as the currentDtxn. * @param ts */ private void setCurrentDtxn(AbstractTransaction ts) { // There can never be another current dtxn still unfinished at this partition! assert(this.currentBlockedTxns.isEmpty()) : String.format("Concurrent multi-partition transactions at partition %d: " + "Orig[%s] <=> New[%s] / BlockedQueue:%d", this.partitionId, this.currentDtxn, ts, this.currentBlockedTxns.size()); assert(this.currentDtxn == null) : String.format("Concurrent multi-partition transactions at partition %d: " + "Orig[%s] <=> New[%s] / BlockedQueue:%d", this.partitionId, this.currentDtxn, ts, this.currentBlockedTxns.size()); // Check whether we should check for speculative txns to execute whenever this // dtxn is idle at this partition this.currentDtxn = ts; if (hstore_conf.site.specexec_enable && ts.isSysProc() == false && this.specExecScheduler.isDisabled() == false) { this.specExecIgnoreCurrent = this.specExecChecker.shouldIgnoreTransaction(ts); } else { this.specExecIgnoreCurrent = true; } if (debug.val) { LOG.debug(String.format("Set %s as the current DTXN for partition %d [specExecIgnore=%s, previous=%s]", ts, this.partitionId, this.specExecIgnoreCurrent, this.lastDtxnDebug)); this.lastDtxnDebug = this.currentDtxn.toString(); } if (hstore_conf.site.exec_profiling && ts.getBasePartition() != this.partitionId) { profiler.sp2_time.start(); } } /** * Reset the current dtxn for this partition */ private void resetCurrentDtxn() { assert(this.currentDtxn != null) : "Trying to reset the currentDtxn when it is already null"; if (debug.val) LOG.debug(String.format("Resetting current DTXN for partition %d to null [previous=%s]", this.partitionId, this.lastDtxnDebug)); this.currentDtxn = null; } /** * Store a new prefetch result for a transaction * @param txnId * @param fragmentId * @param partitionId * @param params * @param result */ public void addPrefetchResult(LocalTransaction ts, int stmtCounter, int fragmentId, int partitionId, int paramsHash, VoltTable result) { if (debug.val) LOG.debug(String.format("%s - Adding prefetch result for %s with %d rows from partition %d " + "[stmtCounter=%d / paramsHash=%d]", ts, CatalogUtil.getPlanFragment(catalogContext.catalog, fragmentId).fullName(), result.getRowCount(), partitionId, stmtCounter, paramsHash)); this.depTracker.addPrefetchResult(ts, stmtCounter, fragmentId, partitionId, paramsHash, result); } // --------------------------------------------------------------- // PartitionExecutor API // --------------------------------------------------------------- /** * Queue a new transaction initialization at this partition. This will cause the * transaction to get added to this partition's lock queue. This PartitionExecutor does * not have to be this txn's base partition/ * @param ts */ public void queueSetPartitionLock(AbstractTransaction ts) { assert(ts.isInitialized()) : "Unexpected uninitialized transaction: " + ts; SetDistributedTxnMessage work = ts.getSetDistributedTxnMessage(); boolean success = this.work_queue.offer(work); assert(success) : String.format("Failed to queue %s at partition %d for %s", work, this.partitionId, ts); if (debug.val) LOG.debug(String.format("%s - Added %s to front of partition %d " + "work queue [size=%d]", ts, work.getClass().getSimpleName(), this.partitionId, this.work_queue.size())); if (hstore_conf.site.specexec_enable) this.specExecScheduler.interruptSearch(work); } /** * New work from the coordinator that this local site needs to execute (non-blocking) * This method will simply chuck the task into the work queue. * We should not be sent an InitiateTaskMessage here! * @param ts * @param task */ public void queueWork(AbstractTransaction ts, WorkFragment fragment) { assert(ts.isInitialized()) : "Unexpected uninitialized transaction: " + ts; WorkFragmentMessage work = ts.getWorkFragmentMessage(fragment); boolean success = this.work_queue.offer(work); // , true); assert(success) : String.format("Failed to queue %s at partition %d for %s", work, this.partitionId, ts); ts.markQueuedWork(this.partitionId); if (debug.val) LOG.debug(String.format("%s - Added %s to partition %d " + "work queue [size=%d]", ts, work.getClass().getSimpleName(), this.partitionId, this.work_queue.size())); if (hstore_conf.site.specexec_enable) this.specExecScheduler.interruptSearch(work); } /** * Add a new work message to our utility queue * @param work */ public void queueUtilityWork(InternalMessage work) { if (debug.val) LOG.debug(String.format("Added utility work %s to partition %d", work.getClass().getSimpleName(), this.partitionId)); this.work_queue.offer(work); } /** * Put the prepare request for the transaction into the queue * @param task * @param status The final status of the transaction */ public void queuePrepare(AbstractTransaction ts) { assert(ts.isInitialized()) : "Unexpected uninitialized transaction: " + ts; PrepareTxnMessage work = ts.getPrepareTxnMessage(); boolean success = this.work_queue.offer(work); assert(success) : String.format("Failed to queue %s at partition %d for %s", work, this.partitionId, ts); if (debug.val) LOG.debug(String.format("%s - Added %s to partition %d " + "work queue [size=%d]", ts, work.getClass().getSimpleName(), this.partitionId, this.work_queue.size())); // if (hstore_conf.site.specexec_enable) this.specExecScheduler.interruptSearch(); } /** * Put the finish request for the transaction into the queue * @param task * @param status The final status of the transaction */ public void queueFinish(AbstractTransaction ts, Status status) { assert(ts.isInitialized()) : "Unexpected uninitialized transaction: " + ts; FinishTxnMessage work = ts.getFinishTxnMessage(status); boolean success = this.work_queue.offer(work); // , true); assert(success) : String.format("Failed to queue %s at partition %d for %s", work, this.partitionId, ts); if (debug.val) LOG.debug(String.format("%s - Added %s to partition %d " + "work queue [size=%d]", ts, work.getClass().getSimpleName(), this.partitionId, this.work_queue.size())); // if (success) this.specExecScheduler.haltSearch(); } /** * Queue a new transaction invocation request at this partition * @param serializedRequest * @param catalog_proc * @param procParams * @param clientCallback * @return */ public boolean queueNewTransaction(ByteBuffer serializedRequest, long initiateTime, Procedure catalog_proc, ParameterSet procParams, RpcCallback<ClientResponseImpl> clientCallback) { boolean sysproc = catalog_proc.getSystemproc(); if (this.currentExecMode == ExecutionMode.DISABLED_REJECT && sysproc == false) return (false); InitializeRequestMessage work = new InitializeRequestMessage(serializedRequest, initiateTime, catalog_proc, procParams, clientCallback); if (debug.val) LOG.debug(String.format("Queuing %s for '%s' request on partition %d " + "[currentDtxn=%s, queueSize=%d, mode=%s]", work.getClass().getSimpleName(), catalog_proc.getName(), this.partitionId, this.currentDtxn, this.work_queue.size(), this.currentExecMode)); return (this.work_queue.offer(work)); } /** * Queue a new transaction invocation request at this partition * @param ts * @param task * @param callback */ public boolean queueStartTransaction(LocalTransaction ts) { assert(ts != null) : "Unexpected null transaction handle!"; boolean singlePartitioned = ts.isPredictSinglePartition(); boolean force = (singlePartitioned == false) || ts.isMapReduce() || ts.isSysProc(); // UPDATED 2012-07-12 // We used to have a bunch of checks to determine whether we needed // put the new request in the blocked queue or not. This required us to // acquire the exec_lock to do the check and then another lock to actually put // the request into the work_queue. Now we'll just throw it right in // the queue (checking for throttling of course) and let the main // thread sort out the mess of whether the txn should get blocked or not if (this.currentExecMode == ExecutionMode.DISABLED_REJECT) { if (debug.val) LOG.warn(String.format("%s - Not queuing txn at partition %d because current mode is %s", ts, this.partitionId, this.currentExecMode)); return (false); } StartTxnMessage work = ts.getStartTxnMessage(); if (debug.val) LOG.debug(String.format("Queuing %s for '%s' request on partition %d " + "[currentDtxn=%s, queueSize=%d, mode=%s]", work.getClass().getSimpleName(), ts.getProcedure().getName(), this.partitionId, this.currentDtxn, this.work_queue.size(), this.currentExecMode)); boolean success = this.work_queue.offer(work); // , force); if (debug.val && force && success == false) { String msg = String.format("Failed to add %s even though force flag was true!", ts); throw new ServerFaultException(msg, ts.getTransactionId()); } if (success && hstore_conf.site.specexec_enable) this.specExecScheduler.interruptSearch(work); return (success); } // --------------------------------------------------------------- // WORK QUEUE PROCESSING METHODS // --------------------------------------------------------------- /** * Process a WorkResult and update the internal state the LocalTransaction accordingly * Note that this will always be invoked by a thread other than the main execution thread * for this PartitionExecutor. That means if something comes back that's bad, we need a way * to alert the other thread so that it can act on it. * @param ts * @param result */ private void processWorkResult(LocalTransaction ts, WorkResult result) { boolean needs_profiling = (hstore_conf.site.txn_profiling && ts.profiler != null); if (debug.val) LOG.debug(String.format("Processing WorkResult for %s on partition %d [srcPartition=%d, deps=%d]", ts, this.partitionId, result.getPartitionId(), result.getDepDataCount())); // If the Fragment failed to execute, then we need to abort the Transaction // Note that we have to do this before we add the responses to the TransactionState so that // we can be sure that the VoltProcedure knows about the problem when it wakes the stored // procedure back up if (result.getStatus() != Status.OK) { if (trace.val) LOG.trace(String.format("Received non-success response %s from partition %d for %s", result.getStatus(), result.getPartitionId(), ts)); SerializableException error = null; if (needs_profiling) ts.profiler.startDeserialization(); try { ByteBuffer buffer = result.getError().asReadOnlyByteBuffer(); error = SerializableException.deserializeFromBuffer(buffer); } catch (Exception ex) { String msg = String.format("Failed to deserialize SerializableException from partition %d " + "for %s [bytes=%d]", result.getPartitionId(), ts, result.getError().size()); throw new ServerFaultException(msg, ex); } finally { if (needs_profiling) ts.profiler.stopDeserialization(); } // At this point there is no need to even deserialize the rest of the message because // we know that we're going to have to abort the transaction if (error == null) { LOG.warn(ts + " - Unexpected null SerializableException\n" + result); } else { if (debug.val) LOG.error(String.format("%s - Got error from partition %d in %s", ts, result.getPartitionId(), result.getClass().getSimpleName()), error); ts.setPendingError(error, true); } return; } if (needs_profiling) ts.profiler.startDeserialization(); for (int i = 0, cnt = result.getDepDataCount(); i < cnt; i++) { if (trace.val) LOG.trace(String.format("Storing intermediate results from partition %d for %s", result.getPartitionId(), ts)); int depId = result.getDepId(i); ByteString bs = result.getDepData(i); VoltTable vt = null; if (bs.isEmpty() == false) { FastDeserializer fd = new FastDeserializer(bs.asReadOnlyByteBuffer()); try { vt = fd.readObject(VoltTable.class); } catch (Exception ex) { throw new ServerFaultException("Failed to deserialize VoltTable from partition " + result.getPartitionId() + " for " + ts, ex); } } this.depTracker.addResult(ts, result.getPartitionId(), depId, vt); } // FOR (dependencies) if (needs_profiling) ts.profiler.stopDeserialization(); } /** * Execute a new transaction at this partition. * This will invoke the run() method define in the VoltProcedure for this txn and * then process the ClientResponse. Only the PartitionExecutor itself should be calling * this directly, since it's the only thing that knows what's going on with the world... * @param ts */ private void executeTransaction(LocalTransaction ts) { assert(ts.isInitialized()) : String.format("Trying to execute uninitialized transaction %s at partition %d", ts, this.partitionId); assert(ts.isMarkedReleased(this.partitionId)) : String.format("Transaction %s was not marked released at partition %d before being executed", ts, this.partitionId); if (trace.val) LOG.debug(String.format("%s - Attempting to start transaction on partition %d", ts, this.partitionId)); // If this is a MapReduceTransaction handle, we actually want to get the // inner LocalTransaction handle for this partition. The MapReduceTransaction // is just a placeholder if (ts instanceof MapReduceTransaction) { MapReduceTransaction mr_ts = (MapReduceTransaction)ts; ts = mr_ts.getLocalTransaction(this.partitionId); assert(ts != null) : "Unexpected null LocalTransaction handle from " + mr_ts; } ExecutionMode before_mode = this.currentExecMode; boolean predict_singlePartition = ts.isPredictSinglePartition(); // ------------------------------- // DISTRIBUTED TXN // ------------------------------- if (predict_singlePartition == false) { // If there is already a dtxn running, then we need to throw this // mofo back into the blocked txn queue // TODO: If our dtxn is on the same site as us, then at this point we know that // it is done executing the control code and is sending around 2PC messages // to commit/abort. That means that we could assume that all of the other // remote partitions are going to agree on the same outcome and we can start // speculatively executing this dtxn. After all, if we're at this point in // the PartitionExecutor then we know that we got this partition's locks // from the TransactionQueueManager. if (this.currentDtxn != null && this.currentDtxn.equals(ts) == false) { assert(this.currentDtxn.equals(ts) == false) : String.format("New DTXN %s != Current DTXN %s", ts, this.currentDtxn); // If this is a local txn, then we can finagle things a bit. if (this.currentDtxn.isExecLocal(this.partitionId)) { // It would be safe for us to speculative execute this DTXN right here // if the currentDtxn has aborted... but we can never be in this state. assert(this.currentDtxn.isAborted() == false) : // Sanity Check String.format("We want to execute %s on partition %d but aborted %s is still hanging around\n", ts, this.partitionId, this.currentDtxn, this.work_queue); // So that means we know that it committed, which doesn't necessarily mean // that it will still commit, but we'll be able to abort, rollback, and requeue // if that happens. // TODO: Right now our current dtxn marker is a single value. We may want to // switch it to a FIFO queue so that we can multiple guys hanging around. // For now we will just do the default thing and block this txn this.blockTransaction(ts); return; } // If it's not local, then we just have to block it right away else { this.blockTransaction(ts); return; } } // If there is no other DTXN right now, then we're it! else if (this.currentDtxn == null) { // || this.currentDtxn.equals(ts) == false) { this.setCurrentDtxn(ts); } // 2011-11-14: We don't want to set the execution mode here, because we know that we // can check whether we were read-only after the txn finishes this.setExecutionMode(this.currentDtxn, ExecutionMode.COMMIT_NONE); if (debug.val) LOG.debug(String.format("Marking %s as current DTXN on Partition %d [isLocal=%s, execMode=%s]", ts, this.partitionId, true, this.currentExecMode)); } // ------------------------------- // SINGLE-PARTITION TXN // ------------------------------- else { // If this is a single-partition transaction, then we need to check whether we are // being executed under speculative execution mode. We have to check this here // because it may be the case that we queued a bunch of transactions when speculative // execution was enabled, but now the transaction that was ahead of this one is finished, // so now we're just executing them regularly if (this.currentDtxn != null) { // HACK: If we are currently under DISABLED mode when we get this, then we just // need to block the transaction and return back to the queue. This is easier than // having to set all sorts of crazy locks if (this.currentExecMode == ExecutionMode.DISABLED || hstore_conf.site.specexec_enable == false) { if (debug.val) LOG.debug(String.format("%s - Blocking single-partition %s until dtxn finishes [mode=%s]", this.currentDtxn, ts, this.currentExecMode)); this.blockTransaction(ts); return; } assert(ts.getSpeculationType() != null); if (debug.val) LOG.debug(String.format("Speculatively executing %s while waiting for dtxn %s [%s]", ts, this.currentDtxn, ts.getSpeculationType())); assert(ts.isSpeculative()) : ts + " was not marked as being speculative!"; } } // If we reach this point, we know that we're about to execute our homeboy here... if (hstore_conf.site.txn_profiling && ts.profiler != null) { ts.profiler.startExec(); } if (hstore_conf.site.exec_profiling) this.profiler.numTransactions++; // Make sure the dependency tracker knows about us if (ts.hasDependencyTracker()) this.depTracker.addTransaction(ts); // Grab a new ExecutionState for this txn ExecutionState execState = this.initExecutionState(); ts.setExecutionState(execState); VoltProcedure volt_proc = this.getVoltProcedure(ts.getProcedure().getId()); assert(volt_proc != null) : "No VoltProcedure for " + ts; if (debug.val) { LOG.debug(String.format("%s - Starting execution of txn on partition %d " + "[txnMode=%s, mode=%s]", ts, this.partitionId, before_mode, this.currentExecMode)); if (trace.val) LOG.trace(String.format("Current Transaction at partition #%d\n%s", this.partitionId, ts.debug())); } if (hstore_conf.site.txn_counters) TransactionCounter.EXECUTED.inc(ts.getProcedure()); ClientResponseImpl cresponse = null; VoltProcedure previous = this.currentVoltProc; try { this.currentVoltProc = volt_proc; cresponse = volt_proc.call(ts, ts.getProcedureParameters().toArray()); // Blocking... // VoltProcedure.call() should handle any exceptions thrown by the transaction // If we get anything out here then that's bad news } catch (Throwable ex) { if (this.isShuttingDown() == false) { SQLStmt last[] = volt_proc.voltLastQueriesExecuted(); LOG.fatal("Unexpected error while executing " + ts, ex); if (last.length > 0) { LOG.fatal(String.format("Last Queries Executed [%d]: %s", last.length, Arrays.toString(last))); } LOG.fatal("LocalTransactionState Dump:\n" + ts.debug()); this.crash(ex); } } finally { this.currentVoltProc = previous; ts.resetExecutionState(); execState.finish(); this.execStates.add(execState); this.finishVoltProcedure(volt_proc); if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.startPost(); // if (cresponse.getStatus() == Status.ABORT_UNEXPECTED) { // cresponse.getException().printStackTrace(); // } } // If this is a MapReduce job, then we can just ignore the ClientResponse // and return immediately. The VoltMapReduceProcedure is responsible for storing // the result at the proper location. if (ts.isMapReduce()) { return; } else if (cresponse == null) { assert(this.isShuttingDown()) : String.format("No ClientResponse for %s???", ts); return; } // ------------------------------- // PROCESS RESPONSE AND FIGURE OUT NEXT STEP // ------------------------------- Status status = cresponse.getStatus(); if (debug.val) { LOG.debug(String.format("%s - Finished execution of transaction control code " + "[status=%s, beforeMode=%s, currentMode=%s]", ts, status, before_mode, this.currentExecMode)); if (ts.hasPendingError()) { LOG.debug(String.format("%s - Txn finished with pending error: %s", ts, ts.getPendingErrorMessage())); } } // We assume that most transactions are not speculatively executed and are successful // Therefore we don't want to grab the exec_mode lock here. if (predict_singlePartition == false || this.canProcessClientResponseNow(ts, status, before_mode)) { this.processClientResponse(ts, cresponse); } // Otherwise always queue our response, since we know that whatever thread is out there // is waiting for us to finish before it drains the queued responses else { // If the transaction aborted, then we can't execute any transaction that touch the tables // that this guy touches. But since we can't just undo this transaction without undoing // everything that came before it, we'll just disable executing all transactions until the // current distributed transaction commits if (status != Status.OK && ts.isExecReadOnly(this.partitionId) == false) { this.setExecutionMode(ts, ExecutionMode.DISABLED); int blocked = this.work_queue.drainTo(this.currentBlockedTxns); if (debug.val) { if (trace.val && blocked > 0) LOG.trace(String.format("Blocking %d transactions at partition %d because ExecutionMode is now %s", blocked, this.partitionId, this.currentExecMode)); LOG.debug(String.format("Disabling execution on partition %d because speculative %s aborted", this.partitionId, ts)); } } if (trace.val) LOG.trace(String.format("%s - Queuing ClientResponse [status=%s, origMode=%s, newMode=%s, dtxn=%s]", ts, cresponse.getStatus(), before_mode, this.currentExecMode, this.currentDtxn)); this.blockClientResponse(ts, cresponse); } } /** * Determines whether a finished transaction that executed locally can have their ClientResponse processed immediately * or if it needs to wait for the response from the outstanding multi-partition transaction for this partition * (1) This is the multi-partition transaction that everyone is waiting for * (2) The transaction was not executed under speculative execution mode * (3) The transaction does not need to wait for the multi-partition transaction to finish first * @param ts * @param status * @param before_mode * @return */ private boolean canProcessClientResponseNow(LocalTransaction ts, Status status, ExecutionMode before_mode) { if (debug.val) LOG.debug(String.format("%s - Checking whether to process %s response now at partition %d " + "[singlePartition=%s, readOnly=%s, specExecModified=%s, before=%s, current=%s]", ts, status, this.partitionId, ts.isPredictSinglePartition(), ts.isExecReadOnly(this.partitionId), this.specExecModified, before_mode, this.currentExecMode)); // Commit All if (this.currentExecMode == ExecutionMode.COMMIT_ALL) { return (true); } // SPECIAL CASE // Any user-aborted, speculative single-partition transaction should be processed immediately. else if (status == Status.ABORT_USER && ts.isSpeculative()) { return (true); } // // SPECIAL CASE // // If this txn threw a user abort, and the current outstanding dtxn is read-only // // then it's safe for us to rollback // else if (status == Status.ABORT_USER && // this.currentDtxn != null && // this.currentDtxn.isExecReadOnly(this.partitionId)) { // return (true); // } // SPECIAL CASE // Anything mispredicted should be processed right away else if (status == Status.ABORT_MISPREDICT) { return (true); } // Process successful txns based on the mode that it was executed under else if (status == Status.OK) { switch (before_mode) { case COMMIT_ALL: return (true); case COMMIT_READONLY: // Read-only speculative txns can be committed right now // TODO: Right now we're going to use the specExecModified flag to disable // sending out any results from spec execed txns that may have read from // a modified database. We should switch to a bitmap of table ids so that we // have can be more selective. // return (false); return (this.specExecModified == false && ts.isExecReadOnly(this.partitionId)); case COMMIT_NONE: { // If this txn does not conflict with the current dtxn, then we should be able // to let it commit but we can't because of the way our undo tokens work return (false); } default: throw new ServerFaultException("Unexpected execution mode: " + before_mode, ts.getTransactionId()); } // SWITCH } // // If the transaction aborted and it was read-only thus far, then we want to process it immediately // else if (status != Status.OK && ts.isExecReadOnly(this.partitionId)) { // return (true); // } assert(this.currentExecMode != ExecutionMode.COMMIT_ALL) : String.format("Queuing ClientResponse for %s when in non-specutative mode [mode=%s, status=%s]", ts, this.currentExecMode, status); return (false); } /** * Process a WorkFragment for a transaction and execute it in this partition's underlying EE. * @param ts * @param fragment * @param allParameters The array of all the ParameterSets for the current SQLStmt batch. */ private void processWorkFragment(AbstractTransaction ts, WorkFragment fragment, ParameterSet allParameters[]) { assert(this.partitionId == fragment.getPartitionId()) : String.format("Tried to execute WorkFragment %s for %s at partition %d but it was suppose " + "to be executed on partition %d", fragment.getFragmentIdList(), ts, this.partitionId, fragment.getPartitionId()); assert(ts.isMarkedPrepared(this.partitionId) == false) : String.format("Tried to execute WorkFragment %s for %s at partition %d after it was marked 2PC:PREPARE", fragment.getFragmentIdList(), ts, this.partitionId); // A txn is "local" if the Java is executing at the same partition as this one boolean is_basepartition = (ts.getBasePartition() == this.partitionId); boolean is_remote = (ts instanceof LocalTransaction == false); boolean is_prefetch = fragment.getPrefetch(); boolean is_readonly = fragment.getReadOnly(); if (debug.val) LOG.debug(String.format("%s - Executing %s [isBasePartition=%s, isRemote=%s, isPrefetch=%s, isReadOnly=%s, fragments=%s]", ts, fragment.getClass().getSimpleName(), is_basepartition, is_remote, is_prefetch, is_readonly, fragment.getFragmentIdCount())); // If this WorkFragment isn't being executed at this txn's base partition, then // we need to start a new execution round if (is_basepartition == false) { long undoToken = this.calculateNextUndoToken(ts, is_readonly); ts.initRound(this.partitionId, undoToken); ts.startRound(this.partitionId); } DependencySet result = null; Status status = Status.OK; SerializableException error = null; // Check how many fragments are not marked as ignored // If the fragment is marked as ignore then it means that it was already // sent to this partition for prefetching. We need to make sure that we remove // it from the list of fragmentIds that we need to execute. int fragmentCount = fragment.getFragmentIdCount(); for (int i = 0; i < fragmentCount; i++) { if (fragment.getStmtIgnore(i)) { fragmentCount--; } } // FOR final ParameterSet parameters[] = tmp_fragmentParams.getParameterSet(fragmentCount); assert(parameters.length == fragmentCount); // Construct data given to the EE to execute this work fragment this.tmp_EEdependencies.clear(); long fragmentIds[] = tmp_fragmentIds.getArray(fragmentCount); int fragmentOffsets[] = tmp_fragmentOffsets.getArray(fragmentCount); int outputDepIds[] = tmp_outputDepIds.getArray(fragmentCount); int inputDepIds[] = tmp_inputDepIds.getArray(fragmentCount); int offset = 0; for (int i = 0, cnt = fragment.getFragmentIdCount(); i < cnt; i++) { if (fragment.getStmtIgnore(i) == false) { fragmentIds[offset] = fragment.getFragmentId(i); fragmentOffsets[offset] = i; outputDepIds[offset] = fragment.getOutputDepId(i); inputDepIds[offset] = fragment.getInputDepId(i); parameters[offset] = allParameters[fragment.getParamIndex(i)]; this.getFragmentInputs(ts, inputDepIds[offset], this.tmp_EEdependencies); if (trace.val && ts.isSysProc() == false && is_basepartition == false) LOG.trace(String.format("%s - Offset:%d FragmentId:%d OutputDep:%d/%d InputDep:%d/%d", ts, offset, fragmentIds[offset], outputDepIds[offset], fragment.getOutputDepId(i), inputDepIds[offset], fragment.getInputDepId(i))); offset++; } } // FOR assert(offset == fragmentCount); try { result = this.executeFragmentIds(ts, ts.getLastUndoToken(this.partitionId), fragmentIds, parameters, outputDepIds, inputDepIds, this.tmp_EEdependencies); } catch (EvictedTupleAccessException ex) { // XXX: What do we do if this is not a single-partition txn? status = Status.ABORT_EVICTEDACCESS; error = ex; } catch (ConstraintFailureException ex) { status = Status.ABORT_UNEXPECTED; error = ex; } catch (SQLException ex) { status = Status.ABORT_UNEXPECTED; error = ex; } catch (EEException ex) { // this.crash(ex); status = Status.ABORT_UNEXPECTED; error = ex; } catch (Throwable ex) { status = Status.ABORT_UNEXPECTED; if (ex instanceof SerializableException) { error = (SerializableException)ex; } else { error = new SerializableException(ex); } } finally { if (error != null) { // error.printStackTrace(); LOG.warn(String.format("%s - Unexpected %s on partition %d", ts, error.getClass().getSimpleName(), this.partitionId), error); // (debug.val ? error : null)); } // Success, but without any results??? if (result == null && status == Status.OK) { String msg = String.format("The WorkFragment %s executed successfully on Partition %d but " + "result is null for %s", fragment.getFragmentIdList(), this.partitionId, ts); Exception ex = new Exception(msg); if (debug.val) LOG.warn(ex); status = Status.ABORT_UNEXPECTED; error = new SerializableException(ex); } } // For single-partition INSERT/UPDATE/DELETE queries, we don't directly // execute the SendPlanNode in order to get back the number of tuples that // were modified. So we have to rely on the output dependency ids set in the task assert(status != Status.OK || (status == Status.OK && result.size() == fragmentIds.length)) : "Got back " + result.size() + " results but was expecting " + fragmentIds.length; // Make sure that we mark the round as finished before we start sending results if (is_basepartition == false) { ts.finishRound(this.partitionId); } // ------------------------------- // PREFETCH QUERIES // ------------------------------- if (is_prefetch) { // Regardless of whether this txn is running at the same HStoreSite as this PartitionExecutor, // we always need to put the result inside of the local query cache // This is so that we can identify if we get request for a query that we have already executed // We'll only do this if it succeeded. If it failed, then we won't do anything and will // just wait until they come back to execute the query again before // we tell them that something went wrong. It's ghetto, but it's just easier this way... if (status == Status.OK) { // We're going to store the result in the base partition cache if they're // on the same HStoreSite as us if (is_remote == false) { PartitionExecutor other = this.hstore_site.getPartitionExecutor(ts.getBasePartition()); for (int i = 0, cnt = result.size(); i < cnt; i++) { if (trace.val) LOG.trace(String.format("%s - Storing %s prefetch result [params=%s]", ts, CatalogUtil.getPlanFragment(catalogContext.catalog, fragment.getFragmentId(fragmentOffsets[i])).fullName(), parameters[i])); other.addPrefetchResult((LocalTransaction)ts, fragment.getStmtCounter(fragmentOffsets[i]), fragment.getFragmentId(fragmentOffsets[i]), this.partitionId, parameters[i].hashCode(), result.dependencies[i]); } // FOR } } // Now if it's a remote transaction, we need to use the coordinator to send // them our result. Note that we want to send a single message per partition. Unlike // with the TransactionWorkRequests, we don't need to wait until all of the partitions // that are prefetching for this txn at our local HStoreSite to finish. if (is_remote) { WorkResult wr = this.buildWorkResult(ts, result, status, error); TransactionPrefetchResult.Builder builder = TransactionPrefetchResult.newBuilder() .setTransactionId(ts.getTransactionId().longValue()) .setSourcePartition(this.partitionId) .setResult(wr) .setStatus(status) .addAllFragmentId(fragment.getFragmentIdList()) .addAllStmtCounter(fragment.getStmtCounterList()); for (int i = 0, cnt = fragment.getFragmentIdCount(); i < cnt; i++) { builder.addParamHash(parameters[i].hashCode()); } if (debug.val) LOG.debug(String.format("%s - Sending back %s to partition %d [numResults=%s, status=%s]", ts, wr.getClass().getSimpleName(), ts.getBasePartition(), result.size(), status)); hstore_coordinator.transactionPrefetchResult((RemoteTransaction)ts, builder.build()); } } // ------------------------------- // LOCAL TRANSACTION // ------------------------------- else if (is_remote == false) { LocalTransaction local_ts = (LocalTransaction)ts; // If the transaction is local, store the result directly in the local TransactionState if (status == Status.OK) { if (trace.val) LOG.trace(String.format("%s - Storing %d dependency results locally for successful work fragment", ts, result.size())); assert(result.size() == outputDepIds.length); DependencyTracker otherTracker = this.hstore_site.getDependencyTracker(ts.getBasePartition()); for (int i = 0; i < outputDepIds.length; i++) { if (trace.val) LOG.trace(String.format("%s - Storing DependencyId #%d [numRows=%d]\n%s", ts, outputDepIds[i], result.dependencies[i].getRowCount(), result.dependencies[i])); try { otherTracker.addResult(local_ts, this.partitionId, outputDepIds[i], result.dependencies[i]); } catch (Throwable ex) { // ex.printStackTrace(); String msg = String.format("Failed to stored Dependency #%d for %s [idx=%d, fragmentId=%d]", outputDepIds[i], ts, i, fragmentIds[i]); LOG.error(String.format("%s - WorkFragment:%d\nExpectedIds:%s\nOutputDepIds: %s\nResultDepIds: %s\n%s", msg, fragment.hashCode(), fragment.getOutputDepIdList(), Arrays.toString(outputDepIds), Arrays.toString(result.depIds), fragment)); throw new ServerFaultException(msg, ex); } } // FOR } else { local_ts.setPendingError(error, true); } } // ------------------------------- // REMOTE TRANSACTION // ------------------------------- else { if (trace.val) LOG.trace(String.format("%s - Constructing WorkResult with %d bytes from partition %d to send " + "back to initial partition %d [status=%s]", ts, (result != null ? result.size() : null), this.partitionId, ts.getBasePartition(), status)); RpcCallback<WorkResult> callback = ((RemoteTransaction)ts).getWorkCallback(); if (callback == null) { LOG.fatal("Unable to send FragmentResponseMessage for " + ts); LOG.fatal("Orignal WorkFragment:\n" + fragment); LOG.fatal(ts.toString()); throw new ServerFaultException("No RPC callback to HStoreSite for " + ts, ts.getTransactionId()); } WorkResult response = this.buildWorkResult((RemoteTransaction)ts, result, status, error); assert(response != null); callback.run(response); } // Check whether this is the last query that we're going to get // from this transaction. If it is, then we can go ahead and prepare the txn if (is_basepartition == false && fragment.getLastFragment()) { if (debug.val) LOG.debug(String.format("%s - Invoking early 2PC:PREPARE at partition %d", ts, this.partitionId)); this.queuePrepare(ts); } } /** * Executes a WorkFragment on behalf of some remote site and returns the * resulting DependencySet * @param fragment * @return * @throws Exception */ private DependencySet executeFragmentIds(AbstractTransaction ts, long undoToken, long fragmentIds[], ParameterSet parameters[], int output_depIds[], int input_depIds[], Map<Integer, List<VoltTable>> input_deps) throws Exception { if (fragmentIds.length == 0) { LOG.warn(String.format("Got a fragment batch for %s that does not have any fragments?", ts)); return (null); } // *********************************** DEBUG *********************************** if (trace.val) { LOG.trace(String.format("%s - Getting ready to kick %d fragments to partition %d EE [undoToken=%d]", ts, fragmentIds.length, this.partitionId, (undoToken != HStoreConstants.NULL_UNDO_LOGGING_TOKEN ? undoToken : "null"))); // if (trace.val) { // LOG.trace("WorkFragmentIds: " + Arrays.toString(fragmentIds)); // Map<String, Object> m = new LinkedHashMap<String, Object>(); // for (int i = 0; i < parameters.length; i++) { // m.put("Parameter[" + i + "]", parameters[i]); // } // FOR // LOG.trace("Parameters:\n" + StringUtil.formatMaps(m)); // } } // *********************************** DEBUG *********************************** DependencySet result = null; // ------------------------------- // SYSPROC FRAGMENTS // ------------------------------- if (ts.isSysProc()) { result = this.executeSysProcFragments(ts, undoToken, fragmentIds.length, fragmentIds, parameters, output_depIds, input_depIds, input_deps); // ------------------------------- // REGULAR FRAGMENTS // ------------------------------- } else { result = this.executePlanFragments(ts, undoToken, fragmentIds.length, fragmentIds, parameters, output_depIds, input_depIds, input_deps); if (result == null) { LOG.warn(String.format("Output DependencySet for %s in %s is null?", Arrays.toString(fragmentIds), ts)); } } return (result); } /** * Execute a BatchPlan directly on this PartitionExecutor without having to covert it * to WorkFragments first. This is big speed improvement over having to queue things up * @param ts * @param plan * @return */ private VoltTable[] executeLocalPlan(LocalTransaction ts, BatchPlanner.BatchPlan plan, ParameterSet parameterSets[]) { // Start the new execution round long undoToken = this.calculateNextUndoToken(ts, plan.isReadOnly()); ts.initFirstRound(undoToken, plan.getBatchSize()); int fragmentCount = plan.getFragmentCount(); long fragmentIds[] = plan.getFragmentIds(); int output_depIds[] = plan.getOutputDependencyIds(); int input_depIds[] = plan.getInputDependencyIds(); // Mark that we touched the local partition once for each query in the batch // ts.getTouchedPartitions().put(this.partitionId, plan.getBatchSize()); // Only notify other partitions that we're done with them if we're not // a single-partition transaction if (hstore_conf.site.specexec_enable && ts.isPredictSinglePartition() == false) { //FIXME //PartitionSet new_done = ts.calculateDonePartitions(this.thresholds); //if (new_done != null && new_done.isEmpty() == false) { // LocalPrepareCallback callback = ts.getPrepareCallback(); // assert(callback.isInitialized()); // this.hstore_coordinator.transactionPrepare(ts, callback, new_done); //} } if (trace.val) LOG.trace(String.format("Txn #%d - BATCHPLAN:\n" + " fragmentIds: %s\n" + " fragmentCount: %s\n" + " output_depIds: %s\n" + " input_depIds: %s", ts.getTransactionId(), Arrays.toString(plan.getFragmentIds()), plan.getFragmentCount(), Arrays.toString(plan.getOutputDependencyIds()), Arrays.toString(plan.getInputDependencyIds()))); // NOTE: There are no dependencies that we need to pass in because the entire // batch is local to this partition. DependencySet result = null; try { result = this.executePlanFragments(ts, undoToken, fragmentCount, fragmentIds, parameterSets, output_depIds, input_depIds, null); } finally { ts.fastFinishRound(this.partitionId); } // assert(result != null) : "Unexpected null DependencySet result for " + ts; if (trace.val) LOG.trace("Output:\n" + result); return (result != null ? result.dependencies : null); } /** * Execute the given fragment tasks on this site's underlying EE * @param ts * @param undoToken * @param batchSize * @param fragmentIds * @param parameterSets * @param output_depIds * @param input_depIds * @return */ private DependencySet executeSysProcFragments(AbstractTransaction ts, long undoToken, int batchSize, long fragmentIds[], ParameterSet parameters[], int output_depIds[], int input_depIds[], Map<Integer, List<VoltTable>> input_deps) { assert(fragmentIds.length == 1); assert(fragmentIds.length == parameters.length) : String.format("%s - Fragments:%d / Parameters:%d", ts, fragmentIds.length, parameters.length); VoltSystemProcedure volt_proc = this.m_registeredSysProcPlanFragments.get(fragmentIds[0]); if (volt_proc == null) { String msg = "No sysproc handle exists for FragmentID #" + fragmentIds[0] + " :: " + this.m_registeredSysProcPlanFragments; throw new ServerFaultException(msg, ts.getTransactionId()); } // HACK: We have to set the TransactionState for sysprocs manually volt_proc.setTransactionState(ts); ts.markExecNotReadOnly(this.partitionId); DependencySet result = null; try { result = volt_proc.executePlanFragment(ts.getTransactionId(), this.tmp_EEdependencies, (int)fragmentIds[0], parameters[0], this.m_systemProcedureContext); } catch (Throwable ex) { String msg = "Unexpected error when executing system procedure"; throw new ServerFaultException(msg, ex, ts.getTransactionId()); } if (debug.val) LOG.debug(String.format("%s - Finished executing sysproc fragment for %s (#%d)%s", ts, m_registeredSysProcPlanFragments.get(fragmentIds[0]).getClass().getSimpleName(), fragmentIds[0], (trace.val ? "\n" + result : ""))); return (result); } /** * Execute the given fragment tasks on this site's underlying EE * @param ts * @param undoToken * @param batchSize * @param fragmentIds * @param parameterSets * @param output_depIds * @param input_depIds * @return */ private DependencySet executePlanFragments(AbstractTransaction ts, long undoToken, int batchSize, long fragmentIds[], ParameterSet parameterSets[], int output_depIds[], int input_depIds[], Map<Integer, List<VoltTable>> input_deps) { assert(this.ee != null) : "The EE object is null. This is bad!"; Long txn_id = ts.getTransactionId(); //LOG.info("in executePlanFragments()"); // *********************************** DEBUG *********************************** if (debug.val) { StringBuilder sb = new StringBuilder(); sb.append(String.format("%s - Executing %d fragments [lastTxnId=%d, undoToken=%d]", ts, batchSize, this.lastCommittedTxnId, undoToken)); // if (trace.val) { Map<String, Object> m = new LinkedHashMap<String, Object>(); m.put("Fragments", Arrays.toString(fragmentIds)); Map<Integer, Object> inner = new LinkedHashMap<Integer, Object>(); for (int i = 0; i < batchSize; i++) inner.put(i, parameterSets[i].toString()); m.put("Parameters", inner); if (batchSize > 0 && input_depIds[0] != HStoreConstants.NULL_DEPENDENCY_ID) { inner = new LinkedHashMap<Integer, Object>(); for (int i = 0; i < batchSize; i++) { List<VoltTable> deps = input_deps.get(input_depIds[i]); inner.put(input_depIds[i], (deps != null ? StringUtil.join("\n", deps) : "???")); } // FOR m.put("Input Dependencies", inner); } m.put("Output Dependencies", Arrays.toString(output_depIds)); sb.append("\n" + StringUtil.formatMaps(m)); // } LOG.debug(sb.toString().trim()); } // *********************************** DEBUG *********************************** // pass attached dependencies to the EE (for non-sysproc work). if (input_deps != null && input_deps.isEmpty() == false) { if (debug.val) LOG.debug(String.format("%s - Stashing %d InputDependencies at partition %d", ts, input_deps.size(), this.partitionId)); this.ee.stashWorkUnitDependencies(input_deps); } // Java-based Table Read-Write Sets boolean readonly = true; boolean speculative = ts.isSpeculative(); boolean singlePartition = ts.isPredictSinglePartition(); int tableIds[] = null; for (int i = 0; i < batchSize; i++) { boolean fragReadOnly = PlanFragmentIdGenerator.isPlanFragmentReadOnly(fragmentIds[i]); // We don't need to maintain read/write sets for non-speculative txns if (speculative || singlePartition == false) { if (fragReadOnly) { tableIds = catalogContext.getReadTableIds(Long.valueOf(fragmentIds[i])); if (tableIds != null) ts.markTableIdsRead(this.partitionId, tableIds); } else { tableIds = catalogContext.getWriteTableIds(Long.valueOf(fragmentIds[i])); if (tableIds != null) ts.markTableIdsWritten(this.partitionId, tableIds); } } readonly = readonly && fragReadOnly; } // Enable read/write set tracking if (hstore_conf.site.exec_readwrite_tracking && ts.hasExecutedWork(this.partitionId) == false) { if (trace.val) LOG.trace(String.format("%s - Enabling read/write set tracking in EE at partition %d", ts, this.partitionId)); this.ee.trackingEnable(txn_id); } // Check whether the txn has only exeuted read-only queries up to this point if (ts.isExecReadOnly(this.partitionId)) { if (readonly == false) { if (trace.val) LOG.trace(String.format("%s - Marking txn as not read-only %s", ts, Arrays.toString(fragmentIds))); ts.markExecNotReadOnly(this.partitionId); } // We can do this here because the only way that we're not read-only is if // we actually modify data at this partition ts.markExecutedWork(this.partitionId); } DependencySet result = null; boolean needs_profiling = false; if (ts.isExecLocal(this.partitionId)) { if (hstore_conf.site.txn_profiling && ((LocalTransaction)ts).profiler != null) { needs_profiling = true; ((LocalTransaction)ts).profiler.startExecEE(); } } Throwable error = null; try { assert(this.lastCommittedUndoToken < undoToken) : String.format("Trying to execute work using undoToken %d for %s but " + "it is less than the last committed undoToken %d at partition %d", undoToken, ts, this.lastCommittedUndoToken, this.partitionId); if (trace.val) LOG.trace(String.format("%s - Executing fragments %s at partition %d [undoToken=%d]", ts, Arrays.toString(fragmentIds), this.partitionId, undoToken)); result = this.ee.executeQueryPlanFragmentsAndGetDependencySet( fragmentIds, batchSize, input_depIds, output_depIds, parameterSets, batchSize, txn_id.longValue(), this.lastCommittedTxnId.longValue(), undoToken); } catch (AssertionError ex) { LOG.error("Fatal error when processing " + ts + "\n" + ts.debug()); error = ex; throw ex; } catch (EvictedTupleAccessException ex) { if (debug.val) LOG.warn("Caught EvictedTupleAccessException."); error = ex; throw ex; } catch (SerializableException ex) { if (debug.val) LOG.error(String.format("%s - Unexpected error in the ExecutionEngine on partition %d", ts, this.partitionId), ex); error = ex; throw ex; } catch (Throwable ex) { error = ex; String msg = String.format("%s - Failed to execute PlanFragments: %s", ts, Arrays.toString(fragmentIds)); throw new ServerFaultException(msg, ex); } finally { if (needs_profiling) ((LocalTransaction)ts).profiler.stopExecEE(); if (error == null && result == null) { LOG.warn(String.format("%s - Finished executing fragments but got back null results [fragmentIds=%s]", ts, Arrays.toString(fragmentIds))); } } // *********************************** DEBUG *********************************** if (debug.val) { if (result != null) { LOG.debug(String.format("%s - Finished executing fragments and got back %d results", ts, result.depIds.length)); } else { LOG.warn(String.format("%s - Finished executing fragments but got back null results? That seems bad...", ts)); } } // *********************************** DEBUG *********************************** return (result); } /** * Load a VoltTable directly into the EE at this partition. * <B>NOTE:</B> This should only be invoked by a system stored procedure. * @param txn_id * @param clusterName * @param databaseName * @param tableName * @param data * @param allowELT * @throws VoltAbortException */ public void loadTable(AbstractTransaction ts, String clusterName, String databaseName, String tableName, VoltTable data, int allowELT) throws VoltAbortException { Table table = this.catalogContext.database.getTables().getIgnoreCase(tableName); if (table == null) { throw new VoltAbortException("Table '" + tableName + "' does not exist in database " + clusterName + "." + databaseName); } if (debug.val) LOG.debug(String.format("Loading %d row(s) into %s [txnId=%d]", data.getRowCount(), table.getName(), ts.getTransactionId())); ts.markExecutedWork(this.partitionId); this.ee.loadTable(table.getRelativeIndex(), data, ts.getTransactionId(), this.lastCommittedTxnId.longValue(), ts.getLastUndoToken(this.partitionId), allowELT != 0); } /** * Load a VoltTable directly into the EE at this partition. * <B>NOTE:</B> This should only be used for testing * @param txnId * @param table * @param data * @param allowELT * @throws VoltAbortException */ protected void loadTable(Long txnId, Table table, VoltTable data, boolean allowELT) throws VoltAbortException { if (debug.val) LOG.debug(String.format("Loading %d row(s) into %s [txnId=%d]", data.getRowCount(), table.getName(), txnId)); this.ee.loadTable(table.getRelativeIndex(), data, txnId.longValue(), this.lastCommittedTxnId.longValue(), HStoreConstants.NULL_UNDO_LOGGING_TOKEN, allowELT); } /** * Execute a SQLStmt batch at this partition. This is the main entry point from * VoltProcedure for where we will execute a SQLStmt batch from a txn. * @param ts The txn handle that is executing this query batch * @param batchSize The number of SQLStmts that the txn queued up using voltQueueSQL() * @param batchStmts The SQLStmts that the txn is trying to execute * @param batchParams The input parameters for the SQLStmts * @param finalTask Whether the txn has marked this as the last batch that they will ever execute * @param forceSinglePartition Whether to force the BatchPlanner to only generate a single-partition plan * @return */ public VoltTable[] executeSQLStmtBatch(LocalTransaction ts, int batchSize, SQLStmt batchStmts[], ParameterSet batchParams[], boolean finalTask, boolean forceSinglePartition) { boolean needs_profiling = (hstore_conf.site.txn_profiling && ts.profiler != null); if (needs_profiling) { ts.profiler.addBatch(batchSize); ts.profiler.stopExecJava(); ts.profiler.startExecPlanning(); } // HACK: This is needed to handle updates on replicated tables properly // when there is only one partition in the cluster. if (catalogContext.numberOfPartitions == 1) { this.depTracker.addTransaction(ts); } if (hstore_conf.site.exec_deferrable_queries) { // TODO: Loop through batchStmts and check whether their corresponding Statement // is marked as deferrable. If so, then remove them from batchStmts and batchParams // (sliding everyone over by one in the arrays). Queue up the deferred query. // Be sure decrement batchSize after you finished processing this. // EXAMPLE: batchStmts[0].getStatement().getDeferrable() } // Calculate the hash code for this batch to see whether we already have a planner final Integer batchHashCode = VoltProcedure.getBatchHashCode(batchStmts, batchSize); BatchPlanner planner = this.batchPlanners.get(batchHashCode); if (planner == null) { // Assume fast case planner = new BatchPlanner(batchStmts, batchSize, ts.getProcedure(), this.p_estimator, forceSinglePartition); this.batchPlanners.put(batchHashCode, planner); } assert(planner != null); // At this point we have to calculate exactly what we need to do on each partition // for this batch. So somehow right now we need to fire this off to either our // local executor or to Evan's magical distributed transaction manager BatchPlanner.BatchPlan plan = planner.plan(ts.getTransactionId(), this.partitionId, ts.getPredictTouchedPartitions(), ts.getTouchedPartitions(), batchParams); assert(plan != null); if (trace.val) { LOG.trace(ts + " - Touched Partitions: " + ts.getTouchedPartitions().values()); LOG.trace(ts + " - Next BatchPlan:\n" + plan.toString()); } if (needs_profiling) ts.profiler.stopExecPlanning(); // Tell the TransactionEstimator that we're about to execute these mofos EstimatorState t_state = ts.getEstimatorState(); if (this.localTxnEstimator != null && t_state != null && t_state.isUpdatesEnabled()) { if (needs_profiling) ts.profiler.startExecEstimation(); try { this.localTxnEstimator.executeQueries(t_state, planner.getStatements(), plan.getStatementPartitions()); } finally { if (needs_profiling) ts.profiler.stopExecEstimation(); } } else if (t_state != null && t_state.shouldAllowUpdates()) { LOG.warn("Skipping estimator updates for " + ts); } // Check whether our plan was caused a mispredict // Doing it this way allows us to update the TransactionEstimator before we abort the txn if (plan.getMisprediction() != null) { MispredictionException ex = plan.getMisprediction(); ts.setPendingError(ex, false); assert(ex.getPartitions().isEmpty() == false) : "Unexpected empty PartitionSet for mispredicated txn " + ts; // Print Misprediction Debug if (hstore_conf.site.exec_mispredict_crash) { // Use a lock so that only dump out the first txn that fails synchronized (PartitionExecutor.class) { LOG.warn("\n" + EstimatorUtil.mispredictDebug(ts, planner, batchStmts, batchParams)); LOG.fatal(String.format("Crashing because site.exec_mispredict_crash is true [txn=%s]", ts)); this.crash(ex); } // SYNCH } else if (debug.val) { if (trace.val) LOG.warn("\n" + EstimatorUtil.mispredictDebug(ts, planner, batchStmts, batchParams)); LOG.debug(ts + " - Aborting and restarting mispredicted txn."); } throw ex; } // Keep track of the number of times that we've executed each query for this transaction int stmtCounters[] = this.tmp_stmtCounters.getArray(batchSize); for (int i = 0; i < batchSize; i++) { stmtCounters[i] = ts.updateStatementCounter(batchStmts[i].getStatement()); } // FOR if (ts.hasPrefetchQueries()) { PartitionSet stmtPartitions[] = plan.getStatementPartitions(); PrefetchState prefetchState = ts.getPrefetchState(); QueryTracker queryTracker = prefetchState.getExecQueryTracker(); assert(prefetchState != null); for (int i = 0; i < batchSize; i++) { // We always have to update the query tracker regardless of whether // the query was prefetched or not. This is so that we can ensure // that we execute the queries in the right order. Statement stmt = batchStmts[i].getStatement(); stmtCounters[i] = queryTracker.addQuery(stmt, stmtPartitions[i], batchParams[i]); } // FOR // FIXME PrefetchQueryUtil.checkSQLStmtBatch(this, ts, plan, batchSize, batchStmts, batchParams); } // PREFETCH VoltTable results[] = null; // FAST-PATH: Single-partition + Local // If the BatchPlan only has WorkFragments that are for this partition, then // we can use the fast-path executeLocalPlan() method if (plan.isSingledPartitionedAndLocal()) { if (trace.val) LOG.trace(String.format("%s - Sending %s directly to the ExecutionEngine at partition %d", ts, plan.getClass().getSimpleName(), this.partitionId)); // If this the finalTask flag is set to true, and we're only executing queries at this // partition, then we need to notify the other partitions that we're done with them. if (hstore_conf.site.exec_early_prepare && finalTask == true && ts.isPredictSinglePartition() == false && ts.isSysProc() == false && ts.allowEarlyPrepare() == true) { tmp_fragmentsPerPartition.clearValues(); tmp_fragmentsPerPartition.put(this.partitionId, batchSize); DonePartitionsNotification notify = this.computeDonePartitions(ts, null, tmp_fragmentsPerPartition, finalTask); if (notify != null && notify.hasSitesToNotify()) this.notifyDonePartitions(ts, notify); } // Execute the queries right away. results = this.executeLocalPlan(ts, plan, batchParams); } // DISTRIBUTED EXECUTION // Otherwise, we need to generate WorkFragments and then send the messages out // to our remote partitions using the HStoreCoordinator else { ExecutionState execState = ts.getExecutionState(); execState.tmp_partitionFragments.clear(); plan.getWorkFragmentsBuilders(ts.getTransactionId(), stmtCounters, execState.tmp_partitionFragments); if (debug.val) LOG.debug(String.format("%s - Using dispatchWorkFragments to execute %d %ss", ts, execState.tmp_partitionFragments.size(), WorkFragment.class.getSimpleName())); if (needs_profiling) { int remote_cnt = 0; PartitionSet stmtPartitions[] = plan.getStatementPartitions(); for (int i = 0; i < batchSize; i++) { if (stmtPartitions[i].get() != ts.getBasePartition()) remote_cnt++; if (trace.val) LOG.trace(String.format("%s - [%02d] stmt:%s / partitions:%s", ts, i, batchStmts[i].getStatement().getName(), stmtPartitions[i])); } // FOR if (trace.val) LOG.trace(String.format("%s - Remote Queries Count = %d", ts, remote_cnt)); ts.profiler.addRemoteQuery(remote_cnt); } // Block until we get all of our responses. results = this.dispatchWorkFragments(ts, batchSize, batchParams, execState.tmp_partitionFragments, finalTask); } if (debug.val && results == null) LOG.warn("Got back a null results array for " + ts + "\n" + plan.toString()); if (needs_profiling) ts.profiler.startExecJava(); return (results); } /** * * @param fresponse */ protected WorkResult buildWorkResult(AbstractTransaction ts, DependencySet result, Status status, SerializableException error) { WorkResult.Builder builder = WorkResult.newBuilder(); // Partition Id builder.setPartitionId(this.partitionId); // Status builder.setStatus(status); // SerializableException if (error != null) { int size = error.getSerializedSize(); BBContainer bc = this.buffer_pool.acquire(size); try { error.serializeToBuffer(bc.b); } catch (IOException ex) { String msg = "Failed to serialize error for " + ts; throw new ServerFaultException(msg, ex); } bc.b.rewind(); builder.setError(ByteString.copyFrom(bc.b)); bc.discard(); } // Push dependencies back to the remote partition that needs it if (status == Status.OK) { for (int i = 0, cnt = result.size(); i < cnt; i++) { builder.addDepId(result.depIds[i]); this.fs.clear(); try { result.dependencies[i].writeExternal(this.fs); ByteString bs = ByteString.copyFrom(this.fs.getBBContainer().b); builder.addDepData(bs); } catch (Exception ex) { throw new ServerFaultException(String.format("Failed to serialize output dependency %d for %s", result.depIds[i], ts), ex); } if (trace.val) LOG.trace(String.format("%s - Serialized Output Dependency %d\n%s", ts, result.depIds[i], result.dependencies[i])); } // FOR this.fs.getBBContainer().discard(); } return (builder.build()); } /** * This method is invoked when the PartitionExecutor wants to execute work at a remote HStoreSite. * The doneNotificationsPerSite is an array where each offset (based on SiteId) may contain * a PartitionSet of the partitions that this txn is finished with at the remote node and will * not be executing any work in the current batch. * @param ts * @param fragmentBuilders * @param parameterSets * @param doneNotificationsPerSite */ private void requestWork(LocalTransaction ts, Collection<WorkFragment.Builder> fragmentBuilders, List<ByteString> parameterSets, DonePartitionsNotification notify) { assert(fragmentBuilders.isEmpty() == false); assert(ts != null); Long txn_id = ts.getTransactionId(); if (trace.val) LOG.trace(String.format("%s - Wrapping %d %s into a %s", ts, fragmentBuilders.size(), WorkFragment.class.getSimpleName(), TransactionWorkRequest.class.getSimpleName())); // If our transaction was originally designated as a single-partitioned, then we need to make // sure that we don't touch any partition other than our local one. If we do, then we need abort // it and restart it as multi-partitioned boolean need_restart = false; boolean predict_singlepartition = ts.isPredictSinglePartition(); PartitionSet done_partitions = ts.getDonePartitions(); Estimate t_estimate = ts.getLastEstimate(); // Now we can go back through and start running all of the WorkFragments that were not blocked // waiting for an input dependency. Note that we pack all the fragments into a single // CoordinatorFragment rather than sending each WorkFragment in its own message for (WorkFragment.Builder fragmentBuilder : fragmentBuilders) { assert(this.depTracker.isBlocked(ts, fragmentBuilder) == false); final int target_partition = fragmentBuilder.getPartitionId(); final int target_site = catalogContext.getSiteIdForPartitionId(target_partition); final PartitionSet doneNotifications = (notify != null ? notify.getNotifications(target_site) : null); // Make sure that this isn't a single-partition txn trying to access a remote partition if (predict_singlepartition && target_partition != this.partitionId) { if (debug.val) LOG.debug(String.format("%s - Txn on partition %d is suppose to be " + "single-partitioned, but it wants to execute a fragment on partition %d", ts, this.partitionId, target_partition)); need_restart = true; break; } // Make sure that this txn isn't trying to access a partition that we said we were // done with earlier else if (done_partitions.contains(target_partition)) { if (debug.val) LOG.warn(String.format("%s on partition %d was marked as done on partition %d " + "but now it wants to go back for more!", ts, this.partitionId, target_partition)); need_restart = true; break; } // Make sure we at least have something to do! else if (fragmentBuilder.getFragmentIdCount() == 0) { LOG.warn(String.format("%s - Trying to send a WorkFragment request with 0 fragments", ts)); continue; } // Add in the specexec query estimate at this partition if needed if (hstore_conf.site.specexec_enable && t_estimate != null && t_estimate.hasQueryEstimate(target_partition)) { List<CountedStatement> queryEst = t_estimate.getQueryEstimate(target_partition); // if (debug.val) if (target_partition == 0) if (debug.val) LOG.debug(String.format("%s - Sending remote query estimate to partition %d " + "containing %d queries\n%s", ts, target_partition, queryEst.size(), StringUtil.join("\n", queryEst))); assert(queryEst.isEmpty() == false); QueryEstimate.Builder estBuilder = QueryEstimate.newBuilder(); for (CountedStatement countedStmt : queryEst) { estBuilder.addStmtIds(countedStmt.statement.getId()); estBuilder.addStmtCounters(countedStmt.counter); } // FOR fragmentBuilder.setFutureStatements(estBuilder); } // Get the TransactionWorkRequest.Builder for the remote HStoreSite // We will use this store our serialized input dependencies TransactionWorkRequestBuilder requestBuilder = tmp_transactionRequestBuilders[target_site]; if (requestBuilder == null) { requestBuilder = tmp_transactionRequestBuilders[target_site] = new TransactionWorkRequestBuilder(); } TransactionWorkRequest.Builder builder = requestBuilder.getBuilder(ts, doneNotifications); // Also keep track of what Statements they are executing so that we know // we need to send over the wire to them. requestBuilder.addParamIndexes(fragmentBuilder.getParamIndexList()); // Input Dependencies if (fragmentBuilder.getNeedsInput()) { if (debug.val) LOG.debug(String.format("%s - Retrieving input dependencies at partition %d", ts, this.partitionId)); tmp_removeDependenciesMap.clear(); for (int i = 0, cnt = fragmentBuilder.getInputDepIdCount(); i < cnt; i++) { this.getFragmentInputs(ts, fragmentBuilder.getInputDepId(i), tmp_removeDependenciesMap); } // FOR for (Entry<Integer, List<VoltTable>> e : tmp_removeDependenciesMap.entrySet()) { if (requestBuilder.hasInputDependencyId(e.getKey())) continue; if (debug.val) LOG.debug(String.format("%s - Attaching %d input dependencies to be sent to %s", ts, e.getValue().size(), HStoreThreadManager.formatSiteName(target_site))); for (VoltTable vt : e.getValue()) { this.fs.clear(); try { this.fs.writeObject(vt); builder.addAttachedDepId(e.getKey().intValue()); builder.addAttachedData(ByteString.copyFrom(this.fs.getBBContainer().b)); } catch (Exception ex) { String msg = String.format("Failed to serialize input dependency %d for %s", e.getKey(), ts); throw new ServerFaultException(msg, ts.getTransactionId()); } if (debug.val) LOG.debug(String.format("%s - Storing %d rows for InputDependency %d to send " + "to partition %d [bytes=%d]", ts, vt.getRowCount(), e.getKey(), fragmentBuilder.getPartitionId(), CollectionUtil.last(builder.getAttachedDataList()).size())); } // FOR requestBuilder.addInputDependencyId(e.getKey()); } // FOR this.fs.getBBContainer().discard(); } builder.addFragments(fragmentBuilder); } // FOR (tasks) // Bad mojo! We need to throw a MispredictionException so that the VoltProcedure // will catch it and we can propagate the error message all the way back to the HStoreSite if (need_restart) { if (trace.val) LOG.trace(String.format("Aborting %s because it was mispredicted", ts)); // This is kind of screwy because we don't actually want to send the touched partitions // histogram because VoltProcedure will just do it for us... throw new MispredictionException(txn_id, null); } // Stick on the ParameterSets that each site needs into the TransactionWorkRequest for (int target_site = 0; target_site < tmp_transactionRequestBuilders.length; target_site++) { TransactionWorkRequestBuilder builder = tmp_transactionRequestBuilders[target_site]; if (builder == null || builder.isDirty() == false) { continue; } assert(builder != null); builder.addParameterSets(parameterSets); // Bombs away! this.hstore_coordinator.transactionWork(ts, target_site, builder.build(), this.request_work_callback); if (debug.val) LOG.debug(String.format("%s - Sent Work request to remote site %s", ts, HStoreThreadManager.formatSiteName(target_site))); } // FOR } /** * Figure out what partitions this transaction is done with. This will only return * a PartitionSet of what partitions we think we're done with. * For each partition that we idenitfy that the txn is done with, we will check to see * whether the txn is going to execute a query at its site in this batch. If it's not, * then we will notify that HStoreSite through the HStoreCoordinator. * If the partition that it doesn't need anymore is local (i.e., it's at the same * HStoreSite that we're at right now), then we'll just pass them a quick message * to let them know that they can prepare the txn. * @param ts * @param estimate * @param fragmentsPerPartition A histogram of the number of PlanFragments the * txn will execute in this batch at each partition. * @param finalTask Whether the txn has marked this as the last batch that they will ever execute * @return A notification object that can be used to notify partitions that this txn is done with them. */ private DonePartitionsNotification computeDonePartitions(final LocalTransaction ts, final Estimate estimate, final FastIntHistogram fragmentsPerPartition, final boolean finalTask) { final PartitionSet touchedPartitions = ts.getPredictTouchedPartitions(); final PartitionSet donePartitions = ts.getDonePartitions(); // Compute the partitions that the txn will be finished with after this batch PartitionSet estDonePartitions = null; // If the finalTask flag is set to true, then the new done partitions // is every partition that this txn has locked if (finalTask) { estDonePartitions = new PartitionSet(touchedPartitions); } // Otherwise, we'll rely on the transaction's current estimate to figure it out. else { if (estimate == null || estimate.isValid() == false) { if (debug.val) LOG.debug(String.format("%s - Unable to compute new done partitions because there " + "is no valid estimate for the txn", ts, estimate.getClass().getSimpleName())); return (null); } estDonePartitions = estimate.getDonePartitions(this.thresholds); if (estDonePartitions == null || estDonePartitions.isEmpty()) { if (debug.val) LOG.debug(String.format("%s - There are no new done partitions identified by %s", ts, estimate.getClass().getSimpleName())); return (null); } } assert(estDonePartitions != null) : "Null done partitions for " + ts; assert(estDonePartitions.isEmpty() == false) : "Empty done partitions for " + ts; if (debug.val) LOG.debug(String.format("%s - New estimated done partitions %s%s", ts, estDonePartitions, (trace.val ? "\n"+estimate : ""))); // Note that we can actually be done with ourself, if this txn is only going to execute queries // at remote partitions. But we can't actually execute anything because this partition's only // execution thread is going to be blocked. So we always do this so that we're not sending a // useless message estDonePartitions.remove(this.partitionId); // Make sure that we only tell partitions that we actually touched, otherwise they will // be stuck waiting for a finish request that will never come! DonePartitionsNotification notify = new DonePartitionsNotification(); for (int partition : estDonePartitions.values()) { // Only mark the txn done at this partition if the Estimate says we were done // with it after executing this batch and it's a partition that we've locked. if (donePartitions.contains(partition) || touchedPartitions.contains(partition) == false) continue; if (trace.val) LOG.trace(String.format("%s - Marking partition %d as done for txn", ts, partition)); notify.donePartitions.add(partition); if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.markEarly2PCPartition(partition); // Check whether we're executing a query at this partition in this batch. // If we're not, then we need to check whether we can piggyback the "done" message // in another WorkFragment going to that partition or whether we have to // send a separate TransactionPrepareRequest if (fragmentsPerPartition.get(partition, 0) == 0) { // We need to let them know that the party is over! if (hstore_site.isLocalPartition(partition)) { // if (debug.val) LOG.info(String.format("%s - Notifying local partition %d that txn is finished it", ts, partition)); hstore_site.getPartitionExecutor(partition).queuePrepare(ts); } // Check whether we can piggyback on another WorkFragment that is going to // the same site else { Site remoteSite = catalogContext.getSiteForPartition(partition); boolean found = false; for (Partition remotePartition : remoteSite.getPartitions().values()) { if (fragmentsPerPartition.get(remotePartition.getId(), 0) != 0) { found = true; break; } } // FOR notify.addSiteNotification(remoteSite, partition, (found == false)); } } } // FOR return (notify); } /** * Send asynchronous notification messages to any remote site to tell them that we * are done with partitions that they have. * @param ts * @param notify */ private void notifyDonePartitions(LocalTransaction ts, DonePartitionsNotification notify) { // BLAST OUT NOTIFICATIONS! for (int remoteSiteId : notify._sitesToNotify) { assert(notify.notificationsPerSite[remoteSiteId] != null); if (debug.val) LOG.info(String.format("%s - Notifying %s that txn is finished with partitions %s", ts, HStoreThreadManager.formatSiteName(remoteSiteId), notify.notificationsPerSite[remoteSiteId])); hstore_coordinator.transactionPrepare(ts, ts.getPrepareCallback(), notify.notificationsPerSite[remoteSiteId]); // Make sure that we remove the PartitionSet for this site so that we don't // try to send the notifications again. notify.notificationsPerSite[remoteSiteId] = null; } // FOR } /** * Execute the given tasks and then block the current thread waiting for the list of dependency_ids to come * back from whatever it was we were suppose to do... * This is the slowest way to execute a bunch of WorkFragments and therefore should only be invoked * for batches that need to access non-local partitions * @param ts The txn handle that is executing this query batch * @param batchSize The number of SQLStmts that the txn queued up using voltQueueSQL() * @param batchParams The input parameters for the SQLStmts * @param allFragmentBuilders * @param finalTask Whether the txn has marked this as the last batch that they will ever execute * @return */ public VoltTable[] dispatchWorkFragments(final LocalTransaction ts, final int batchSize, final ParameterSet batchParams[], final Collection<WorkFragment.Builder> allFragmentBuilders, boolean finalTask) { assert(allFragmentBuilders.isEmpty() == false) : "Unexpected empty WorkFragment list for " + ts; final boolean needs_profiling = (hstore_conf.site.txn_profiling && ts.profiler != null); // *********************************** DEBUG *********************************** if (debug.val) { LOG.debug(String.format("%s - Preparing to dispatch %d messages and wait for the results [needsProfiling=%s]", ts, allFragmentBuilders.size(), needs_profiling)); if (trace.val) { StringBuilder sb = new StringBuilder(); sb.append(ts + " - WorkFragments:\n"); for (WorkFragment.Builder fragment : allFragmentBuilders) { sb.append(StringBoxUtil.box(fragment.toString()) + "\n"); } // FOR sb.append(ts + " - ParameterSets:\n"); for (ParameterSet ps : batchParams) { sb.append(ps + "\n"); } // FOR LOG.trace(sb); } } // *********************************** DEBUG *********************************** // OPTIONAL: Check to make sure that this request is valid // (1) At least one of the WorkFragments needs to be executed on a remote partition // (2) All of the PlanFragments ids in the WorkFragments match this txn's Procedure if (hstore_conf.site.exec_validate_work && ts.isSysProc() == false) { LOG.warn(String.format("%s - Checking whether all of the WorkFragments are valid", ts)); boolean has_remote = false; for (WorkFragment.Builder frag : allFragmentBuilders) { if (frag.getPartitionId() != this.partitionId) { has_remote = true; } for (int frag_id : frag.getFragmentIdList()) { PlanFragment catalog_frag = CatalogUtil.getPlanFragment(catalogContext.database, frag_id); Statement catalog_stmt = catalog_frag.getParent(); assert(catalog_stmt != null); Procedure catalog_proc = catalog_stmt.getParent(); if (catalog_proc.equals(ts.getProcedure()) == false) { LOG.warn(ts.debug() + "\n" + allFragmentBuilders + "\n---- INVALID ----\n" + frag); String msg = String.format("%s - Unexpected %s", ts, catalog_frag.fullName()); throw new ServerFaultException(msg, ts.getTransactionId()); } } } // FOR if (has_remote == false) { LOG.warn(ts.debug() + "\n" + allFragmentBuilders); String msg = ts + "Trying to execute all local single-partition queries using the slow-path!"; throw new ServerFaultException(msg, ts.getTransactionId()); } } boolean first = true; boolean serializedParams = false; CountDownLatch latch = null; boolean all_local = true; boolean is_localSite; boolean is_localPartition; boolean is_localReadOnly = true; int num_localPartition = 0; int num_localSite = 0; int num_remote = 0; int num_skipped = 0; int total = 0; Collection<WorkFragment.Builder> fragmentBuilders = allFragmentBuilders; // Make sure our txn is in our DependencyTracker if (trace.val) LOG.trace(String.format("%s - Added transaction to %s", ts, this.depTracker.getClass().getSimpleName())); this.depTracker.addTransaction(ts); // Count the number of fragments that we're going to send to each partition and // figure out whether the txn will always be read-only at this partition tmp_fragmentsPerPartition.clearValues(); for (WorkFragment.Builder fragmentBuilder : allFragmentBuilders) { int partition = fragmentBuilder.getPartitionId(); tmp_fragmentsPerPartition.put(partition); if (this.partitionId == partition && fragmentBuilder.getReadOnly() == false) { is_localReadOnly = false; } } // FOR long undoToken = this.calculateNextUndoToken(ts, is_localReadOnly); ts.initFirstRound(undoToken, batchSize); final boolean predict_singlePartition = ts.isPredictSinglePartition(); // Calculate whether we are finished with partitions now final Estimate lastEstimate = ts.getLastEstimate(); DonePartitionsNotification notify = null; if (hstore_conf.site.exec_early_prepare && ts.isSysProc() == false && ts.allowEarlyPrepare()) { notify = this.computeDonePartitions(ts, lastEstimate, tmp_fragmentsPerPartition, finalTask); if (notify != null && notify.hasSitesToNotify()) this.notifyDonePartitions(ts, notify); } // Attach the ParameterSets to our transaction handle so that anybody on this HStoreSite // can access them directly without needing to deserialize them from the WorkFragments ts.attachParameterSets(batchParams); // Now if we have some work sent out to other partitions, we need to wait until they come back // In the first part, we wait until all of our blocked WorkFragments become unblocked final BlockingDeque<Collection<WorkFragment.Builder>> queue = this.depTracker.getUnblockedWorkFragmentsQueue(ts); // Run through this loop if: // (1) We have no pending errors // (2) This is our first time in the loop (first == true) // (3) If we know that there are still messages being blocked // (4) If we know that there are still unblocked messages that we need to process // (5) The latch for this round is still greater than zero while (ts.hasPendingError() == false && (first == true || this.depTracker.stillHasWorkFragments(ts) || (latch != null && latch.getCount() > 0))) { if (trace.val) LOG.trace(String.format("%s - %s loop [first=%s, stillHasWorkFragments=%s, latch=%s]", ts, ClassUtil.getCurrentMethodName(), first, this.depTracker.stillHasWorkFragments(ts), queue.size(), latch)); // If this is the not first time through the loop, then poll the queue // to get our list of fragments if (first == false) { all_local = true; is_localSite = false; is_localPartition = false; num_localPartition = 0; num_localSite = 0; num_remote = 0; num_skipped = 0; total = 0; if (trace.val) LOG.trace(String.format("%s - Waiting for unblocked tasks on partition %d", ts, this.partitionId)); fragmentBuilders = queue.poll(); // NON-BLOCKING // If we didn't get back a list of fragments here, then we will spin through // and invoke utilityWork() to try to do something useful until what we need shows up if (needs_profiling) ts.profiler.startExecDtxnWork(); if (hstore_conf.site.exec_profiling) this.profiler.sp1_time.start(); try { while (fragmentBuilders == null) { // If there is more work that we could do, then we'll just poll the queue // without waiting so that we can go back and execute it again if we have // more time. if (this.utilityWork()) { fragmentBuilders = queue.poll(); } // Otherwise we will wait a little so that we don't spin the CPU else { fragmentBuilders = queue.poll(WORK_QUEUE_POLL_TIME, TimeUnit.MILLISECONDS); } } // WHILE } catch (InterruptedException ex) { if (this.hstore_site.isShuttingDown() == false) { LOG.error(String.format("%s - We were interrupted while waiting for blocked tasks", ts), ex); } return (null); } finally { if (needs_profiling) ts.profiler.stopExecDtxnWork(); if (hstore_conf.site.exec_profiling) this.profiler.sp1_time.stopIfStarted(); } } assert(fragmentBuilders != null); // If the list to fragments unblock is empty, then we // know that we have dispatched all of the WorkFragments for the // transaction's current SQLStmt batch. That means we can just wait // until all the results return to us. if (fragmentBuilders.isEmpty()) { if (trace.val) LOG.trace(String.format("%s - Got an empty list of WorkFragments at partition %d. " + "Blocking until dependencies arrive", ts, this.partitionId)); break; } this.tmp_localWorkFragmentBuilders.clear(); if (predict_singlePartition == false) { this.tmp_remoteFragmentBuilders.clear(); this.tmp_localSiteFragmentBuilders.clear(); } // ------------------------------- // FAST PATH: Assume everything is local // ------------------------------- if (predict_singlePartition) { for (WorkFragment.Builder fragmentBuilder : fragmentBuilders) { if (first == false || this.depTracker.addWorkFragment(ts, fragmentBuilder, batchParams)) { this.tmp_localWorkFragmentBuilders.add(fragmentBuilder); total++; num_localPartition++; } } // FOR // We have to tell the transaction handle to start the round before we send off the // WorkFragments for execution, since they might start executing locally! if (first) { ts.startRound(this.partitionId); latch = this.depTracker.getDependencyLatch(ts); } // Execute all of our WorkFragments quickly at our local ExecutionEngine for (WorkFragment.Builder fragmentBuilder : this.tmp_localWorkFragmentBuilders) { if (debug.val) LOG.debug(String.format("%s - Got unblocked %s to execute locally", ts, fragmentBuilder.getClass().getSimpleName())); assert(fragmentBuilder.getPartitionId() == this.partitionId) : String.format("Trying to process %s for %s on partition %d but it should have been " + "sent to partition %d [singlePartition=%s]\n%s", fragmentBuilder.getClass().getSimpleName(), ts, this.partitionId, fragmentBuilder.getPartitionId(), predict_singlePartition, fragmentBuilder); WorkFragment fragment = fragmentBuilder.build(); this.processWorkFragment(ts, fragment, batchParams); } // FOR } // ------------------------------- // SLOW PATH: Mixed local and remote messages // ------------------------------- else { // Look at each task and figure out whether it needs to be executed at a remote // HStoreSite or whether we can execute it at one of our local PartitionExecutors. for (WorkFragment.Builder fragmentBuilder : fragmentBuilders) { int partition = fragmentBuilder.getPartitionId(); is_localSite = hstore_site.isLocalPartition(partition); is_localPartition = (partition == this.partitionId); all_local = all_local && is_localPartition; // If this is the last WorkFragment that we're going to send to this partition for // this batch, then we will want to check whether we know that this is the last // time this txn will ever need to go to that txn. If so, then we'll want to if (notify != null && notify.donePartitions.contains(partition) && tmp_fragmentsPerPartition.dec(partition) == 0) { if (debug.val) LOG.debug(String.format("%s - Setting last fragment flag in %s for partition %d", ts, WorkFragment.class.getSimpleName(), partition)); fragmentBuilder.setLastFragment(true); } if (first == false || this.depTracker.addWorkFragment(ts, fragmentBuilder, batchParams)) { total++; // At this point we know that all the WorkFragment has been registered // in the LocalTransaction, so then it's safe for us to look to see // whether we already have a prefetched result that we need // if (prefetch && is_localPartition == false) { // boolean skip_queue = true; // for (int i = 0, cnt = fragmentBuilder.getFragmentIdCount(); i < cnt; i++) { // int fragId = fragmentBuilder.getFragmentId(i); // int paramIdx = fragmentBuilder.getParamIndex(i); // // VoltTable vt = this.queryCache.getResult(ts.getTransactionId(), // fragId, // partition, // parameters[paramIdx]); // if (vt != null) { // if (trace.val) // LOG.trace(String.format("%s - Storing cached result from partition %d for fragment %d", // ts, partition, fragId)); // this.depTracker.addResult(ts, partition, fragmentBuilder.getOutputDepId(i), vt); // } else { // skip_queue = false; // } // } // FOR // // If we were able to get cached results for all of the fragmentIds in // // this WorkFragment, then there is no need for us to send the message // // So we'll just skip queuing it up! How nice! // if (skip_queue) { // if (debug.val) // LOG.debug(String.format("%s - Using prefetch result for all fragments from partition %d", // ts, partition)); // num_skipped++; // continue; // } // } // Otherwise add it to our list of WorkFragments that we want // queue up right now if (is_localPartition) { is_localReadOnly = (is_localReadOnly && fragmentBuilder.getReadOnly()); this.tmp_localWorkFragmentBuilders.add(fragmentBuilder); num_localPartition++; } else if (is_localSite) { this.tmp_localSiteFragmentBuilders.add(fragmentBuilder); num_localSite++; } else { this.tmp_remoteFragmentBuilders.add(fragmentBuilder); num_remote++; } } } // FOR assert(total == (num_remote + num_localSite + num_localPartition + num_skipped)) : String.format("Total:%d / Remote:%d / LocalSite:%d / LocalPartition:%d / Skipped:%d", total, num_remote, num_localSite, num_localPartition, num_skipped); // We have to tell the txn to start the round before we send off the // WorkFragments for execution, since they might start executing locally! if (first) { ts.startRound(this.partitionId); latch = this.depTracker.getDependencyLatch(ts); } // Now request the fragments that aren't local // We want to push these out as soon as possible if (num_remote > 0) { // We only need to serialize the ParameterSets once if (serializedParams == false) { if (needs_profiling) ts.profiler.startSerialization(); tmp_serializedParams.clear(); for (int i = 0; i < batchParams.length; i++) { if (batchParams[i] == null) { tmp_serializedParams.add(ByteString.EMPTY); } else { this.fs.clear(); try { batchParams[i].writeExternal(this.fs); ByteString bs = ByteString.copyFrom(this.fs.getBBContainer().b); tmp_serializedParams.add(bs); } catch (Exception ex) { String msg = "Failed to serialize ParameterSet " + i + " for " + ts; throw new ServerFaultException(msg, ex, ts.getTransactionId()); } } } // FOR if (needs_profiling) ts.profiler.stopSerialization(); } if (trace.val) LOG.trace(String.format("%s - Requesting %d %s to be executed on remote partitions " + "[doneNotifications=%s]", ts, WorkFragment.class.getSimpleName(), num_remote, notify!=null)); this.requestWork(ts, tmp_remoteFragmentBuilders, tmp_serializedParams, notify); if (needs_profiling) ts.profiler.markRemoteQuery(); } // Then dispatch the task that are needed at the same HStoreSite but // at a different partition than this one if (num_localSite > 0) { if (trace.val) LOG.trace(String.format("%s - Executing %d WorkFragments on local site's partitions", ts, num_localSite)); for (WorkFragment.Builder builder : this.tmp_localSiteFragmentBuilders) { PartitionExecutor other = hstore_site.getPartitionExecutor(builder.getPartitionId()); other.queueWork(ts, builder.build()); } // FOR if (needs_profiling) ts.profiler.markRemoteQuery(); } // Then execute all of the tasks need to access the partitions at this HStoreSite // We'll dispatch the remote-partition-local-site fragments first because they're going // to need to get queued up by at the other PartitionExecutors if (num_localPartition > 0) { if (trace.val) LOG.trace(String.format("%s - Executing %d WorkFragments on local partition", ts, num_localPartition)); for (WorkFragment.Builder fragmentBuilder : this.tmp_localWorkFragmentBuilders) { this.processWorkFragment(ts, fragmentBuilder.build(), batchParams); } // FOR } } if (trace.val) LOG.trace(String.format("%s - Dispatched %d WorkFragments " + "[remoteSite=%d, localSite=%d, localPartition=%d]", ts, total, num_remote, num_localSite, num_localPartition)); first = false; } // WHILE this.fs.getBBContainer().discard(); if (trace.val) LOG.trace(String.format("%s - BREAK OUT [first=%s, stillHasWorkFragments=%s, latch=%s]", ts, first, this.depTracker.stillHasWorkFragments(ts), latch)); // assert(ts.stillHasWorkFragments() == false) : // String.format("Trying to block %s before all of its WorkFragments have been dispatched!\n%s\n%s", // ts, // StringUtil.join("** ", "\n", tempDebug), // this.getVoltProcedure(ts.getProcedureName()).getLastBatchPlan()); // Now that we know all of our WorkFragments have been dispatched, we can then // wait for all of the results to come back in. if (latch == null) latch = this.depTracker.getDependencyLatch(ts); assert(latch != null) : String.format("Unexpected null dependency latch for " + ts); if (latch.getCount() > 0) { if (debug.val) { LOG.debug(String.format("%s - All blocked messages dispatched. Waiting for %d dependencies", ts, latch.getCount())); if (trace.val) LOG.trace(ts.toString()); } boolean timeout = false; long startTime = EstTime.currentTimeMillis(); if (needs_profiling) ts.profiler.startExecDtxnWork(); if (hstore_conf.site.exec_profiling) this.profiler.sp1_time.start(); try { while (latch.getCount() > 0 && ts.hasPendingError() == false) { if (this.utilityWork() == false) { timeout = latch.await(WORK_QUEUE_POLL_TIME, TimeUnit.MILLISECONDS); if (timeout == false) break; } if ((EstTime.currentTimeMillis() - startTime) > hstore_conf.site.exec_response_timeout) { timeout = true; break; } } // WHILE } catch (InterruptedException ex) { if (this.hstore_site.isShuttingDown() == false) { LOG.error(String.format("%s - We were interrupted while waiting for results", ts), ex); } timeout = true; } catch (Throwable ex) { String msg = String.format("Fatal error for %s while waiting for results", ts); throw new ServerFaultException(msg, ex); } finally { if (needs_profiling) ts.profiler.stopExecDtxnWork(); if (hstore_conf.site.exec_profiling) this.profiler.sp1_time.stopIfStarted(); } if (timeout && this.isShuttingDown() == false) { LOG.warn(String.format("Still waiting for responses for %s after %d ms [latch=%d]\n%s", ts, hstore_conf.site.exec_response_timeout, latch.getCount(), ts.debug())); LOG.warn("Procedure Parameters:\n" + ts.getProcedureParameters()); hstore_conf.site.exec_profiling = true; LOG.warn(hstore_site.statusSnapshot()); String msg = "The query responses for " + ts + " never arrived!"; throw new ServerFaultException(msg, ts.getTransactionId()); } } // Update done partitions if (notify != null && notify.donePartitions.isEmpty() == false) { if (debug.val) LOG.debug(String.format("%s - Marking new done partitions %s", ts, notify.donePartitions)); ts.getDonePartitions().addAll(notify.donePartitions); } // IMPORTANT: Check whether the fragments failed somewhere and we got a response with an error // We will rethrow this so that it pops the stack all the way back to VoltProcedure.call() // where we can generate a message to the client if (ts.hasPendingError()) { if (debug.val) LOG.warn(String.format("%s was hit with a %s", ts, ts.getPendingError().getClass().getSimpleName())); throw ts.getPendingError(); } // IMPORTANT: Don't try to check whether we got back the right number of tables because the batch // may have hit an error and we didn't execute all of them. VoltTable results[] = null; try { results = this.depTracker.getResults(ts); } catch (AssertionError ex) { LOG.error("Failed to get final results for batch\n" + ts.debug()); throw ex; } ts.finishRound(this.partitionId); if (debug.val) { if (trace.val) LOG.trace(ts + " is now running and looking for love in all the wrong places..."); LOG.debug(String.format("%s - Returning back %d tables to VoltProcedure", ts, results.length)); } return (results); } // --------------------------------------------------------------- // COMMIT + ABORT METHODS // --------------------------------------------------------------- /** * Queue a speculatively executed transaction to send its ClientResponseImpl message */ private void blockClientResponse(LocalTransaction ts, ClientResponseImpl cresponse) { assert(ts.isPredictSinglePartition() == true) : String.format("Specutatively executed multi-partition %s [mode=%s, status=%s]", ts, this.currentExecMode, cresponse.getStatus()); assert(ts.isSpeculative() == true) : String.format("Blocking ClientResponse for non-specutative %s [mode=%s, status=%s]", ts, this.currentExecMode, cresponse.getStatus()); assert(cresponse.getStatus() != Status.ABORT_MISPREDICT) : String.format("Trying to block ClientResponse for mispredicted %s [mode=%s, status=%s]", ts, this.currentExecMode, cresponse.getStatus()); assert(this.currentExecMode != ExecutionMode.COMMIT_ALL) : String.format("Blocking ClientResponse for %s when in non-specutative mode [mode=%s, status=%s]", ts, this.currentExecMode, cresponse.getStatus()); this.specExecBlocked.push(Pair.of(ts, cresponse)); this.specExecModified = this.specExecModified && ts.isExecReadOnly(this.partitionId); if (debug.val) LOG.debug(String.format("%s - Blocking %s ClientResponse [partitions=%s, blockQueue=%d]", ts, cresponse.getStatus(), ts.getTouchedPartitions().values(), this.specExecBlocked.size())); } /** * For the given transaction's ClientResponse, figure out whether we can send it back to the client * right now or whether we need to initiate two-phase commit. * @param ts * @param cresponse */ protected void processClientResponse(LocalTransaction ts, ClientResponseImpl cresponse) { // IMPORTANT: If we executed this locally and only touched our partition, then we need to commit/abort right here // 2010-11-14: The reason why we can do this is because we will just ignore the commit // message when it shows from the Dtxn.Coordinator. We should probably double check with Evan on this... Status status = cresponse.getStatus(); if (debug.val) { LOG.debug(String.format("%s - Processing ClientResponse at partition %d " + "[status=%s, singlePartition=%s, local=%s, clientHandle=%d]", ts, this.partitionId, status, ts.isPredictSinglePartition(), ts.isExecLocal(this.partitionId), cresponse.getClientHandle())); if (trace.val) { LOG.trace(ts + " Touched Partitions: " + ts.getTouchedPartitions().values()); if (ts.isPredictSinglePartition() == false) LOG.trace(ts + " Done Partitions: " + ts.getDonePartitions()); } } // ------------------------------- // ALL: Transactions that need to be internally restarted // ------------------------------- if (status == Status.ABORT_MISPREDICT || status == Status.ABORT_SPECULATIVE || status == Status.ABORT_EVICTEDACCESS) { // If the txn was mispredicted, then we will pass the information over to the // HStoreSite so that it can re-execute the transaction. We want to do this // first so that the txn gets re-executed as soon as possible... if (debug.val) LOG.debug(String.format("%s - Restarting because transaction was hit with %s", ts, (ts.getPendingError() != null ? ts.getPendingError().getClass().getSimpleName() : ""))); // We don't want to delete the transaction here because whoever is going to requeue it for // us will need to know what partitions that the transaction touched when it executed before if (ts.isPredictSinglePartition()) { this.finishTransaction(ts, status); this.hstore_site.transactionRequeue(ts, status); } // Send a message all the partitions involved that the party is over // and that they need to abort the transaction. We don't actually care when we get the // results back because we'll start working on new txns right away. // Note that when we call transactionFinish() right here this thread will then go on // to invoke HStoreSite.transactionFinish() for us. That means when it returns we will // have successfully aborted the txn at least at all of the local partitions at this site. else { if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.startPostFinish(); LocalFinishCallback finish_callback = ts.getFinishCallback(); finish_callback.init(ts, status); finish_callback.markForRequeue(); if (hstore_conf.site.exec_profiling) this.profiler.network_time.start(); this.hstore_coordinator.transactionFinish(ts, status, finish_callback); if (hstore_conf.site.exec_profiling) this.profiler.network_time.stopIfStarted(); } } // ------------------------------- // ALL: Single-Partition Transactions // ------------------------------- else if (ts.isPredictSinglePartition()) { // Commit or abort the transaction only if we haven't done it already // This can happen when we commit speculative txns out of order if (ts.isMarkedFinished(this.partitionId) == false) { this.finishTransaction(ts, status); } // We have to mark it as loggable to prevent the response // from getting sent back to the client if (hstore_conf.site.commandlog_enable) ts.markLogEnabled(); if (hstore_conf.site.exec_profiling) this.profiler.network_time.start(); this.hstore_site.responseSend(ts, cresponse); if (hstore_conf.site.exec_profiling) this.profiler.network_time.stopIfStarted(); this.hstore_site.queueDeleteTransaction(ts.getTransactionId(), status); } // ------------------------------- // COMMIT: Distributed Transaction // ------------------------------- else if (status == Status.OK) { // We need to set the new ExecutionMode before we invoke transactionPrepare // because the LocalTransaction handle might get cleaned up immediately ExecutionMode newMode = null; if (hstore_conf.site.specexec_enable) { newMode = (ts.isExecReadOnly(this.partitionId) ? ExecutionMode.COMMIT_READONLY : ExecutionMode.COMMIT_NONE); } else { newMode = ExecutionMode.DISABLED; } this.setExecutionMode(ts, newMode); // We have to send a prepare message to all of our remote HStoreSites // We want to make sure that we don't go back to ones that we've already told PartitionSet donePartitions = ts.getDonePartitions(); PartitionSet notifyPartitions = new PartitionSet(); for (int partition : ts.getPredictTouchedPartitions().values()) { if (donePartitions.contains(partition) == false) { notifyPartitions.add(partition); } } // FOR if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.startPostPrepare(); ts.setClientResponse(cresponse); if (hstore_conf.site.exec_profiling) { this.profiler.network_time.start(); this.profiler.sp3_local_time.start(); } LocalPrepareCallback callback = ts.getPrepareCallback(); callback.init(ts, notifyPartitions); this.hstore_coordinator.transactionPrepare(ts, callback, notifyPartitions); if (hstore_conf.site.exec_profiling) this.profiler.network_time.stopIfStarted(); } // ------------------------------- // ABORT: Distributed Transaction // ------------------------------- else { // Send back the result to the client right now, since there's no way // that we're magically going to be able to recover this and get them a result // This has to come before the network messages above because this will clean-up the // LocalTransaction state information this.hstore_site.responseSend(ts, cresponse); // Send a message all the partitions involved that the party is over // and that they need to abort the transaction. We don't actually care when we get the // results back because we'll start working on new txns right away. // Note that when we call transactionFinish() right here this thread will then go on // to invoke HStoreSite.transactionFinish() for us. That means when it returns we will // have successfully aborted the txn at least at all of the local partitions at this site. if (hstore_conf.site.txn_profiling && ts.profiler != null) ts.profiler.startPostFinish(); LocalFinishCallback callback = ts.getFinishCallback(); callback.init(ts, status); if (hstore_conf.site.exec_profiling) this.profiler.network_time.start(); try { this.hstore_coordinator.transactionFinish(ts, status, callback); } finally { if (hstore_conf.site.exec_profiling) this.profiler.network_time.stopIfStarted(); } } } /** * Enable speculative execution mode for this partition. The given transaction is * the one that we will need to wait to finish before we can release the ClientResponses * for any speculatively executed transactions. * @param txn_id * @return true if speculative execution was enabled at this partition */ private Status prepareTransaction(AbstractTransaction ts) { assert(ts != null) : "Unexpected null transaction handle at partition " + this.partitionId; assert(ts.isInitialized()) : String.format("Trying to prepare uninitialized transaction %s at partition %d", ts, this.partitionId); assert(ts.isMarkedFinished(this.partitionId) == false) : String.format("Trying to prepare %s again after it was already finished at partition %d", ts, this.partitionId); Status status = Status.OK; // Skip if we've already invoked prepared for this txn at this partition if (ts.isMarkedPrepared(this.partitionId) == false) { if (debug.val) LOG.debug(String.format("%s - Preparing to commit txn at partition %d [specBlocked=%d]", ts, this.partitionId, this.specExecBlocked.size())); ExecutionMode newMode = ExecutionMode.COMMIT_NONE; if (hstore_conf.site.exec_profiling && this.partitionId != ts.getBasePartition() && ts.needsFinish(this.partitionId)) { profiler.sp3_remote_time.start(); } if (hstore_conf.site.specexec_enable) { // Check to see if there were any conflicts with the dtxn and any of its speculative // txns at this partition. If there were, then we know that we can't commit the txn here. LocalTransaction spec_ts; for (Pair<LocalTransaction, ClientResponseImpl> pair : this.specExecBlocked) { spec_ts = pair.getFirst(); if (debug.val) LOG.debug(String.format("%s - Checking for conflicts with speculative %s at partition %d [%s]", ts, spec_ts, this.partitionId, this.specExecChecker.getClass().getSimpleName())); if (this.specExecChecker.hasConflictAfter(ts, spec_ts, this.partitionId)) { if (debug.val) LOG.debug(String.format("%s - Conflict found with speculative txn %s at partition %d", ts, spec_ts, this.partitionId)); status = Status.ABORT_RESTART; break; } } // FOR // Check whether the txn that we're waiting for is read-only. // If it is, then that means all read-only transactions can commit right away if (status == Status.OK && ts.isExecReadOnly(this.partitionId)) { if (debug.val) LOG.debug(String.format("%s - Txn is read-only at partition %d [readOnly=%s]", ts, this.partitionId, ts.isExecReadOnly(this.partitionId))); newMode = ExecutionMode.COMMIT_READONLY; } } if (this.currentDtxn != null) this.setExecutionMode(ts, newMode); } // It's ok if they try to prepare the txn twice. That might just mean that they never // got the acknowledgement back in time if they tried to send an early commit message. else if (debug.val) { LOG.debug(String.format("%s - Already marked 2PC:PREPARE at partition %d", ts, this.partitionId)); } // IMPORTANT // When we do an early 2PC-PREPARE, we won't have this callback ready // because we don't know what callback to use to send the acknowledgements // back over the network PartitionCountingCallback<AbstractTransaction> callback = ts.getPrepareCallback(); if (status == Status.OK) { if (callback.isInitialized()) { try { callback.run(this.partitionId); } catch (Throwable ex) { LOG.warn("Unexpected error for " + ts, ex); } } // But we will always mark ourselves as prepared at this partition ts.markPrepared(this.partitionId); } else { if (debug.val) LOG.debug(String.format("%s - Aborting txn from partition %d [%s]", ts, this.partitionId, status)); callback.abort(this.partitionId, status); } return (status); } /** * Internal call to abort/commit the transaction down in the execution engine * @param ts * @param commit */ private void finishTransaction(AbstractTransaction ts, Status status) { assert(ts != null) : "Unexpected null transaction handle at partition " + this.partitionId; assert(ts.isInitialized()) : String.format("Trying to commit uninitialized transaction %s at partition %d", ts, this.partitionId); assert(ts.isMarkedFinished(this.partitionId) == false) : String.format("Trying to commit %s twice at partition %d", ts, this.partitionId); // This can be null if they haven't submitted anything boolean commit = (status == Status.OK); long undoToken = (commit ? ts.getLastUndoToken(this.partitionId) : ts.getFirstUndoToken(this.partitionId)); // Only commit/abort this transaction if: // (2) We have the last undo token used by this transaction // (3) The transaction was executed with undo buffers // (4) The transaction actually submitted work to the EE // (5) The transaction modified data at this partition if (ts.needsFinish(this.partitionId) && undoToken != HStoreConstants.NULL_UNDO_LOGGING_TOKEN) { if (trace.val) LOG.trace(String.format("%s - Invoking EE to finish work for txn [%s / speculative=%s]", ts, status, ts.isSpeculative())); this.finishWorkEE(ts, undoToken, commit); } // We always need to do the following things regardless if we hit up the EE or not if (commit) this.lastCommittedTxnId = ts.getTransactionId(); if (trace.val) LOG.trace(String.format("%s - Telling queue manager that txn is finished at partition %d", ts, this.partitionId)); this.queueManager.lockQueueFinished(ts, status, this.partitionId); if (debug.val) LOG.debug(String.format("%s - Successfully %sed transaction at partition %d", ts, (commit ? "committ" : "abort"), this.partitionId)); ts.markFinished(this.partitionId); } /** * The real method that actually reaches down into the EE and commits/undos the changes * for the given token. * Unless you know what you're doing, you probably want to be calling finishTransaction() * instead of calling this directly. * @param ts * @param undoToken * @param commit */ private void finishWorkEE(AbstractTransaction ts, long undoToken, boolean commit) { assert(ts.isMarkedFinished(this.partitionId) == false) : String.format("Trying to commit %s twice at partition %d", ts, this.partitionId); // If the txn is completely read-only and they didn't use undo-logging, then // there is nothing that we need to do, except to check to make sure we aren't // trying to abort this txn if (undoToken == HStoreConstants.DISABLE_UNDO_LOGGING_TOKEN) { // SANITY CHECK: Make sure that they're not trying to undo a transaction that // modified the database but did not use undo logging if (ts.isExecReadOnly(this.partitionId) == false && commit == false) { String msg = String.format("TRYING TO ABORT TRANSACTION ON PARTITION %d WITHOUT UNDO LOGGING [undoToken=%d]", this.partitionId, undoToken); LOG.fatal(msg + "\n" + ts.debug()); this.crash(new ServerFaultException(msg, ts.getTransactionId())); } if (debug.val) LOG.debug(String.format("%s - undoToken == DISABLE_UNDO_LOGGING_TOKEN", ts)); } // COMMIT / ABORT else { boolean needs_profiling = false; if (hstore_conf.site.txn_profiling && ts.isExecLocal(this.partitionId) && ((LocalTransaction)ts).profiler != null) { needs_profiling = true; ((LocalTransaction)ts).profiler.startPostEE(); } assert(this.lastCommittedUndoToken != undoToken) : String.format("Trying to %s undoToken %d for %s twice at partition %d", (commit ? "COMMIT" : "ABORT"), undoToken, ts, this.partitionId); // COMMIT! if (commit) { if (debug.val) { LOG.debug(String.format("%s - COMMITING txn on partition %d with undoToken %d " + "[lastTxnId=%d, lastUndoToken=%d, dtxn=%s]%s", ts, this.partitionId, undoToken, this.lastCommittedTxnId, this.lastCommittedUndoToken, this.currentDtxn, (ts instanceof LocalTransaction ? " - " + ((LocalTransaction)ts).getSpeculationType() : ""))); if (this.specExecBlocked.isEmpty() == false && ts.isPredictSinglePartition() == false) { LOG.debug(String.format("%s - # of Speculatively Executed Txns: %d ", ts, this.specExecBlocked.size())); } } assert(this.lastCommittedUndoToken < undoToken) : String.format("Trying to commit undoToken %d for %s but it is less than the " + "last committed undoToken %d at partition %d\n" + "Last Committed Txn: %d", undoToken, ts, this.lastCommittedUndoToken, this.partitionId, this.lastCommittedTxnId); this.ee.releaseUndoToken(undoToken); this.lastCommittedUndoToken = undoToken; } // ABORT! else { // Evan says that txns will be aborted LIFO. This means the first txn that // we get in abortWork() will have a the greatest undoToken, which means that // it will automagically rollback all other outstanding txns. // I'm lazy/tired, so for now I'll just rollback everything I get, but in theory // we should be able to check whether our undoToken has already been rolled back if (debug.val) { LOG.debug(String.format("%s - ABORTING txn on partition %d with undoToken %d " + "[lastTxnId=%d, lastUndoToken=%d, dtxn=%s]%s", ts, this.partitionId, undoToken, this.lastCommittedTxnId, this.lastCommittedUndoToken, this.currentDtxn, (ts instanceof LocalTransaction ? " - " + ((LocalTransaction)ts).getSpeculationType() : ""))); if (this.specExecBlocked.isEmpty() == false && ts.isPredictSinglePartition() == false) { LOG.debug(String.format("%s - # of Speculatively Executed Txns: %d ", ts, this.specExecBlocked.size())); } } assert(this.lastCommittedUndoToken < undoToken) : String.format("Trying to abort undoToken %d for %s but it is less than the " + "last committed undoToken %d at partition %d " + "[lastTxnId=%d, lastUndoToken=%d, dtxn=%s]%s", undoToken, ts, this.lastCommittedUndoToken, this.partitionId, this.lastCommittedTxnId, this.lastCommittedUndoToken, this.currentDtxn, (ts instanceof LocalTransaction ? " - " + ((LocalTransaction)ts).getSpeculationType() : "")); this.ee.undoUndoToken(undoToken); } if (needs_profiling) ((LocalTransaction)ts).profiler.stopPostEE(); } } /** * Somebody told us that our partition needs to abort/commit the given transaction id. * This method should only be used for distributed transactions, because * it will do some extra work for speculative execution * @param ts - The transaction to finish up. * @param status - The final status of the transaction */ private void finishDistributedTransaction(final AbstractTransaction ts, final Status status) { if (debug.val) LOG.debug(String.format("%s - Processing finish request at partition %d " + "[status=%s, readOnly=%s]", ts, this.partitionId, status, ts.isExecReadOnly(this.partitionId))); if (this.currentDtxn == ts) { // 2012-11-22 -- Yes, today is Thanksgiving and I'm working on my database. // That's just grad student life I guess. Anyway, if you're reading this then // you know that this is an important part of the system. We have a dtxn that // we have been told is completely finished and now we need to either commit // or abort any changes that it may have made at this partition. The tricky thing // is that if we have speculative execution enabled, then we need to make sure // that we process any transactions that were executed while the dtxn was running // in the right order to ensure that we maintain serializability. // Here is the basic logic of what's about to happen: // // (1) If the dtxn is commiting, then we just need to commit the the last txn that // was executed (since this will have the largest undo token). // The EE will automatically commit all undo tokens less than that. // (2) If the dtxn is aborting, then we can commit any speculative txn that was // executed before the dtxn's first non-readonly undo token. // // Note that none of the speculative txns in the blocked queue will need to be // aborted at this point, because we will have rolled back their changes immediately // when they aborted, so that our dtxn doesn't read dirty data. if (this.specExecBlocked.isEmpty() == false) { // First thing we need to do is get the latch that will be set by any transaction // that was in the middle of being executed when we were called if (debug.val) LOG.debug(String.format("%s - Checking %d blocked speculative transactions at " + "partition %d [currentMode=%s]", ts, this.specExecBlocked.size(), this.partitionId, this.currentExecMode)); LocalTransaction spec_ts = null; ClientResponseImpl spec_cr = null; // ------------------------------- // DTXN NON-READ-ONLY ABORT // If the dtxn did not modify this partition, then everthing can commit // Otherwise, we want to commit anything that was executed before the dtxn started // ------------------------------- if (status != Status.OK && ts.isExecReadOnly(this.partitionId) == false) { // We need to get the first undo tokens for our distributed transaction long dtxnUndoToken = ts.getFirstUndoToken(this.partitionId); if (debug.val) LOG.debug(String.format("%s - Looking for speculative txns to commit before we rollback undoToken %d", ts, dtxnUndoToken)); // Queue of speculative txns that need to be committed. final Queue<Pair<LocalTransaction, ClientResponseImpl>> txnsToCommit = new LinkedList<Pair<LocalTransaction,ClientResponseImpl>>(); // Queue of speculative txns that need to be aborted + restarted final Queue<Pair<LocalTransaction, ClientResponseImpl>> txnsToRestart = new LinkedList<Pair<LocalTransaction,ClientResponseImpl>>(); long spec_token; long max_token = HStoreConstants.NULL_UNDO_LOGGING_TOKEN; LocalTransaction max_ts = null; for (Pair<LocalTransaction, ClientResponseImpl> pair : this.specExecBlocked) { boolean shouldCommit = false; spec_ts = pair.getFirst(); spec_token = spec_ts.getFirstUndoToken(this.partitionId); if (debug.val) LOG.debug(String.format("Speculative Txn %s [undoToken=%d, %s]", spec_ts, spec_token, spec_ts.getSpeculationType())); // Speculative txns should never be executed without an undo token assert(spec_token != HStoreConstants.DISABLE_UNDO_LOGGING_TOKEN); assert(spec_ts.isSpeculative()) : spec_ts + " isn't marked as speculative!"; // If the speculative undoToken is null, then this txn didn't execute // any queries. That means we can always commit it if (spec_token == HStoreConstants.NULL_UNDO_LOGGING_TOKEN) { if (debug.val) LOG.debug(String.format("Speculative Txn %s has a null undoToken at partition %d", spec_ts, this.partitionId)); shouldCommit = true; } // Otherwise, look to see if this txn was speculatively executed before the // first undo token of the distributed txn. That means we know that this guy // didn't read any modifications made by the dtxn. else if (spec_token < dtxnUndoToken) { if (debug.val) LOG.debug(String.format("Speculative Txn %s has an undoToken less than the dtxn %s " + "at partition %d [%d < %d]", spec_ts, ts, this.partitionId, spec_token, dtxnUndoToken)); shouldCommit = true; } // Ok so at this point we know that our spec txn came *after* the distributed txn // started. So we need to use our checker to see whether there is a conflict else if (this.specExecChecker.hasConflictAfter(ts, spec_ts, this.partitionId) == false) { if (debug.val) LOG.debug(String.format("Speculative Txn %s does not conflict with dtxn %s at partition %d", spec_ts, ts, this.partitionId)); shouldCommit = true; } if (shouldCommit) { txnsToCommit.add(pair); if (spec_token != HStoreConstants.NULL_UNDO_LOGGING_TOKEN && spec_token > max_token) { max_token = spec_token; max_ts = spec_ts; } } else { txnsToRestart.add(pair); } } // FOR if (debug.val) LOG.debug(String.format("%s - Found %d speculative txns at partition %d that need to be " + "committed *before* we abort this txn", ts, txnsToCommit.size(), this.partitionId)); // (1) Commit the greatest token that we've seen. This means that // all our other txns can be safely processed without needing // to go down in the EE if (max_token != HStoreConstants.NULL_UNDO_LOGGING_TOKEN) { assert(max_ts != null); this.finishWorkEE(max_ts, max_token, true); } // (2) Process all the txns that need to be committed Pair<LocalTransaction, ClientResponseImpl> pair = null; while ((pair = txnsToCommit.poll()) != null) { spec_ts = pair.getFirst(); spec_cr = pair.getSecond(); spec_ts.markFinished(this.partitionId); try { if (debug.val) LOG.debug(String.format("%s - Releasing blocked ClientResponse for %s [status=%s]", ts, spec_ts, spec_cr.getStatus())); this.processClientResponse(spec_ts, spec_cr); } catch (Throwable ex) { String msg = "Failed to complete queued response for " + spec_ts; throw new ServerFaultException(msg, ex, ts.getTransactionId()); } } // FOR // (3) Abort the distributed txn this.finishTransaction(ts, status); // (4) Restart all the other txns while ((pair = txnsToRestart.poll()) != null) { spec_ts = pair.getFirst(); spec_cr = pair.getSecond(); MispredictionException error = new MispredictionException(spec_ts.getTransactionId(), spec_ts.getTouchedPartitions()); spec_ts.setPendingError(error, false); spec_cr.setStatus(Status.ABORT_SPECULATIVE); this.processClientResponse(spec_ts, spec_cr); } // FOR } // ------------------------------- // DTXN READ-ONLY ABORT or DTXN COMMIT // ------------------------------- else { // **IMPORTANT** // If the dtxn needs to commit, then all we need to do is get the // last undoToken that we've generated (since we know that it had to // have been used either by our distributed txn or for one of our // speculative txns). // // If the read-only dtxn needs to abort, then there's nothing we need to // do, because it didn't make any changes. That means we can just // commit the last speculatively executed transaction // // Once we have this token, we can just make a direct call to the EE // to commit any changes that came before it. Note that we are using our // special 'finishWorkEE' method that does not require us to provide // the transaction that we're committing. long undoToken = this.lastUndoToken; if (debug.val) LOG.debug(String.format("%s - Last undoToken at partition %d => %d", ts, this.partitionId, undoToken)); // Bombs away! if (undoToken != this.lastCommittedUndoToken) { this.finishWorkEE(ts, undoToken, true); // IMPORTANT: Make sure that we remove the dtxn from the lock queue! // This is normally done in finishTransaction() but because we're trying // to be clever and invoke the EE directly, we have to make sure that // we call it ourselves. this.queueManager.lockQueueFinished(ts, status, this.partitionId); } // Make sure that we mark the dtxn as finished so that we don't // try to do anything with it later on. ts.markFinished(this.partitionId); // Now make sure that all of the speculative txns are processed without // committing (since we just committed any change that they could have made // up above). Pair<LocalTransaction, ClientResponseImpl> pair = null; while ((pair = this.specExecBlocked.pollFirst()) != null) { spec_ts = pair.getFirst(); spec_cr = pair.getSecond(); spec_ts.markFinished(this.partitionId); try { if (trace.val) LOG.trace(String.format("%s - Releasing blocked ClientResponse for %s [status=%s]", ts, spec_ts, spec_cr.getStatus())); this.processClientResponse(spec_ts, spec_cr); } catch (Throwable ex) { String msg = "Failed to complete queued response for " + spec_ts; throw new ServerFaultException(msg, ex, ts.getTransactionId()); } } // WHILE } this.specExecBlocked.clear(); this.specExecModified = false; if (trace.val) LOG.trace(String.format("Finished processing all queued speculative txns for dtxn %s", ts)); } // ------------------------------- // NO SPECULATIVE TXNS // ------------------------------- else { // There are no speculative txns waiting for this dtxn, // so we can just commit it right away if (debug.val) LOG.debug(String.format("%s - No speculative txns at partition %d. Just %s txn by itself", ts, this.partitionId, (status == Status.OK ? "commiting" : "aborting"))); this.finishTransaction(ts, status); } // Clear our cached query results that are specific for this transaction // this.queryCache.purgeTransaction(ts.getTransactionId()); // TODO: Remove anything in our queue for this txn // if (ts.hasQueuedWork(this.partitionId)) { // } // Check whether this is the response that the speculatively executed txns have been waiting for // We could have turned off speculative execution mode beforehand if (debug.val) LOG.debug(String.format("%s - Attempting to unmark as the current DTXN at partition %d and " + "setting execution mode to %s", ts, this.partitionId, ExecutionMode.COMMIT_ALL)); try { // Resetting the current_dtxn variable has to come *before* we change the execution mode this.resetCurrentDtxn(); this.setExecutionMode(ts, ExecutionMode.COMMIT_ALL); // Release blocked transactions this.releaseBlockedTransactions(ts); } catch (Throwable ex) { String msg = String.format("Failed to finish %s at partition %d", ts, this.partitionId); throw new ServerFaultException(msg, ex, ts.getTransactionId()); } if (hstore_conf.site.exec_profiling) { this.profiler.sp3_local_time.stopIfStarted(); this.profiler.sp3_remote_time.stopIfStarted(); } } // We were told told to finish a dtxn that is not the current one // at this partition. That's ok as long as it's aborting and not trying // to commit. else { assert(status != Status.OK) : String.format("Trying to commit %s at partition %d but the current dtxn is %s", ts, this.partitionId, this.currentDtxn); this.queueManager.lockQueueFinished(ts, status, this.partitionId); } // ------------------------------- // FINISH CALLBACKS // ------------------------------- // MapReduceTransaction if (ts instanceof MapReduceTransaction) { PartitionCountingCallback<AbstractTransaction> callback = ((MapReduceTransaction)ts).getCleanupCallback(); // We don't want to invoke this callback at the basePartition's site // because we don't want the parent txn to actually get deleted. if (this.partitionId == ts.getBasePartition()) { if (debug.val) LOG.debug(String.format("%s - Notifying %s that the txn is finished at partition %d", ts, callback.getClass().getSimpleName(), this.partitionId)); callback.run(this.partitionId); } } else { PartitionCountingCallback<AbstractTransaction> callback = ts.getFinishCallback(); if (debug.val) LOG.debug(String.format("%s - Notifying %s that the txn is finished at partition %d", ts, callback.getClass().getSimpleName(), this.partitionId)); callback.run(this.partitionId); } } private void blockTransaction(InternalTxnMessage work) { if (debug.val) LOG.debug(String.format("%s - Adding %s work to blocked queue", work.getTransaction(), work.getClass().getSimpleName())); this.currentBlockedTxns.add(work); } private void blockTransaction(LocalTransaction ts) { this.blockTransaction(new StartTxnMessage(ts)); } /** * Release all the transactions that are currently in this partition's blocked queue * into the work queue. * @param ts */ private void releaseBlockedTransactions(AbstractTransaction ts) { if (this.currentBlockedTxns.isEmpty() == false) { if (debug.val) LOG.debug(String.format("Attempting to release %d blocked transactions at partition %d because of %s", this.currentBlockedTxns.size(), this.partitionId, ts)); this.work_queue.addAll(this.currentBlockedTxns); int released = this.currentBlockedTxns.size(); this.currentBlockedTxns.clear(); if (debug.val) LOG.debug(String.format("Released %d blocked transactions at partition %d because of %s", released, this.partitionId, ts)); } assert(this.currentBlockedTxns.isEmpty()); } // --------------------------------------------------------------- // SNAPSHOT METHODS // --------------------------------------------------------------- /** * Do snapshot work exclusively until there is no more. Also blocks * until the syncing and closing of snapshot data targets has completed. */ public void initiateSnapshots(Deque<SnapshotTableTask> tasks) { m_snapshotter.initiateSnapshots(ee, tasks); } public Collection<Exception> completeSnapshotWork() throws InterruptedException { return m_snapshotter.completeSnapshotWork(ee); } // --------------------------------------------------------------- // SHUTDOWN METHODS // --------------------------------------------------------------- /** * Cause this PartitionExecutor to make the entire HStore cluster shutdown * This won't return! */ public synchronized void crash(Throwable ex) { String msg = String.format("PartitionExecutor for Partition #%d is crashing", this.partitionId); if (ex == null) LOG.warn(msg); else LOG.warn(msg, ex); assert(this.hstore_coordinator != null); this.hstore_coordinator.shutdownClusterBlocking(ex); } @Override public boolean isShuttingDown() { return (this.hstore_site.isShuttingDown()); // shutdown_state == State.PREPARE_SHUTDOWN || this.shutdown_state == State.SHUTDOWN); } @Override public void prepareShutdown(boolean error) { this.shutdown_state = ShutdownState.PREPARE_SHUTDOWN; } /** * Somebody from the outside wants us to shutdown */ public synchronized void shutdown() { if (this.shutdown_state == ShutdownState.SHUTDOWN) { if (debug.val) LOG.debug(String.format("Partition #%d told to shutdown again. Ignoring...", this.partitionId)); return; } this.shutdown_state = ShutdownState.SHUTDOWN; if (debug.val) LOG.debug(String.format("Shutting down PartitionExecutor for Partition #%d", this.partitionId)); // Clear the queue this.work_queue.clear(); // Knock out this ma if (this.m_snapshotter != null) this.m_snapshotter.shutdown(); // Make sure we shutdown our threadpool // this.thread_pool.shutdownNow(); if (this.self != null) this.self.interrupt(); if (this.shutdown_latch != null) { try { this.shutdown_latch.acquire(); } catch (InterruptedException ex) { // Ignore } catch (Exception ex) { LOG.fatal("Unexpected error while shutting down", ex); } } } // ---------------------------------------------------------------------------- // DEBUG METHODS // ---------------------------------------------------------------------------- @Override public String toString() { return String.format("%s{%s}", this.getClass().getSimpleName(), HStoreThreadManager.formatPartitionName(siteId, partitionId)); } public class Debug implements DebugContext { public VoltProcedure getVoltProcedure(String procName) { Procedure proc = catalogContext.procedures.getIgnoreCase(procName); return (PartitionExecutor.this.getVoltProcedure(proc.getId())); } public SpecExecScheduler getSpecExecScheduler() { return (PartitionExecutor.this.specExecScheduler); } public AbstractConflictChecker getSpecExecConflictChecker() { return (PartitionExecutor.this.specExecChecker); } public Collection<BatchPlanner> getBatchPlanners() { return (PartitionExecutor.this.batchPlanners.values()); } public PartitionExecutorProfiler getProfiler() { return (PartitionExecutor.this.profiler); } public Thread getExecutionThread() { return (PartitionExecutor.this.self); } public Queue<InternalMessage> getWorkQueue() { return (PartitionExecutor.this.work_queue); } public void setExecutionMode(AbstractTransaction ts, ExecutionMode newMode) { PartitionExecutor.this.setExecutionMode(ts, newMode); } public ExecutionMode getExecutionMode() { return (PartitionExecutor.this.currentExecMode); } public Long getLastExecutedTxnId() { return (PartitionExecutor.this.lastExecutedTxnId); } public Long getLastCommittedTxnId() { return (PartitionExecutor.this.lastCommittedTxnId); } public long getLastCommittedIndoToken() { return (PartitionExecutor.this.lastCommittedUndoToken); } /** * Get the VoltProcedure handle of the current running txn. This could be null. * <B>FOR TESTING ONLY</B> */ public VoltProcedure getCurrentVoltProcedure() { return (PartitionExecutor.this.currentVoltProc); } /** * Get the txnId of the current distributed transaction at this partition * <B>FOR TESTING ONLY</B> */ public AbstractTransaction getCurrentDtxn() { return (PartitionExecutor.this.currentDtxn); } /** * Get the txnId of the current distributed transaction at this partition * <B>FOR TESTING ONLY</B> */ public Long getCurrentDtxnId() { Long ret = null; // This is a race condition, so we'll just ignore any errors if (PartitionExecutor.this.currentDtxn != null) { try { ret = PartitionExecutor.this.currentDtxn.getTransactionId(); } catch (NullPointerException ex) { // IGNORE } } return (ret); } public Long getCurrentTxnId() { return (PartitionExecutor.this.currentTxnId); } public int getBlockedWorkCount() { return (PartitionExecutor.this.currentBlockedTxns.size()); } /** * Return the number of spec exec txns have completed but are waiting * for the distributed txn to finish at this partition */ public int getBlockedSpecExecCount() { return (PartitionExecutor.this.specExecBlocked.size()); } public int getWorkQueueSize() { return (PartitionExecutor.this.work_queue.size()); } public void updateMemory() { PartitionExecutor.this.updateMemoryStats(EstTime.currentTimeMillis()); } /** * Replace the ConflictChecker. This should only be used for testing * @param checker */ protected void setConflictChecker(AbstractConflictChecker checker) { LOG.warn(String.format("Replacing original checker %s with %s at partition %d", specExecChecker.getClass().getSimpleName(), checker.getClass().getSimpleName(), partitionId)); specExecChecker = checker; specExecScheduler.getDebugContext().setConflictChecker(checker); } } private Debug cachedDebugContext; public Debug getDebugContext() { if (this.cachedDebugContext == null) { // We don't care if we're thread-safe here... this.cachedDebugContext = new Debug(); } return this.cachedDebugContext; } }
diff --git a/src/com/avona/games/towerdefence/MovingObject.java b/src/com/avona/games/towerdefence/MovingObject.java index cbbbbff..5a4491e 100644 --- a/src/com/avona/games/towerdefence/MovingObject.java +++ b/src/com/avona/games/towerdefence/MovingObject.java @@ -1,16 +1,16 @@ package com.avona.games.towerdefence; public abstract class MovingObject extends LocationObject { private static final long serialVersionUID = 1L; public V2 velocity = new V2(1.0f, 1.0f); public MovingObject() { } public MovingObject(final MovingObject other) { super(other); - if (other.location != null) + if (other.velocity != null) velocity = other.velocity.copy(); } }
true
true
public MovingObject(final MovingObject other) { super(other); if (other.location != null) velocity = other.velocity.copy(); }
public MovingObject(final MovingObject other) { super(other); if (other.velocity != null) velocity = other.velocity.copy(); }
diff --git a/src/server/model/AggroBot.java b/src/server/model/AggroBot.java index 174778a..fd1823d 100644 --- a/src/server/model/AggroBot.java +++ b/src/server/model/AggroBot.java @@ -1,50 +1,51 @@ package server.model; import java.util.List; public class AggroBot extends Bot { private static final float MOVE_DIRECTION_MEMORY = 15; private float lastMoveX; private float lastMoveY; public AggroBot(int id, float x, float y, String name) { super(id, x, y, name); this.lastMoveX = Float.MAX_VALUE; this.lastMoveY = Float.MAX_VALUE; } @Override protected List<Entity> move(Game game, float dX, float dY) { float beforeX = this.getX(); float beforeY = this.getY(); List<Entity> result; - if (euclideanLength(lastMoveX, lastMoveY) < this.speed / 2) + if (euclideanLength(lastMoveX, lastMoveY) < this.speed / 2 + && abs(lastMoveX) + abs(lastMoveY) > 0) if (abs(lastMoveX) > abs(lastMoveY)) result = super.move(game, dX + memoryX(), 0 + memoryY()); else result = super.move(game, 0 + memoryX(), dY + memoryY()); else result = super.move(game, dX + memoryX(), dY + memoryY()); float afterX = this.getX(); float afterY = this.getY(); this.lastMoveX = afterX - beforeX; this.lastMoveY = afterY - beforeY; return result; } private float memoryX() { return lastMoveX * MOVE_DIRECTION_MEMORY; } private float memoryY() { return lastMoveY * MOVE_DIRECTION_MEMORY; } private float abs(float f) { return f < 0 ? -f : f; } }
true
true
protected List<Entity> move(Game game, float dX, float dY) { float beforeX = this.getX(); float beforeY = this.getY(); List<Entity> result; if (euclideanLength(lastMoveX, lastMoveY) < this.speed / 2) if (abs(lastMoveX) > abs(lastMoveY)) result = super.move(game, dX + memoryX(), 0 + memoryY()); else result = super.move(game, 0 + memoryX(), dY + memoryY()); else result = super.move(game, dX + memoryX(), dY + memoryY()); float afterX = this.getX(); float afterY = this.getY(); this.lastMoveX = afterX - beforeX; this.lastMoveY = afterY - beforeY; return result; }
protected List<Entity> move(Game game, float dX, float dY) { float beforeX = this.getX(); float beforeY = this.getY(); List<Entity> result; if (euclideanLength(lastMoveX, lastMoveY) < this.speed / 2 && abs(lastMoveX) + abs(lastMoveY) > 0) if (abs(lastMoveX) > abs(lastMoveY)) result = super.move(game, dX + memoryX(), 0 + memoryY()); else result = super.move(game, 0 + memoryX(), dY + memoryY()); else result = super.move(game, dX + memoryX(), dY + memoryY()); float afterX = this.getX(); float afterY = this.getY(); this.lastMoveX = afterX - beforeX; this.lastMoveY = afterY - beforeY; return result; }
diff --git a/src/com/redhat/ceylon/compiler/java/codegen/CodegenUtil.java b/src/com/redhat/ceylon/compiler/java/codegen/CodegenUtil.java index 54d79fc01..a94a37406 100644 --- a/src/com/redhat/ceylon/compiler/java/codegen/CodegenUtil.java +++ b/src/com/redhat/ceylon/compiler/java/codegen/CodegenUtil.java @@ -1,276 +1,279 @@ /* * 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.java.codegen; import com.redhat.ceylon.compiler.java.codegen.AbstractTransformer.BoxingStrategy; import com.redhat.ceylon.compiler.java.util.Util; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseMemberExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilerAnnotation; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Term; /** * Utility functions that are specific to the codegen package * @see Util */ class CodegenUtil { private CodegenUtil(){} static boolean isErasedAttribute(String name){ // ERASURE return "hash".equals(name) || "string".equals(name); } static boolean isSmall(TypedDeclaration declaration) { return "hash".equals(declaration.getName()); } static boolean isUnBoxed(Term node){ return node.getUnboxed(); } static boolean isUnBoxed(TypedDeclaration decl){ // null is considered boxed return decl.getUnboxed() == Boolean.TRUE; } static void markUnBoxed(Term node) { node.setUnboxed(true); } static BoxingStrategy getBoxingStrategy(Term node) { return isUnBoxed(node) ? BoxingStrategy.UNBOXED : BoxingStrategy.BOXED; } static BoxingStrategy getBoxingStrategy(TypedDeclaration decl) { return isUnBoxed(decl) ? BoxingStrategy.UNBOXED : BoxingStrategy.BOXED; } static boolean isRaw(TypedDeclaration decl){ ProducedType type = decl.getType(); return type != null && type.isRaw(); } static boolean isRaw(Term node){ ProducedType type = node.getTypeModel(); return type != null && type.isRaw(); } static void markRaw(Term node) { ProducedType type = node.getTypeModel(); if(type != null) type.setRaw(true); } static boolean hasTypeErased(Term node){ return node.getTypeErased(); } static boolean hasTypeErased(TypedDeclaration decl){ return decl.getTypeErased(); } static void markTypeErased(Term node) { markTypeErased(node, true); } static void markTypeErased(Term node, boolean erased) { node.setTypeErased(erased); } /** * Determines if the given statement or argument has a compiler annotation * with the given name. * * @param decl The statement or argument * @param name The compiler annotation name * @return true if the statement or argument has an annotation with the * given name * * @see #hasCompilerAnnotationWithArgument(com.redhat.ceylon.compiler.typechecker.tree.Tree.Declaration, String, String) */ static boolean hasCompilerAnnotation(Tree.StatementOrArgument decl, String name){ for(CompilerAnnotation annotation : decl.getCompilerAnnotations()){ if(annotation.getIdentifier().getText().equals(name)) return true; } return false; } /** * Determines if the given statement or argument has a compiler annotation * with the given name and with the given argument. * * @param decl The statement or argument * @param name The compiler annotation name * @param argument The compiler annotation's argument * @return true if the statement or argument has an annotation with the * given name and argument value * * @see #hasCompilerAnnotation(com.redhat.ceylon.compiler.typechecker.tree.Tree.Declaration, String) */ static boolean hasCompilerAnnotationWithArgument(Tree.StatementOrArgument decl, String name, String argument){ for (CompilerAnnotation annotation : decl.getCompilerAnnotations()) { if (annotation.getIdentifier().getText().equals(name)) { if (annotation.getStringLiteral() == null) { continue; } String text = annotation.getStringLiteral().getText(); if (text == null) { continue; } text = text.substring(1, text.length()-1);//remove ""; if (text.equals(argument)) { return true; } } } return false; } static boolean isDirectAccessVariable(Term term) { if(!(term instanceof BaseMemberExpression)) return false; Declaration decl = ((BaseMemberExpression)term).getDeclaration(); if(decl == null) // typechecker error return false; // make sure we don't try to optimise things which can't be optimised return decl instanceof Value && !decl.isToplevel() && !decl.isClassOrInterfaceMember() && !decl.isCaptured() && !decl.isShared(); } static Declaration getTopmostRefinedDeclaration(Declaration decl){ if (decl instanceof Parameter && decl.getContainer() instanceof Class) { // Parameters in a refined class are not considered refinements themselves // We have in find the refined attribute Class c = (Class)decl.getContainer(); if (c.isAlias()) { int index = c.getParameterList().getParameters().indexOf(decl); while (c.isAlias()) { c = c.getExtendedTypeDeclaration(); } decl = c.getParameterList().getParameters().get(index); } Declaration refinedDecl = c.getRefinedMember(decl.getName(), null, false);//?? elipses=false?? if(refinedDecl != null && refinedDecl != decl) { return getTopmostRefinedDeclaration(refinedDecl); } return decl; } else if(decl instanceof Parameter && decl.getContainer() instanceof Method){ // Parameters in a refined method are not considered refinements themselves // so we have to look up the corresponding parameter in the container's refined declaration Method func = (Method)decl.getContainer(); Parameter param = (Parameter)decl; Method refinedFunc = (Method) getTopmostRefinedDeclaration((Declaration)decl.getContainer()); // shortcut if the functional doesn't override anything if(refinedFunc == decl.getContainer()) return decl; if (func.getParameterLists().size() != refinedFunc.getParameterLists().size()) { throw new RuntimeException("Different numbers of parameter lists"); } for (int ii = 0; ii < func.getParameterLists().size(); ii++) { + if (func.getParameterLists().get(ii).getParameters().size() != refinedFunc.getParameterLists().get(ii).getParameters().size()) { + throw new RuntimeException("Different sized parameter lists"); + } // find the index of the parameter int index = func.getParameterLists().get(ii).getParameters().indexOf(param); if (index == -1) { continue; } return refinedFunc.getParameterLists().get(ii).getParameters().get(index); } } Declaration refinedDecl = decl.getRefinedDeclaration(); if(refinedDecl != null && refinedDecl != decl) return getTopmostRefinedDeclaration(refinedDecl); return decl; } static Parameter findParamForDecl(Tree.TypedDeclaration decl) { String attrName = decl.getIdentifier().getText(); return findParamForDecl(attrName, decl.getDeclarationModel()); } static Parameter findParamForDecl(TypedDeclaration decl) { String attrName = decl.getName(); return findParamForDecl(attrName, decl); } static Parameter findParamForDecl(String attrName, TypedDeclaration decl) { Parameter result = null; if (decl.getContainer() instanceof Functional) { Functional f = (Functional)decl.getContainer(); result = f.getParameter(attrName); } return result; } static MethodOrValue findMethodOrValueForParam(Parameter param) { MethodOrValue result = null; String attrName = param.getName(); Declaration member = param.getContainer().getDirectMember(attrName, null, false); if (member instanceof MethodOrValue) { result = (MethodOrValue)member; } return result; } static boolean isVoid(ProducedType type) { return type != null && type.getDeclaration() != null && type.getDeclaration().getUnit().getAnythingDeclaration().getType().isExactly(type); } public static boolean canOptimiseMethodSpecifier(Term expression, Method m) { if(expression instanceof Tree.FunctionArgument) return true; if(expression instanceof Tree.BaseMemberOrTypeExpression == false) return false; Declaration declaration = ((Tree.BaseMemberOrTypeExpression)expression).getDeclaration(); // methods are fine because they are constant if(declaration instanceof Method) return true; // toplevel constructors are fine if(declaration instanceof Class) return true; // parameters are constant too if(declaration instanceof Parameter) return true; // the rest we can't know: we can't trust attributes that could be getters or overridden // we can't trust even toplevel attributes that could be made variable in the future because of // binary compat. return false; } }
true
true
static Declaration getTopmostRefinedDeclaration(Declaration decl){ if (decl instanceof Parameter && decl.getContainer() instanceof Class) { // Parameters in a refined class are not considered refinements themselves // We have in find the refined attribute Class c = (Class)decl.getContainer(); if (c.isAlias()) { int index = c.getParameterList().getParameters().indexOf(decl); while (c.isAlias()) { c = c.getExtendedTypeDeclaration(); } decl = c.getParameterList().getParameters().get(index); } Declaration refinedDecl = c.getRefinedMember(decl.getName(), null, false);//?? elipses=false?? if(refinedDecl != null && refinedDecl != decl) { return getTopmostRefinedDeclaration(refinedDecl); } return decl; } else if(decl instanceof Parameter && decl.getContainer() instanceof Method){ // Parameters in a refined method are not considered refinements themselves // so we have to look up the corresponding parameter in the container's refined declaration Method func = (Method)decl.getContainer(); Parameter param = (Parameter)decl; Method refinedFunc = (Method) getTopmostRefinedDeclaration((Declaration)decl.getContainer()); // shortcut if the functional doesn't override anything if(refinedFunc == decl.getContainer()) return decl; if (func.getParameterLists().size() != refinedFunc.getParameterLists().size()) { throw new RuntimeException("Different numbers of parameter lists"); } for (int ii = 0; ii < func.getParameterLists().size(); ii++) { // find the index of the parameter int index = func.getParameterLists().get(ii).getParameters().indexOf(param); if (index == -1) { continue; } return refinedFunc.getParameterLists().get(ii).getParameters().get(index); } } Declaration refinedDecl = decl.getRefinedDeclaration(); if(refinedDecl != null && refinedDecl != decl) return getTopmostRefinedDeclaration(refinedDecl); return decl; }
static Declaration getTopmostRefinedDeclaration(Declaration decl){ if (decl instanceof Parameter && decl.getContainer() instanceof Class) { // Parameters in a refined class are not considered refinements themselves // We have in find the refined attribute Class c = (Class)decl.getContainer(); if (c.isAlias()) { int index = c.getParameterList().getParameters().indexOf(decl); while (c.isAlias()) { c = c.getExtendedTypeDeclaration(); } decl = c.getParameterList().getParameters().get(index); } Declaration refinedDecl = c.getRefinedMember(decl.getName(), null, false);//?? elipses=false?? if(refinedDecl != null && refinedDecl != decl) { return getTopmostRefinedDeclaration(refinedDecl); } return decl; } else if(decl instanceof Parameter && decl.getContainer() instanceof Method){ // Parameters in a refined method are not considered refinements themselves // so we have to look up the corresponding parameter in the container's refined declaration Method func = (Method)decl.getContainer(); Parameter param = (Parameter)decl; Method refinedFunc = (Method) getTopmostRefinedDeclaration((Declaration)decl.getContainer()); // shortcut if the functional doesn't override anything if(refinedFunc == decl.getContainer()) return decl; if (func.getParameterLists().size() != refinedFunc.getParameterLists().size()) { throw new RuntimeException("Different numbers of parameter lists"); } for (int ii = 0; ii < func.getParameterLists().size(); ii++) { if (func.getParameterLists().get(ii).getParameters().size() != refinedFunc.getParameterLists().get(ii).getParameters().size()) { throw new RuntimeException("Different sized parameter lists"); } // find the index of the parameter int index = func.getParameterLists().get(ii).getParameters().indexOf(param); if (index == -1) { continue; } return refinedFunc.getParameterLists().get(ii).getParameters().get(index); } } Declaration refinedDecl = decl.getRefinedDeclaration(); if(refinedDecl != null && refinedDecl != decl) return getTopmostRefinedDeclaration(refinedDecl); return decl; }
diff --git a/jamwiki-web/src/main/java/org/jamwiki/db/DatabaseUpgrades.java b/jamwiki-web/src/main/java/org/jamwiki/db/DatabaseUpgrades.java index e17cfc91..8bffbbdd 100644 --- a/jamwiki-web/src/main/java/org/jamwiki/db/DatabaseUpgrades.java +++ b/jamwiki-web/src/main/java/org/jamwiki/db/DatabaseUpgrades.java @@ -1,506 +1,516 @@ /** * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999. * * This program is free software; you can redistribute it and/or modify * it under the terms of the latest version of the GNU Lesser General * Public License as published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program (LICENSE.txt); if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.jamwiki.db; import java.sql.Connection; import java.sql.Types; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.jamwiki.Environment; import org.jamwiki.WikiBase; import org.jamwiki.WikiVersion; import org.jamwiki.model.Role; import org.jamwiki.model.WikiGroup; import org.jamwiki.utils.Encryption; import org.jamwiki.utils.WikiLogger; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; /** * This class simply contains utility methods for upgrading database schemas * (if needed) between JAMWiki versions. In general upgrade methods will only * be maintained for a few versions and then deleted - for example, JAMWiki version 10.0.0 * does not need to keep the upgrade methods from JAMWiki 0.0.1 around. */ public class DatabaseUpgrades { private static final WikiLogger logger = WikiLogger.getLogger(DatabaseUpgrades.class.getName()); /** * */ private DatabaseUpgrades() { } private static TransactionDefinition getTransactionDefinition() { DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); return def; } /** * Special login method - it cannot be assumed that the database schema * is unchanged, so do not use standard methods. */ public static boolean login(String username, String password) throws Exception { WikiVersion oldVersion = new WikiVersion(Environment.getValue(Environment.PROP_BASE_WIKI_VERSION)); if (!oldVersion.before(0, 7, 0)) { return (WikiBase.getDataHandler().authenticate(username, password)); } Connection conn = DatabaseConnection.getConnection(); WikiPreparedStatement stmt = new WikiPreparedStatement("select 1 from jam_wiki_user_info where login = ? and encoded_password = ?"); if (!StringUtils.isBlank(password)) { password = Encryption.encrypt(password); } stmt.setString(1, username); stmt.setString(2, password); WikiResultSet rs = stmt.executeQuery(conn); return (rs.size() > 0); } /** * */ public static Vector upgrade060(Vector messages) throws Exception { TransactionStatus status = DatabaseConnection.startTransaction(getTransactionDefinition()); try { Connection conn = DatabaseConnection.getConnection(); // create jam_group table DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_GROUP_TABLE, conn); messages.add("Added jam_group table"); // create jam_role table DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_ROLE_TABLE, conn); messages.add("Added jam_role table"); // create jam_role_map table String sql = "CREATE TABLE jam_role_map ( " + "role_name VARCHAR(30) NOT NULL, " + "wiki_user_id INTEGER, " + "group_id INTEGER, " + "CONSTRAINT jam_u_rmap UNIQUE (role_name, wiki_user_id, group_id), " + "CONSTRAINT jam_f_rmap_role FOREIGN KEY (role_name) REFERENCES jam_role(role_name), " + "CONSTRAINT jam_f_rmap_wuser FOREIGN KEY (wiki_user_id) REFERENCES jam_wiki_user(wiki_user_id), " + "CONSTRAINT jam_f_rmap_group FOREIGN KEY (group_id) REFERENCES jam_group(group_id) " + ") "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Added jam_role_map table"); // setup basic roles WikiDatabase.setupRoles(); messages.add("Added basic wiki roles."); // setup basic groups DatabaseUpgrades.setupGroups(); messages.add("Added basic wiki groups."); // convert old-style admins to new // assign admins all permissions during upgrades just to be safe. for // new installs it is sufficient just to give them the basics Role[] adminRoles = {Role.ROLE_ADMIN, Role.ROLE_EDIT_EXISTING, Role.ROLE_EDIT_NEW, Role.ROLE_MOVE, Role.ROLE_SYSADMIN, Role.ROLE_TRANSLATE, Role.ROLE_UPLOAD, Role.ROLE_VIEW}; for (int i = 0; i < adminRoles.length; i++) { Role adminRole = adminRoles[i]; sql = "insert into jam_role_map ( " + " role_name, wiki_user_id " + ") " + "select '" + adminRole.getAuthority() + "', wiki_user_id " + "from jam_wiki_user where is_admin = 1 "; DatabaseConnection.executeUpdate(sql, conn); } if (Environment.getBooleanValue(Environment.PROP_TOPIC_FORCE_USERNAME)) { sql = "delete from jam_role_map " + "where role_name = ? " + "and group_id = (select group_id from jam_group where group_name = ?) "; WikiPreparedStatement stmt = new WikiPreparedStatement(sql); stmt.setString(1, Role.ROLE_EDIT_EXISTING.getAuthority()); stmt.setString(2, WikiGroup.GROUP_ANONYMOUS); stmt.executeUpdate(conn); stmt = new WikiPreparedStatement(sql); stmt.setString(1, Role.ROLE_EDIT_NEW.getAuthority()); stmt.setString(2, WikiGroup.GROUP_ANONYMOUS); stmt.executeUpdate(conn); } if (!Environment.getBooleanValue(Environment.PROP_TOPIC_NON_ADMIN_TOPIC_MOVE)) { sql = "delete from jam_role_map " + "where role_name = ? " + "and group_id = (select group_id from jam_group where group_name = ?) "; WikiPreparedStatement stmt = new WikiPreparedStatement(sql); stmt.setString(1, Role.ROLE_MOVE.getAuthority()); stmt.setString(2, WikiGroup.GROUP_REGISTERED_USER); stmt.executeUpdate(conn); } sql = "alter table jam_wiki_user drop column is_admin "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Converted admin users to new role structure."); } catch (Exception e) { DatabaseConnection.rollbackOnException(status, e); try { DatabaseConnection.executeUpdate("drop table jam_role_map"); } catch (Exception ex) {} try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_ROLE_TABLE); } catch (Exception ex) {} try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_GROUP_TABLE); } catch (Exception ex) {} throw e; } catch (Error err) { DatabaseConnection.rollbackOnException(status, err); throw err; } DatabaseConnection.commit(status); return messages; } /** * */ private static void setupGroups() throws Exception { WikiGroup group = new WikiGroup(); group.setName(WikiGroup.GROUP_ANONYMOUS); // FIXME - use message key group.setDescription("All non-logged in users are automatically assigned to the anonymous group."); WikiBase.getDataHandler().writeWikiGroup(group); List anonymousRoles = new Vector(); anonymousRoles.add(Role.ROLE_EDIT_EXISTING.getAuthority()); anonymousRoles.add(Role.ROLE_EDIT_NEW.getAuthority()); anonymousRoles.add(Role.ROLE_UPLOAD.getAuthority()); anonymousRoles.add(Role.ROLE_VIEW.getAuthority()); DatabaseUpgrades.writeRoleMapGroup(group.getGroupId(), anonymousRoles, null); group = new WikiGroup(); group.setName(WikiGroup.GROUP_REGISTERED_USER); // FIXME - use message key group.setDescription("All logged in users are automatically assigned to the registered user group."); WikiBase.getDataHandler().writeWikiGroup(group); List userRoles = new Vector(); userRoles.add(Role.ROLE_EDIT_EXISTING.getAuthority()); userRoles.add(Role.ROLE_EDIT_NEW.getAuthority()); userRoles.add(Role.ROLE_MOVE.getAuthority()); userRoles.add(Role.ROLE_UPLOAD.getAuthority()); userRoles.add(Role.ROLE_VIEW.getAuthority()); DatabaseUpgrades.writeRoleMapGroup(group.getGroupId(), userRoles, null); } /** * */ private static void writeRoleMapGroup(int groupId, List roles, Object transactionObject) throws Exception { TransactionStatus status = DatabaseConnection.startTransaction(); try { Connection conn = DatabaseConnection.getConnection(); WikiPreparedStatement stmt = new WikiPreparedStatement("delete from jam_role_map where group_id = ?"); stmt.setInt(1, groupId); stmt.executeUpdate(conn); Iterator roleIterator = roles.iterator(); while (roleIterator.hasNext()) { String role = (String)roleIterator.next(); stmt = new WikiPreparedStatement("insert into jam_role_map (role_name, wiki_user_id, group_id) values (?, ?, ?)"); stmt.setString(1, role); stmt.setNull(2, Types.INTEGER); stmt.setInt(3, groupId); stmt.executeUpdate(conn); } } catch (Exception e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (Error err) { DatabaseConnection.rollbackOnException(status, err); throw err; } DatabaseConnection.commit(status); } /** * */ public static Vector upgrade061(Vector messages) throws Exception { TransactionStatus status = DatabaseConnection.startTransaction(getTransactionDefinition()); try { String sql = null; Connection conn = DatabaseConnection.getConnection(); // delete ROLE_DELETE sql = "delete from jam_role_map where role_name = 'ROLE_DELETE'"; DatabaseConnection.executeUpdate(sql, conn); sql = "delete from jam_role where role_name = 'ROLE_DELETE'"; DatabaseConnection.executeUpdate(sql, conn); messages.add("Removed ROLE_DELETE"); } catch (Exception e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (Error err) { DatabaseConnection.rollbackOnException(status, err); throw err; } DatabaseConnection.commit(status); return messages; } /** * */ public static Vector upgrade063(Vector messages) throws Exception { TransactionStatus status = DatabaseConnection.startTransaction(getTransactionDefinition()); try { String sql = null; Connection conn = DatabaseConnection.getConnection(); // increase the size of ip address columns String dbType = Environment.getValue(Environment.PROP_DB_TYPE); if (dbType.equals(WikiBase.DATA_HANDLER_DB2) || dbType.equals(WikiBase.DATA_HANDLER_DB2400)) { sql = "alter table jam_topic_version alter column wiki_user_ip_address set data type varchar(39) "; DatabaseConnection.executeUpdate(sql, conn); sql = "alter table jam_file_version alter column wiki_user_ip_address set data type varchar(39) "; DatabaseConnection.executeUpdate(sql, conn); sql = "alter table jam_wiki_user alter column create_ip_address set data type varchar(39) "; DatabaseConnection.executeUpdate(sql, conn); sql = "alter table jam_wiki_user alter column last_login_ip_address set data type varchar(39) "; DatabaseConnection.executeUpdate(sql, conn); } else if (dbType.equals(WikiBase.DATA_HANDLER_MYSQL) || dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_topic_version modify wiki_user_ip_address varchar(39) not null "; DatabaseConnection.executeUpdate(sql, conn); sql = "alter table jam_file_version modify wiki_user_ip_address varchar(39) not null "; DatabaseConnection.executeUpdate(sql, conn); sql = "alter table jam_wiki_user modify create_ip_address varchar(39) not null "; DatabaseConnection.executeUpdate(sql, conn); sql = "alter table jam_wiki_user modify last_login_ip_address varchar(39) not null "; DatabaseConnection.executeUpdate(sql, conn); } else if (dbType.equals(WikiBase.DATA_HANDLER_POSTGRES)) { sql = "alter table jam_topic_version alter column wiki_user_ip_address type varchar(39) "; DatabaseConnection.executeUpdate(sql, conn); sql = "alter table jam_file_version alter column wiki_user_ip_address type varchar(39) "; DatabaseConnection.executeUpdate(sql, conn); sql = "alter table jam_wiki_user alter column create_ip_address type varchar(39) "; DatabaseConnection.executeUpdate(sql, conn); sql = "alter table jam_wiki_user alter column last_login_ip_address type varchar(39) "; DatabaseConnection.executeUpdate(sql, conn); } else { sql = "alter table jam_topic_version alter column wiki_user_ip_address varchar(39) not null "; DatabaseConnection.executeUpdate(sql, conn); sql = "alter table jam_file_version alter column wiki_user_ip_address varchar(39) not null "; DatabaseConnection.executeUpdate(sql, conn); sql = "alter table jam_wiki_user alter column create_ip_address varchar(39) not null "; DatabaseConnection.executeUpdate(sql, conn); sql = "alter table jam_wiki_user alter column last_login_ip_address varchar(39) not null "; DatabaseConnection.executeUpdate(sql, conn); } messages.add("Increased IP address field sizes to support IPv6"); } catch (Exception e) { messages.add("Unable to modify database schema to support IPv6. Please see UPGRADE.txt for further details on this optional modification." + e.getMessage()); // do not throw this error and halt the upgrade process - changing the column size // is not required for systems that have already been successfully installed, it // is simply being done to keep new installs consistent with existing installs. logger.info("Failure while updating database for IPv6 support. See UPGRADE.txt for instructions on how to manually complete this optional step.", e); DatabaseConnection.rollbackOnException(status, e); status = null; // so we do not try to commit } catch (Error err) { DatabaseConnection.rollbackOnException(status, err); throw err; } if (status != null) { DatabaseConnection.commit(status); } return messages; } /** * */ public static Vector upgrade070(Vector messages) throws Exception { TransactionStatus status = DatabaseConnection.startTransaction(getTransactionDefinition()); String dbType = Environment.getValue(Environment.PROP_DB_TYPE); try { String sql = null; Connection conn = DatabaseConnection.getConnection(); // add characters_changed column to jam_topic_version if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_topic_version add (characters_changed INTEGER) "; + } else if (dbType.equals(WikiBase.DATA_HANDLER_MSSQL)) { + sql = "alter table jam_recent_change add [characters_changed] int "; } else { sql = "alter table jam_topic_version add column characters_changed INTEGER "; } DatabaseConnection.executeUpdate(sql, conn); messages.add("Added characters_changed column to jam_topic_version"); // add characters_changed column to jam_recent_change if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_recent_change add (characters_changed INTEGER) "; + } else if (dbType.equals(WikiBase.DATA_HANDLER_MSSQL)) { + sql = "alter table jam_topic_version add [characters_changed] int "; } else { sql = "alter table jam_recent_change add column characters_changed INTEGER "; } DatabaseConnection.executeUpdate(sql, conn); messages.add("Added characters_changed column to jam_recent_change"); // copy columns from jam_wiki_user_info into jam_wiki_user if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_wiki_user add (email VARCHAR(100)) "; + } else if (dbType.equals(WikiBase.DATA_HANDLER_MSSQL)) { + sql = "alter table jam_wiki_user add email VARCHAR(100) "; } else { sql = "alter table jam_wiki_user add column email VARCHAR(100) "; } DatabaseConnection.executeUpdate(sql, conn); sql = "update jam_wiki_user set email = ( " + "select email " + "from jam_wiki_user_info " + "where jam_wiki_user.wiki_user_id = jam_wiki_user_info.wiki_user_id " + ") "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Added email column to jam_wiki_user"); // add new columns to jam_wiki_user if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_wiki_user add (editor VARCHAR(50)) "; + } else if (dbType.equals(WikiBase.DATA_HANDLER_MSSQL)) { + sql = "alter table jam_wiki_user add editor VARCHAR(50) "; } else { sql = "alter table jam_wiki_user add column editor VARCHAR(50) "; } DatabaseConnection.executeUpdate(sql, conn); if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_wiki_user add (signature VARCHAR(255)) "; + } else if (dbType.equals(WikiBase.DATA_HANDLER_MSSQL)) { + sql = "alter table jam_wiki_user add signature VARCHAR(255) "; } else { sql = "alter table jam_wiki_user add column signature VARCHAR(255) "; } DatabaseConnection.executeUpdate(sql, conn); messages.add("Added editor and signature columns to jam_wiki_user"); if (dbType.equals(WikiBase.DATA_HANDLER_HSQL)) { DatabaseConnection.executeUpdate(HSqlQueryHandler.STATEMENT_CREATE_USERS_TABLE, conn); } else { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_USERS_TABLE, conn); } sql = "insert into jam_users ( " + "username, password " + ") " + "select login, encoded_password " + "from jam_wiki_user_info "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Added jam_users table"); sql = "alter table jam_wiki_user drop column remember_key"; DatabaseConnection.executeUpdate(sql, conn); messages.add("Dropped the remember_key column from jam_wiki_user"); if (dbType.equals(WikiBase.DATA_HANDLER_HSQL)) { DatabaseConnection.executeUpdate(HSqlQueryHandler.STATEMENT_CREATE_AUTHORITIES_TABLE, conn); } else if (dbType.equals(WikiBase.DATA_HANDLER_MYSQL)) { DatabaseConnection.executeUpdate(MySqlQueryHandler.STATEMENT_CREATE_AUTHORITIES_TABLE, conn); } else { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_AUTHORITIES_TABLE, conn); } sql = "insert into jam_authorities ( " + "username, authority " + ") " + "select jam_wiki_user.login, jam_role_map.role_name " + "from jam_wiki_user, jam_role_map " + "where jam_wiki_user.wiki_user_id = jam_role_map.wiki_user_id "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Added jam_authorities table"); if (dbType.equals(WikiBase.DATA_HANDLER_HSQL)) { DatabaseConnection.executeUpdate(HSqlQueryHandler.STATEMENT_CREATE_GROUP_AUTHORITIES_TABLE, conn); } else if (dbType.equals(WikiBase.DATA_HANDLER_MYSQL)) { DatabaseConnection.executeUpdate(MySqlQueryHandler.STATEMENT_CREATE_GROUP_AUTHORITIES_TABLE, conn); } else { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_GROUP_AUTHORITIES_TABLE, conn); } sql = "insert into jam_group_authorities ( " + "group_id, authority " + ") " + "select jam_group.group_id, jam_role_map.role_name " + "from jam_group, jam_role_map " + "where jam_group.group_id = jam_role_map.group_id "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Added jam_group_authorities table"); sql = "drop table jam_role_map "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Dropped the jam_role_map table"); if (dbType.equals(WikiBase.DATA_HANDLER_HSQL)) { DatabaseConnection.executeUpdate(MySqlQueryHandler.STATEMENT_CREATE_GROUP_MEMBERS_TABLE, conn); } else { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_GROUP_MEMBERS_TABLE, conn); } sql = "select group_id from jam_group where group_name = '" + WikiGroup.GROUP_REGISTERED_USER + "'"; WikiResultSet rs = DatabaseConnection.executeQuery(sql, conn); int groupId = rs.getInt("group_id"); sql = "select username from jam_users "; rs = DatabaseConnection.executeQuery(sql, conn); int id = 1; while (rs.next()) { sql = "insert into jam_group_members ( " + "id, username, group_id " + ") values ( " + id + ", '" + StringEscapeUtils.escapeSql(rs.getString("username")) + "', " + groupId + ") "; DatabaseConnection.executeUpdate(sql, conn); id++; } messages.add("Added jam_group_members table"); sql = "drop table jam_wiki_user_info"; DatabaseConnection.executeUpdate(sql, conn); messages.add("Dropped jam_wiki_user_info table"); } catch (Exception e) { DatabaseConnection.rollbackOnException(status, e); try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_GROUP_MEMBERS_TABLE); } catch (Exception ex) {} try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_GROUP_AUTHORITIES_TABLE); } catch (Exception ex) {} try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_AUTHORITIES_TABLE); } catch (Exception ex) {} try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_USERS_TABLE); } catch (Exception ex) {} throw e; } catch (Error err) { DatabaseConnection.rollbackOnException(status, err); throw err; } DatabaseConnection.commit(status); // perform a second transaction to populate the new columns. this code is in its own // transaction since if it fails the upgrade can still be considered successful. status = DatabaseConnection.startTransaction(getTransactionDefinition()); try { String sql = null; if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "update jam_topic_version set characters_changed = ( " + "select (dbms_lob.getlength(current_version.version_content) - dbms_lob.getlength(previous_version.version_content)) " + "from jam_topic_version current_version " + "left outer join jam_topic_version previous_version " + "on current_version.previous_topic_version_id = previous_version.topic_version_id " + "where jam_topic_version.topic_version_id = current_version.topic_version_id " + ") "; } else { sql = "update jam_topic_version set characters_changed = ( " + "select (char_length(current_version.version_content) - char_length(coalesce(previous_version.version_content, ''))) " + "from jam_topic_version current_version " + "left outer join jam_topic_version previous_version " + "on current_version.previous_topic_version_id = previous_version.topic_version_id " + "where jam_topic_version.topic_version_id = current_version.topic_version_id " + ") "; } Connection conn = DatabaseConnection.getConnection(); DatabaseConnection.executeUpdate(sql, conn); messages.add("Populated characters_changed column in jam_topic_version"); } catch (Throwable t) { messages.add("Unable to populate characters_changed colum in jam_topic_version. Please see UPGRADE.txt for further details on this optional modification." + t.getMessage()); // do not throw this error and halt the upgrade process - populating the field // is not required for existing systems. logger.info("Failure while populating characters_changed colum in jam_topic_version. See UPGRADE.txt for instructions on how to manually complete this optional step.", t); try { DatabaseConnection.rollbackOnException(status, t); } catch (Exception e) { // ignore } status = null; // so we do not try to commit } if (status != null) { DatabaseConnection.commit(status); } WikiBase.getDataHandler().reloadRecentChanges(); messages.add("Populated characters_changed column in jam_recent_change"); return messages; } }
false
true
public static Vector upgrade070(Vector messages) throws Exception { TransactionStatus status = DatabaseConnection.startTransaction(getTransactionDefinition()); String dbType = Environment.getValue(Environment.PROP_DB_TYPE); try { String sql = null; Connection conn = DatabaseConnection.getConnection(); // add characters_changed column to jam_topic_version if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_topic_version add (characters_changed INTEGER) "; } else { sql = "alter table jam_topic_version add column characters_changed INTEGER "; } DatabaseConnection.executeUpdate(sql, conn); messages.add("Added characters_changed column to jam_topic_version"); // add characters_changed column to jam_recent_change if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_recent_change add (characters_changed INTEGER) "; } else { sql = "alter table jam_recent_change add column characters_changed INTEGER "; } DatabaseConnection.executeUpdate(sql, conn); messages.add("Added characters_changed column to jam_recent_change"); // copy columns from jam_wiki_user_info into jam_wiki_user if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_wiki_user add (email VARCHAR(100)) "; } else { sql = "alter table jam_wiki_user add column email VARCHAR(100) "; } DatabaseConnection.executeUpdate(sql, conn); sql = "update jam_wiki_user set email = ( " + "select email " + "from jam_wiki_user_info " + "where jam_wiki_user.wiki_user_id = jam_wiki_user_info.wiki_user_id " + ") "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Added email column to jam_wiki_user"); // add new columns to jam_wiki_user if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_wiki_user add (editor VARCHAR(50)) "; } else { sql = "alter table jam_wiki_user add column editor VARCHAR(50) "; } DatabaseConnection.executeUpdate(sql, conn); if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_wiki_user add (signature VARCHAR(255)) "; } else { sql = "alter table jam_wiki_user add column signature VARCHAR(255) "; } DatabaseConnection.executeUpdate(sql, conn); messages.add("Added editor and signature columns to jam_wiki_user"); if (dbType.equals(WikiBase.DATA_HANDLER_HSQL)) { DatabaseConnection.executeUpdate(HSqlQueryHandler.STATEMENT_CREATE_USERS_TABLE, conn); } else { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_USERS_TABLE, conn); } sql = "insert into jam_users ( " + "username, password " + ") " + "select login, encoded_password " + "from jam_wiki_user_info "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Added jam_users table"); sql = "alter table jam_wiki_user drop column remember_key"; DatabaseConnection.executeUpdate(sql, conn); messages.add("Dropped the remember_key column from jam_wiki_user"); if (dbType.equals(WikiBase.DATA_HANDLER_HSQL)) { DatabaseConnection.executeUpdate(HSqlQueryHandler.STATEMENT_CREATE_AUTHORITIES_TABLE, conn); } else if (dbType.equals(WikiBase.DATA_HANDLER_MYSQL)) { DatabaseConnection.executeUpdate(MySqlQueryHandler.STATEMENT_CREATE_AUTHORITIES_TABLE, conn); } else { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_AUTHORITIES_TABLE, conn); } sql = "insert into jam_authorities ( " + "username, authority " + ") " + "select jam_wiki_user.login, jam_role_map.role_name " + "from jam_wiki_user, jam_role_map " + "where jam_wiki_user.wiki_user_id = jam_role_map.wiki_user_id "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Added jam_authorities table"); if (dbType.equals(WikiBase.DATA_HANDLER_HSQL)) { DatabaseConnection.executeUpdate(HSqlQueryHandler.STATEMENT_CREATE_GROUP_AUTHORITIES_TABLE, conn); } else if (dbType.equals(WikiBase.DATA_HANDLER_MYSQL)) { DatabaseConnection.executeUpdate(MySqlQueryHandler.STATEMENT_CREATE_GROUP_AUTHORITIES_TABLE, conn); } else { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_GROUP_AUTHORITIES_TABLE, conn); } sql = "insert into jam_group_authorities ( " + "group_id, authority " + ") " + "select jam_group.group_id, jam_role_map.role_name " + "from jam_group, jam_role_map " + "where jam_group.group_id = jam_role_map.group_id "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Added jam_group_authorities table"); sql = "drop table jam_role_map "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Dropped the jam_role_map table"); if (dbType.equals(WikiBase.DATA_HANDLER_HSQL)) { DatabaseConnection.executeUpdate(MySqlQueryHandler.STATEMENT_CREATE_GROUP_MEMBERS_TABLE, conn); } else { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_GROUP_MEMBERS_TABLE, conn); } sql = "select group_id from jam_group where group_name = '" + WikiGroup.GROUP_REGISTERED_USER + "'"; WikiResultSet rs = DatabaseConnection.executeQuery(sql, conn); int groupId = rs.getInt("group_id"); sql = "select username from jam_users "; rs = DatabaseConnection.executeQuery(sql, conn); int id = 1; while (rs.next()) { sql = "insert into jam_group_members ( " + "id, username, group_id " + ") values ( " + id + ", '" + StringEscapeUtils.escapeSql(rs.getString("username")) + "', " + groupId + ") "; DatabaseConnection.executeUpdate(sql, conn); id++; } messages.add("Added jam_group_members table"); sql = "drop table jam_wiki_user_info"; DatabaseConnection.executeUpdate(sql, conn); messages.add("Dropped jam_wiki_user_info table"); } catch (Exception e) { DatabaseConnection.rollbackOnException(status, e); try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_GROUP_MEMBERS_TABLE); } catch (Exception ex) {} try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_GROUP_AUTHORITIES_TABLE); } catch (Exception ex) {} try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_AUTHORITIES_TABLE); } catch (Exception ex) {} try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_USERS_TABLE); } catch (Exception ex) {} throw e; } catch (Error err) { DatabaseConnection.rollbackOnException(status, err); throw err; } DatabaseConnection.commit(status); // perform a second transaction to populate the new columns. this code is in its own // transaction since if it fails the upgrade can still be considered successful. status = DatabaseConnection.startTransaction(getTransactionDefinition()); try { String sql = null; if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "update jam_topic_version set characters_changed = ( " + "select (dbms_lob.getlength(current_version.version_content) - dbms_lob.getlength(previous_version.version_content)) " + "from jam_topic_version current_version " + "left outer join jam_topic_version previous_version " + "on current_version.previous_topic_version_id = previous_version.topic_version_id " + "where jam_topic_version.topic_version_id = current_version.topic_version_id " + ") "; } else { sql = "update jam_topic_version set characters_changed = ( " + "select (char_length(current_version.version_content) - char_length(coalesce(previous_version.version_content, ''))) " + "from jam_topic_version current_version " + "left outer join jam_topic_version previous_version " + "on current_version.previous_topic_version_id = previous_version.topic_version_id " + "where jam_topic_version.topic_version_id = current_version.topic_version_id " + ") "; } Connection conn = DatabaseConnection.getConnection(); DatabaseConnection.executeUpdate(sql, conn); messages.add("Populated characters_changed column in jam_topic_version"); } catch (Throwable t) { messages.add("Unable to populate characters_changed colum in jam_topic_version. Please see UPGRADE.txt for further details on this optional modification." + t.getMessage()); // do not throw this error and halt the upgrade process - populating the field // is not required for existing systems. logger.info("Failure while populating characters_changed colum in jam_topic_version. See UPGRADE.txt for instructions on how to manually complete this optional step.", t); try { DatabaseConnection.rollbackOnException(status, t); } catch (Exception e) { // ignore } status = null; // so we do not try to commit } if (status != null) { DatabaseConnection.commit(status); } WikiBase.getDataHandler().reloadRecentChanges(); messages.add("Populated characters_changed column in jam_recent_change"); return messages; }
public static Vector upgrade070(Vector messages) throws Exception { TransactionStatus status = DatabaseConnection.startTransaction(getTransactionDefinition()); String dbType = Environment.getValue(Environment.PROP_DB_TYPE); try { String sql = null; Connection conn = DatabaseConnection.getConnection(); // add characters_changed column to jam_topic_version if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_topic_version add (characters_changed INTEGER) "; } else if (dbType.equals(WikiBase.DATA_HANDLER_MSSQL)) { sql = "alter table jam_recent_change add [characters_changed] int "; } else { sql = "alter table jam_topic_version add column characters_changed INTEGER "; } DatabaseConnection.executeUpdate(sql, conn); messages.add("Added characters_changed column to jam_topic_version"); // add characters_changed column to jam_recent_change if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_recent_change add (characters_changed INTEGER) "; } else if (dbType.equals(WikiBase.DATA_HANDLER_MSSQL)) { sql = "alter table jam_topic_version add [characters_changed] int "; } else { sql = "alter table jam_recent_change add column characters_changed INTEGER "; } DatabaseConnection.executeUpdate(sql, conn); messages.add("Added characters_changed column to jam_recent_change"); // copy columns from jam_wiki_user_info into jam_wiki_user if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_wiki_user add (email VARCHAR(100)) "; } else if (dbType.equals(WikiBase.DATA_HANDLER_MSSQL)) { sql = "alter table jam_wiki_user add email VARCHAR(100) "; } else { sql = "alter table jam_wiki_user add column email VARCHAR(100) "; } DatabaseConnection.executeUpdate(sql, conn); sql = "update jam_wiki_user set email = ( " + "select email " + "from jam_wiki_user_info " + "where jam_wiki_user.wiki_user_id = jam_wiki_user_info.wiki_user_id " + ") "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Added email column to jam_wiki_user"); // add new columns to jam_wiki_user if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_wiki_user add (editor VARCHAR(50)) "; } else if (dbType.equals(WikiBase.DATA_HANDLER_MSSQL)) { sql = "alter table jam_wiki_user add editor VARCHAR(50) "; } else { sql = "alter table jam_wiki_user add column editor VARCHAR(50) "; } DatabaseConnection.executeUpdate(sql, conn); if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "alter table jam_wiki_user add (signature VARCHAR(255)) "; } else if (dbType.equals(WikiBase.DATA_HANDLER_MSSQL)) { sql = "alter table jam_wiki_user add signature VARCHAR(255) "; } else { sql = "alter table jam_wiki_user add column signature VARCHAR(255) "; } DatabaseConnection.executeUpdate(sql, conn); messages.add("Added editor and signature columns to jam_wiki_user"); if (dbType.equals(WikiBase.DATA_HANDLER_HSQL)) { DatabaseConnection.executeUpdate(HSqlQueryHandler.STATEMENT_CREATE_USERS_TABLE, conn); } else { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_USERS_TABLE, conn); } sql = "insert into jam_users ( " + "username, password " + ") " + "select login, encoded_password " + "from jam_wiki_user_info "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Added jam_users table"); sql = "alter table jam_wiki_user drop column remember_key"; DatabaseConnection.executeUpdate(sql, conn); messages.add("Dropped the remember_key column from jam_wiki_user"); if (dbType.equals(WikiBase.DATA_HANDLER_HSQL)) { DatabaseConnection.executeUpdate(HSqlQueryHandler.STATEMENT_CREATE_AUTHORITIES_TABLE, conn); } else if (dbType.equals(WikiBase.DATA_HANDLER_MYSQL)) { DatabaseConnection.executeUpdate(MySqlQueryHandler.STATEMENT_CREATE_AUTHORITIES_TABLE, conn); } else { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_AUTHORITIES_TABLE, conn); } sql = "insert into jam_authorities ( " + "username, authority " + ") " + "select jam_wiki_user.login, jam_role_map.role_name " + "from jam_wiki_user, jam_role_map " + "where jam_wiki_user.wiki_user_id = jam_role_map.wiki_user_id "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Added jam_authorities table"); if (dbType.equals(WikiBase.DATA_HANDLER_HSQL)) { DatabaseConnection.executeUpdate(HSqlQueryHandler.STATEMENT_CREATE_GROUP_AUTHORITIES_TABLE, conn); } else if (dbType.equals(WikiBase.DATA_HANDLER_MYSQL)) { DatabaseConnection.executeUpdate(MySqlQueryHandler.STATEMENT_CREATE_GROUP_AUTHORITIES_TABLE, conn); } else { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_GROUP_AUTHORITIES_TABLE, conn); } sql = "insert into jam_group_authorities ( " + "group_id, authority " + ") " + "select jam_group.group_id, jam_role_map.role_name " + "from jam_group, jam_role_map " + "where jam_group.group_id = jam_role_map.group_id "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Added jam_group_authorities table"); sql = "drop table jam_role_map "; DatabaseConnection.executeUpdate(sql, conn); messages.add("Dropped the jam_role_map table"); if (dbType.equals(WikiBase.DATA_HANDLER_HSQL)) { DatabaseConnection.executeUpdate(MySqlQueryHandler.STATEMENT_CREATE_GROUP_MEMBERS_TABLE, conn); } else { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_CREATE_GROUP_MEMBERS_TABLE, conn); } sql = "select group_id from jam_group where group_name = '" + WikiGroup.GROUP_REGISTERED_USER + "'"; WikiResultSet rs = DatabaseConnection.executeQuery(sql, conn); int groupId = rs.getInt("group_id"); sql = "select username from jam_users "; rs = DatabaseConnection.executeQuery(sql, conn); int id = 1; while (rs.next()) { sql = "insert into jam_group_members ( " + "id, username, group_id " + ") values ( " + id + ", '" + StringEscapeUtils.escapeSql(rs.getString("username")) + "', " + groupId + ") "; DatabaseConnection.executeUpdate(sql, conn); id++; } messages.add("Added jam_group_members table"); sql = "drop table jam_wiki_user_info"; DatabaseConnection.executeUpdate(sql, conn); messages.add("Dropped jam_wiki_user_info table"); } catch (Exception e) { DatabaseConnection.rollbackOnException(status, e); try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_GROUP_MEMBERS_TABLE); } catch (Exception ex) {} try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_GROUP_AUTHORITIES_TABLE); } catch (Exception ex) {} try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_AUTHORITIES_TABLE); } catch (Exception ex) {} try { DatabaseConnection.executeUpdate(AnsiQueryHandler.STATEMENT_DROP_USERS_TABLE); } catch (Exception ex) {} throw e; } catch (Error err) { DatabaseConnection.rollbackOnException(status, err); throw err; } DatabaseConnection.commit(status); // perform a second transaction to populate the new columns. this code is in its own // transaction since if it fails the upgrade can still be considered successful. status = DatabaseConnection.startTransaction(getTransactionDefinition()); try { String sql = null; if (dbType.equals(WikiBase.DATA_HANDLER_ORACLE)) { sql = "update jam_topic_version set characters_changed = ( " + "select (dbms_lob.getlength(current_version.version_content) - dbms_lob.getlength(previous_version.version_content)) " + "from jam_topic_version current_version " + "left outer join jam_topic_version previous_version " + "on current_version.previous_topic_version_id = previous_version.topic_version_id " + "where jam_topic_version.topic_version_id = current_version.topic_version_id " + ") "; } else { sql = "update jam_topic_version set characters_changed = ( " + "select (char_length(current_version.version_content) - char_length(coalesce(previous_version.version_content, ''))) " + "from jam_topic_version current_version " + "left outer join jam_topic_version previous_version " + "on current_version.previous_topic_version_id = previous_version.topic_version_id " + "where jam_topic_version.topic_version_id = current_version.topic_version_id " + ") "; } Connection conn = DatabaseConnection.getConnection(); DatabaseConnection.executeUpdate(sql, conn); messages.add("Populated characters_changed column in jam_topic_version"); } catch (Throwable t) { messages.add("Unable to populate characters_changed colum in jam_topic_version. Please see UPGRADE.txt for further details on this optional modification." + t.getMessage()); // do not throw this error and halt the upgrade process - populating the field // is not required for existing systems. logger.info("Failure while populating characters_changed colum in jam_topic_version. See UPGRADE.txt for instructions on how to manually complete this optional step.", t); try { DatabaseConnection.rollbackOnException(status, t); } catch (Exception e) { // ignore } status = null; // so we do not try to commit } if (status != null) { DatabaseConnection.commit(status); } WikiBase.getDataHandler().reloadRecentChanges(); messages.add("Populated characters_changed column in jam_recent_change"); return messages; }
diff --git a/src/groovy/org/pillarone/riskanalytics/domain/pc/reserves/LineOfBusinessReserves.java b/src/groovy/org/pillarone/riskanalytics/domain/pc/reserves/LineOfBusinessReserves.java index 3e8af57..80ba5e7 100644 --- a/src/groovy/org/pillarone/riskanalytics/domain/pc/reserves/LineOfBusinessReserves.java +++ b/src/groovy/org/pillarone/riskanalytics/domain/pc/reserves/LineOfBusinessReserves.java @@ -1,91 +1,91 @@ package org.pillarone.riskanalytics.domain.pc.reserves; import org.pillarone.riskanalytics.core.components.Component; import org.pillarone.riskanalytics.core.packets.PacketList; import org.pillarone.riskanalytics.core.parameterization.ConstrainedMultiDimensionalParameter; import org.pillarone.riskanalytics.core.parameterization.ConstraintsFactory; import org.pillarone.riskanalytics.core.util.GroovyUtils; import org.pillarone.riskanalytics.domain.pc.claims.Claim; import org.pillarone.riskanalytics.domain.pc.claims.SortClaimsByFractionOfPeriod; import org.pillarone.riskanalytics.domain.pc.constraints.ReservePortion; import org.pillarone.riskanalytics.domain.pc.lob.LobMarker; import org.pillarone.riskanalytics.domain.pc.reserves.fasttrack.ClaimDevelopmentLeanPacket; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * @author stefan.kunz (at) intuitive-collaboration (dot) com */ public class LineOfBusinessReserves extends Component { private static final String RESERVES = "Reserves"; private static final String PORTION = "Portion of Claims"; private PacketList<Claim> inClaims = new PacketList<Claim>(Claim.class); private PacketList<Claim> outClaims = new PacketList<Claim>(Claim.class); // todo(sku): remove the following and related lines as soon as PMO-648 is resolved private PacketList<ClaimDevelopmentLeanPacket> outClaimsDevelopmentLean = new PacketList<ClaimDevelopmentLeanPacket>(ClaimDevelopmentLeanPacket.class); private ConstrainedMultiDimensionalParameter parmPortions = new ConstrainedMultiDimensionalParameter( GroovyUtils.toList("[[],[]]"), Arrays.asList(RESERVES, PORTION), ConstraintsFactory.getConstraints(ReservePortion.IDENTIFIER)); protected void doCalculation() { if (inClaims.size() > 0) { List<Claim> lobClaims = new ArrayList<Claim>(); int portionColumn = parmPortions.getColumnIndex(PORTION); Component lineOfBusiness = inClaims.get(0).sender; // works only if this component is part of a component implementing LobMarker for (Claim claim : inClaims) { String originName = claim.origin.getNormalizedName(); int row = parmPortions.getColumnByName(RESERVES).indexOf(originName); if (row > -1) { Claim lobClaim = claim.copy(); - lobClaim.setOriginalClaim(claim); + lobClaim.setOriginalClaim(lobClaim); lobClaim.origin = lineOfBusiness; lobClaim.setLineOfBusiness((LobMarker) lineOfBusiness); lobClaim.scale((Double) parmPortions.getValueAt(row + 1, portionColumn)); lobClaims.add(lobClaim); outClaimsDevelopmentLean.add((ClaimDevelopmentLeanPacket) lobClaim); } } Collections.sort(lobClaims, SortClaimsByFractionOfPeriod.getInstance()); outClaims.addAll(lobClaims); } } public PacketList<Claim> getInClaims() { return inClaims; } public void setInClaims(PacketList<Claim> inClaims) { this.inClaims = inClaims; } public PacketList<Claim> getOutClaims() { return outClaims; } public void setOutClaims(PacketList<Claim> outClaims) { this.outClaims = outClaims; } public ConstrainedMultiDimensionalParameter getParmPortions() { return parmPortions; } public void setParmPortions(ConstrainedMultiDimensionalParameter parmPortions) { this.parmPortions = parmPortions; } public PacketList<ClaimDevelopmentLeanPacket> getOutClaimsDevelopmentLean() { return outClaimsDevelopmentLean; } public void setOutClaimsDevelopmentLean(PacketList<ClaimDevelopmentLeanPacket> outClaimsDevelopmentLean) { this.outClaimsDevelopmentLean = outClaimsDevelopmentLean; } }
true
true
protected void doCalculation() { if (inClaims.size() > 0) { List<Claim> lobClaims = new ArrayList<Claim>(); int portionColumn = parmPortions.getColumnIndex(PORTION); Component lineOfBusiness = inClaims.get(0).sender; // works only if this component is part of a component implementing LobMarker for (Claim claim : inClaims) { String originName = claim.origin.getNormalizedName(); int row = parmPortions.getColumnByName(RESERVES).indexOf(originName); if (row > -1) { Claim lobClaim = claim.copy(); lobClaim.setOriginalClaim(claim); lobClaim.origin = lineOfBusiness; lobClaim.setLineOfBusiness((LobMarker) lineOfBusiness); lobClaim.scale((Double) parmPortions.getValueAt(row + 1, portionColumn)); lobClaims.add(lobClaim); outClaimsDevelopmentLean.add((ClaimDevelopmentLeanPacket) lobClaim); } } Collections.sort(lobClaims, SortClaimsByFractionOfPeriod.getInstance()); outClaims.addAll(lobClaims); } }
protected void doCalculation() { if (inClaims.size() > 0) { List<Claim> lobClaims = new ArrayList<Claim>(); int portionColumn = parmPortions.getColumnIndex(PORTION); Component lineOfBusiness = inClaims.get(0).sender; // works only if this component is part of a component implementing LobMarker for (Claim claim : inClaims) { String originName = claim.origin.getNormalizedName(); int row = parmPortions.getColumnByName(RESERVES).indexOf(originName); if (row > -1) { Claim lobClaim = claim.copy(); lobClaim.setOriginalClaim(lobClaim); lobClaim.origin = lineOfBusiness; lobClaim.setLineOfBusiness((LobMarker) lineOfBusiness); lobClaim.scale((Double) parmPortions.getValueAt(row + 1, portionColumn)); lobClaims.add(lobClaim); outClaimsDevelopmentLean.add((ClaimDevelopmentLeanPacket) lobClaim); } } Collections.sort(lobClaims, SortClaimsByFractionOfPeriod.getInstance()); outClaims.addAll(lobClaims); } }
diff --git a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/PluginXMLGenerator.java b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/PluginXMLGenerator.java index 90f21ea8f..55db5978d 100644 --- a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/PluginXMLGenerator.java +++ b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/PluginXMLGenerator.java @@ -1,159 +1,159 @@ /******************************************************************************* * Copyright (c) 2006-2010 * Software Technology Group, Dresden University of Technology * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Software Technology Group - TU Dresden, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.codegen.resource.generators; import java.io.PrintWriter; import org.emftext.sdk.IPluginDescriptor; import org.emftext.sdk.OptionManager; import org.emftext.sdk.codegen.annotations.SyntaxDependent; import org.emftext.sdk.codegen.composites.StringComposite; import org.emftext.sdk.codegen.composites.XMLComposite; import org.emftext.sdk.codegen.parameters.ArtifactParameter; import org.emftext.sdk.codegen.resource.GenerationContext; import org.emftext.sdk.codegen.resource.TextResourceArtifacts; import org.emftext.sdk.codegen.resource.generators.EProblemTypeGenerator.PROBLEM_TYPES; import org.emftext.sdk.codegen.util.NameUtil; import org.emftext.sdk.concretesyntax.ConcreteSyntax; import org.emftext.sdk.concretesyntax.OptionTypes; import org.emftext.sdk.util.ConcreteSyntaxUtil; /** * A generator for the plugin.xml file. * * TODO mseifert: make this generator reusable */ @SyntaxDependent public class PluginXMLGenerator extends ResourceBaseGenerator<ArtifactParameter<GenerationContext>> { private final NameUtil nameUtil = new NameUtil(); private ConcreteSyntaxUtil csUtil = new ConcreteSyntaxUtil(); private String pluginID; private String builderID; @Override public void doGenerate(PrintWriter out) { super.doGenerate(out); IPluginDescriptor resourcePlugin = getContext().getResourcePlugin(); pluginID = resourcePlugin.getName(); builderID = nameUtil.getBuilderID(getContext().getConcreteSyntax()); out.write(getContentOfPluginXML()); out.flush(); } /** * Generate the XML file describing the plug-in. * * @return Generated code. */ private String getContentOfPluginXML() { final ConcreteSyntax concreteSyntax = getContext().getConcreteSyntax(); final String primaryConcreteSyntaxName = csUtil.getPrimarySyntaxName(concreteSyntax); final String secondaryConcreteSyntaxName = csUtil.getSecondarySyntaxName(concreteSyntax); final String qualifiedResourceFactoryClassName; - if (secondaryConcreteSyntaxName != null) { + if (secondaryConcreteSyntaxName == null) { qualifiedResourceFactoryClassName = resourceFactoryDelegatorClassName; } else { qualifiedResourceFactoryClassName = resourceFactoryClassName; } final boolean disableBuilder = OptionManager.INSTANCE.getBooleanOptionValue(concreteSyntax, OptionTypes.DISABLE_BUILDER); StringComposite sc = new XMLComposite(); sc.add("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sc.add("<?eclipse version=\"3.2\"?>"); sc.add("<plugin>"); // register the syntax meta information String metaInformationClass = getContext().getQualifiedClassName(TextResourceArtifacts.META_INFORMATION); sc.add("<extension point=\"org.emftext.access.syntax\">"); sc.add("<metaInformationProvider class=\"" + metaInformationClass + "\" id=\"" + metaInformationClass + "\">"); sc.add("</metaInformationProvider>"); sc.add("</extension>"); sc.addLineBreak(); String problemID = pluginID + ".problem"; sc.add("<extension id=\"" + problemID + "\" name=\"EMFText Problem\" point=\"org.eclipse.core.resources.markers\">"); sc.add("<persistent value=\"true\">"); sc.add("</persistent>"); sc.add("<super type=\"org.eclipse.core.resources.problemmarker\">"); sc.add("</super>"); sc.add("<super type=\"org.eclipse.core.resources.textmarker\">"); sc.add("</super>"); sc.add("<super type=\"org.eclipse.emf.ecore.diagnostic\">"); sc.add("</super>"); sc.add("</extension>"); sc.addLineBreak(); for (PROBLEM_TYPES nextType : PROBLEM_TYPES.values()) { if (nextType == PROBLEM_TYPES.UNKNOWN) { continue; } String nextProblemTypeID = problemID + "." + nextType.name().toLowerCase(); sc.add("<extension id=\"" + nextProblemTypeID + "\" name=\"EMFText Problem\" point=\"org.eclipse.core.resources.markers\">"); sc.add("<persistent value=\"true\">"); sc.add("</persistent>"); sc.add("<super type=\"" + problemID + "\">"); sc.add("</super>"); sc.add("</extension>"); sc.addLineBreak(); } sc.add("<extension id=\"" + nameUtil.getNatureID(concreteSyntax) + "\" name=\"" + concreteSyntax.getName() + " nature\" point=\"org.eclipse.core.resources.natures\">"); sc.add("<runtime>"); sc.add("<run class=\"" + getContext().getQualifiedClassName(TextResourceArtifacts.NATURE)+ "\" />"); sc.add("</runtime>"); if (!disableBuilder) { sc.add("<builder id=\"" + builderID + "\" />"); } sc.add("</extension>"); sc.addLineBreak(); if (!disableBuilder) { sc.add("<extension point=\"org.eclipse.core.resources.builders\" id=\"" + builderID + "\" name=\"" + concreteSyntax.getName() + " Builder\">"); sc.add("<builder hasNature=\"true\">"); sc.add("<run class=\"" + getContext().getQualifiedClassName(TextResourceArtifacts.BUILDER_ADAPTER)+ "\" />"); sc.add("</builder>"); sc.add("</extension>"); sc.addLineBreak(); } sc.add("<extension-point id=\"" + pluginID + ".default_load_options\" name=\"Default Load Options\" schema=\"schema/default_load_options.exsd\"/>"); sc.addLineBreak(); String qualifiedBasePluginName = OptionManager.INSTANCE.getStringOptionValue(concreteSyntax, OptionTypes.BASE_RESOURCE_PLUGIN); if (secondaryConcreteSyntaxName == null) { // register the generated resource factory sc.add("<extension point=\"org.eclipse.emf.ecore.extension_parser\">"); sc.add("<parser class=\"" + qualifiedResourceFactoryClassName + "\" type=\"" + primaryConcreteSyntaxName + "\">"); sc.add("</parser>"); sc.add("</extension>"); sc.addLineBreak(); sc.add("<extension-point id=\"" + pluginID + ".additional_extension_parser\" name=\"Additional Extension Parser\" schema=\"schema/additional_extension_parser.exsd\"/>"); sc.addLineBreak(); } else if (qualifiedBasePluginName != null) { sc.add("<extension point=\""+ qualifiedBasePluginName + ".additional_extension_parser\">"); sc.add("<parser class=\"" + qualifiedResourceFactoryClassName + "\" type=\"" + secondaryConcreteSyntaxName + "\">"); sc.add("</parser>"); sc.add("</extension>"); sc.addLineBreak(); } sc.add("</plugin>"); return sc.toString(); } }
true
true
private String getContentOfPluginXML() { final ConcreteSyntax concreteSyntax = getContext().getConcreteSyntax(); final String primaryConcreteSyntaxName = csUtil.getPrimarySyntaxName(concreteSyntax); final String secondaryConcreteSyntaxName = csUtil.getSecondarySyntaxName(concreteSyntax); final String qualifiedResourceFactoryClassName; if (secondaryConcreteSyntaxName != null) { qualifiedResourceFactoryClassName = resourceFactoryDelegatorClassName; } else { qualifiedResourceFactoryClassName = resourceFactoryClassName; } final boolean disableBuilder = OptionManager.INSTANCE.getBooleanOptionValue(concreteSyntax, OptionTypes.DISABLE_BUILDER); StringComposite sc = new XMLComposite(); sc.add("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sc.add("<?eclipse version=\"3.2\"?>"); sc.add("<plugin>"); // register the syntax meta information String metaInformationClass = getContext().getQualifiedClassName(TextResourceArtifacts.META_INFORMATION); sc.add("<extension point=\"org.emftext.access.syntax\">"); sc.add("<metaInformationProvider class=\"" + metaInformationClass + "\" id=\"" + metaInformationClass + "\">"); sc.add("</metaInformationProvider>"); sc.add("</extension>"); sc.addLineBreak(); String problemID = pluginID + ".problem"; sc.add("<extension id=\"" + problemID + "\" name=\"EMFText Problem\" point=\"org.eclipse.core.resources.markers\">"); sc.add("<persistent value=\"true\">"); sc.add("</persistent>"); sc.add("<super type=\"org.eclipse.core.resources.problemmarker\">"); sc.add("</super>"); sc.add("<super type=\"org.eclipse.core.resources.textmarker\">"); sc.add("</super>"); sc.add("<super type=\"org.eclipse.emf.ecore.diagnostic\">"); sc.add("</super>"); sc.add("</extension>"); sc.addLineBreak(); for (PROBLEM_TYPES nextType : PROBLEM_TYPES.values()) { if (nextType == PROBLEM_TYPES.UNKNOWN) { continue; } String nextProblemTypeID = problemID + "." + nextType.name().toLowerCase(); sc.add("<extension id=\"" + nextProblemTypeID + "\" name=\"EMFText Problem\" point=\"org.eclipse.core.resources.markers\">"); sc.add("<persistent value=\"true\">"); sc.add("</persistent>"); sc.add("<super type=\"" + problemID + "\">"); sc.add("</super>"); sc.add("</extension>"); sc.addLineBreak(); } sc.add("<extension id=\"" + nameUtil.getNatureID(concreteSyntax) + "\" name=\"" + concreteSyntax.getName() + " nature\" point=\"org.eclipse.core.resources.natures\">"); sc.add("<runtime>"); sc.add("<run class=\"" + getContext().getQualifiedClassName(TextResourceArtifacts.NATURE)+ "\" />"); sc.add("</runtime>"); if (!disableBuilder) { sc.add("<builder id=\"" + builderID + "\" />"); } sc.add("</extension>"); sc.addLineBreak(); if (!disableBuilder) { sc.add("<extension point=\"org.eclipse.core.resources.builders\" id=\"" + builderID + "\" name=\"" + concreteSyntax.getName() + " Builder\">"); sc.add("<builder hasNature=\"true\">"); sc.add("<run class=\"" + getContext().getQualifiedClassName(TextResourceArtifacts.BUILDER_ADAPTER)+ "\" />"); sc.add("</builder>"); sc.add("</extension>"); sc.addLineBreak(); } sc.add("<extension-point id=\"" + pluginID + ".default_load_options\" name=\"Default Load Options\" schema=\"schema/default_load_options.exsd\"/>"); sc.addLineBreak(); String qualifiedBasePluginName = OptionManager.INSTANCE.getStringOptionValue(concreteSyntax, OptionTypes.BASE_RESOURCE_PLUGIN); if (secondaryConcreteSyntaxName == null) { // register the generated resource factory sc.add("<extension point=\"org.eclipse.emf.ecore.extension_parser\">"); sc.add("<parser class=\"" + qualifiedResourceFactoryClassName + "\" type=\"" + primaryConcreteSyntaxName + "\">"); sc.add("</parser>"); sc.add("</extension>"); sc.addLineBreak(); sc.add("<extension-point id=\"" + pluginID + ".additional_extension_parser\" name=\"Additional Extension Parser\" schema=\"schema/additional_extension_parser.exsd\"/>"); sc.addLineBreak(); } else if (qualifiedBasePluginName != null) { sc.add("<extension point=\""+ qualifiedBasePluginName + ".additional_extension_parser\">"); sc.add("<parser class=\"" + qualifiedResourceFactoryClassName + "\" type=\"" + secondaryConcreteSyntaxName + "\">"); sc.add("</parser>"); sc.add("</extension>"); sc.addLineBreak(); } sc.add("</plugin>"); return sc.toString(); }
private String getContentOfPluginXML() { final ConcreteSyntax concreteSyntax = getContext().getConcreteSyntax(); final String primaryConcreteSyntaxName = csUtil.getPrimarySyntaxName(concreteSyntax); final String secondaryConcreteSyntaxName = csUtil.getSecondarySyntaxName(concreteSyntax); final String qualifiedResourceFactoryClassName; if (secondaryConcreteSyntaxName == null) { qualifiedResourceFactoryClassName = resourceFactoryDelegatorClassName; } else { qualifiedResourceFactoryClassName = resourceFactoryClassName; } final boolean disableBuilder = OptionManager.INSTANCE.getBooleanOptionValue(concreteSyntax, OptionTypes.DISABLE_BUILDER); StringComposite sc = new XMLComposite(); sc.add("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sc.add("<?eclipse version=\"3.2\"?>"); sc.add("<plugin>"); // register the syntax meta information String metaInformationClass = getContext().getQualifiedClassName(TextResourceArtifacts.META_INFORMATION); sc.add("<extension point=\"org.emftext.access.syntax\">"); sc.add("<metaInformationProvider class=\"" + metaInformationClass + "\" id=\"" + metaInformationClass + "\">"); sc.add("</metaInformationProvider>"); sc.add("</extension>"); sc.addLineBreak(); String problemID = pluginID + ".problem"; sc.add("<extension id=\"" + problemID + "\" name=\"EMFText Problem\" point=\"org.eclipse.core.resources.markers\">"); sc.add("<persistent value=\"true\">"); sc.add("</persistent>"); sc.add("<super type=\"org.eclipse.core.resources.problemmarker\">"); sc.add("</super>"); sc.add("<super type=\"org.eclipse.core.resources.textmarker\">"); sc.add("</super>"); sc.add("<super type=\"org.eclipse.emf.ecore.diagnostic\">"); sc.add("</super>"); sc.add("</extension>"); sc.addLineBreak(); for (PROBLEM_TYPES nextType : PROBLEM_TYPES.values()) { if (nextType == PROBLEM_TYPES.UNKNOWN) { continue; } String nextProblemTypeID = problemID + "." + nextType.name().toLowerCase(); sc.add("<extension id=\"" + nextProblemTypeID + "\" name=\"EMFText Problem\" point=\"org.eclipse.core.resources.markers\">"); sc.add("<persistent value=\"true\">"); sc.add("</persistent>"); sc.add("<super type=\"" + problemID + "\">"); sc.add("</super>"); sc.add("</extension>"); sc.addLineBreak(); } sc.add("<extension id=\"" + nameUtil.getNatureID(concreteSyntax) + "\" name=\"" + concreteSyntax.getName() + " nature\" point=\"org.eclipse.core.resources.natures\">"); sc.add("<runtime>"); sc.add("<run class=\"" + getContext().getQualifiedClassName(TextResourceArtifacts.NATURE)+ "\" />"); sc.add("</runtime>"); if (!disableBuilder) { sc.add("<builder id=\"" + builderID + "\" />"); } sc.add("</extension>"); sc.addLineBreak(); if (!disableBuilder) { sc.add("<extension point=\"org.eclipse.core.resources.builders\" id=\"" + builderID + "\" name=\"" + concreteSyntax.getName() + " Builder\">"); sc.add("<builder hasNature=\"true\">"); sc.add("<run class=\"" + getContext().getQualifiedClassName(TextResourceArtifacts.BUILDER_ADAPTER)+ "\" />"); sc.add("</builder>"); sc.add("</extension>"); sc.addLineBreak(); } sc.add("<extension-point id=\"" + pluginID + ".default_load_options\" name=\"Default Load Options\" schema=\"schema/default_load_options.exsd\"/>"); sc.addLineBreak(); String qualifiedBasePluginName = OptionManager.INSTANCE.getStringOptionValue(concreteSyntax, OptionTypes.BASE_RESOURCE_PLUGIN); if (secondaryConcreteSyntaxName == null) { // register the generated resource factory sc.add("<extension point=\"org.eclipse.emf.ecore.extension_parser\">"); sc.add("<parser class=\"" + qualifiedResourceFactoryClassName + "\" type=\"" + primaryConcreteSyntaxName + "\">"); sc.add("</parser>"); sc.add("</extension>"); sc.addLineBreak(); sc.add("<extension-point id=\"" + pluginID + ".additional_extension_parser\" name=\"Additional Extension Parser\" schema=\"schema/additional_extension_parser.exsd\"/>"); sc.addLineBreak(); } else if (qualifiedBasePluginName != null) { sc.add("<extension point=\""+ qualifiedBasePluginName + ".additional_extension_parser\">"); sc.add("<parser class=\"" + qualifiedResourceFactoryClassName + "\" type=\"" + secondaryConcreteSyntaxName + "\">"); sc.add("</parser>"); sc.add("</extension>"); sc.addLineBreak(); } sc.add("</plugin>"); return sc.toString(); }
diff --git a/src/com/android/mms/transaction/SmsMessageSender.java b/src/com/android/mms/transaction/SmsMessageSender.java index 0aee539b..c59f147e 100644 --- a/src/com/android/mms/transaction/SmsMessageSender.java +++ b/src/com/android/mms/transaction/SmsMessageSender.java @@ -1,204 +1,204 @@ /* * Copyright (C) 2008 Esmertec AG. * Copyright (C) 2008 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.mms.transaction; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.database.sqlite.SqliteWrapper; import android.net.Uri; import android.preference.PreferenceManager; import android.provider.Telephony.Sms; import android.provider.Telephony.Sms.Inbox; import android.telephony.SmsMessage; import android.util.Log; import com.android.mms.LogTag; import com.android.mms.MmsConfig; import com.android.mms.ui.MessagingPreferenceActivity; import com.google.android.mms.MmsException; import java.util.ArrayList; public class SmsMessageSender implements MessageSender { protected final Context mContext; protected final int mNumberOfDests; private final String[] mDests; protected final String mMessageText; protected final String mServiceCenter; protected final long mThreadId; protected long mTimestamp; private static final String TAG = "SmsMessageSender"; // Default preference values private static final boolean DEFAULT_DELIVERY_REPORT_MODE = false; private static final boolean DEFAULT_SMS_SPLIT_COUNTER = false; private static final String[] SERVICE_CENTER_PROJECTION = new String[] { Sms.Conversations.REPLY_PATH_PRESENT, Sms.Conversations.SERVICE_CENTER, }; private static final int COLUMN_REPLY_PATH_PRESENT = 0; private static final int COLUMN_SERVICE_CENTER = 1; public SmsMessageSender(Context context, String[] dests, String msgText, long threadId) { mContext = context; mMessageText = msgText; if (dests != null) { mNumberOfDests = dests.length; mDests = new String[mNumberOfDests]; System.arraycopy(dests, 0, mDests, 0, mNumberOfDests); } else { mNumberOfDests = 0; mDests = null; } mTimestamp = System.currentTimeMillis(); mThreadId = threadId; mServiceCenter = getOutgoingServiceCenter(mThreadId); } public boolean sendMessage(long token) throws MmsException { // In order to send the message one by one, instead of sending now, the message will split, // and be put into the queue along with each destinations return queueMessage(token); } private boolean queueMessage(long token) throws MmsException { if ((mMessageText == null) || (mNumberOfDests == 0)) { // Don't try to send an empty message. throw new MmsException("Null message body or dest."); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); boolean requestDeliveryReport = prefs.getBoolean( MessagingPreferenceActivity.SMS_DELIVERY_REPORT_MODE, DEFAULT_DELIVERY_REPORT_MODE); boolean splitMessage = MmsConfig.getSplitSmsEnabled(); boolean splitCounter = prefs.getBoolean( MessagingPreferenceActivity.SMS_SPLIT_COUNTER, DEFAULT_SMS_SPLIT_COUNTER); int[] params = SmsMessage.calculateLength(mMessageText, false); /* SmsMessage.calculateLength returns an int[4] with: * int[0] being the number of SMS's required, * int[1] the number of code units used, * int[2] is the number of code units remaining until the next message. * int[3] is the encoding type that should be used for the message. */ int nSmsPages = params[0]; // To split or not to split, that is THE question! if (splitMessage && (nSmsPages > 1)) { // Split the message by encoding ArrayList<String> MessageBody = SmsMessage.fragmentText(mMessageText); // Start send loop for split messages for(int page = 0; page < nSmsPages; page++) { // Adds counter at end of message if(splitCounter) { String counterText = MessageBody.get(page) + "(" + (page + 1) + "/" + nSmsPages + ")"; MessageBody.set(page, counterText); } for (int i = 0; i < mNumberOfDests; i++) { try { Sms.addMessageToUri(mContext.getContentResolver(), Uri.parse("content://sms/queued"), mDests[i], MessageBody.get(page), null, mTimestamp, true /* read */, requestDeliveryReport, mThreadId); } catch (SQLiteException e) { SqliteWrapper.checkSQLiteException(mContext, e); } } } } else { // Send without split or counter for (int i = 0; i < mNumberOfDests; i++) { try { if (LogTag.DEBUG_SEND) { Log.v(TAG, "queueMessage mDests[i]: " + mDests[i] + " mThreadId: " + mThreadId); } Sms.addMessageToUri(mContext.getContentResolver(), Uri.parse("content://sms/queued"), mDests[i], mMessageText, null, mTimestamp, true /* read */, requestDeliveryReport, mThreadId); } catch (SQLiteException e) { if (LogTag.DEBUG_SEND) { Log.e(TAG, "queueMessage SQLiteException", e); } SqliteWrapper.checkSQLiteException(mContext, e); } } } // Notify the SmsReceiverService to send the message out mContext.sendBroadcast(new Intent(SmsReceiverService.ACTION_SEND_MESSAGE, null, mContext, - SmsReceiver.class)); + PrivilegedSmsReceiver.class)); return false; } /** * Get the service center to use for a reply. * * The rule from TS 23.040 D.6 is that we send reply messages to * the service center of the message to which we're replying, but * only if we haven't already replied to that message and only if * <code>TP-Reply-Path</code> was set in that message. * * Therefore, return the service center from the most recent * message in the conversation, but only if it is a message from * the other party, and only if <code>TP-Reply-Path</code> is set. * Otherwise, return null. */ private String getOutgoingServiceCenter(long threadId) { Cursor cursor = null; try { cursor = SqliteWrapper.query(mContext, mContext.getContentResolver(), Inbox.CONTENT_URI, SERVICE_CENTER_PROJECTION, "thread_id = " + threadId, null, "date DESC"); if ((cursor == null) || !cursor.moveToFirst()) { return null; } boolean replyPathPresent = (1 == cursor.getInt(COLUMN_REPLY_PATH_PRESENT)); return replyPathPresent ? cursor.getString(COLUMN_SERVICE_CENTER) : null; } finally { if (cursor != null) { cursor.close(); } } } private void log(String msg) { Log.d(LogTag.TAG, "[SmsMsgSender] " + msg); } }
true
true
private boolean queueMessage(long token) throws MmsException { if ((mMessageText == null) || (mNumberOfDests == 0)) { // Don't try to send an empty message. throw new MmsException("Null message body or dest."); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); boolean requestDeliveryReport = prefs.getBoolean( MessagingPreferenceActivity.SMS_DELIVERY_REPORT_MODE, DEFAULT_DELIVERY_REPORT_MODE); boolean splitMessage = MmsConfig.getSplitSmsEnabled(); boolean splitCounter = prefs.getBoolean( MessagingPreferenceActivity.SMS_SPLIT_COUNTER, DEFAULT_SMS_SPLIT_COUNTER); int[] params = SmsMessage.calculateLength(mMessageText, false); /* SmsMessage.calculateLength returns an int[4] with: * int[0] being the number of SMS's required, * int[1] the number of code units used, * int[2] is the number of code units remaining until the next message. * int[3] is the encoding type that should be used for the message. */ int nSmsPages = params[0]; // To split or not to split, that is THE question! if (splitMessage && (nSmsPages > 1)) { // Split the message by encoding ArrayList<String> MessageBody = SmsMessage.fragmentText(mMessageText); // Start send loop for split messages for(int page = 0; page < nSmsPages; page++) { // Adds counter at end of message if(splitCounter) { String counterText = MessageBody.get(page) + "(" + (page + 1) + "/" + nSmsPages + ")"; MessageBody.set(page, counterText); } for (int i = 0; i < mNumberOfDests; i++) { try { Sms.addMessageToUri(mContext.getContentResolver(), Uri.parse("content://sms/queued"), mDests[i], MessageBody.get(page), null, mTimestamp, true /* read */, requestDeliveryReport, mThreadId); } catch (SQLiteException e) { SqliteWrapper.checkSQLiteException(mContext, e); } } } } else { // Send without split or counter for (int i = 0; i < mNumberOfDests; i++) { try { if (LogTag.DEBUG_SEND) { Log.v(TAG, "queueMessage mDests[i]: " + mDests[i] + " mThreadId: " + mThreadId); } Sms.addMessageToUri(mContext.getContentResolver(), Uri.parse("content://sms/queued"), mDests[i], mMessageText, null, mTimestamp, true /* read */, requestDeliveryReport, mThreadId); } catch (SQLiteException e) { if (LogTag.DEBUG_SEND) { Log.e(TAG, "queueMessage SQLiteException", e); } SqliteWrapper.checkSQLiteException(mContext, e); } } } // Notify the SmsReceiverService to send the message out mContext.sendBroadcast(new Intent(SmsReceiverService.ACTION_SEND_MESSAGE, null, mContext, SmsReceiver.class)); return false; }
private boolean queueMessage(long token) throws MmsException { if ((mMessageText == null) || (mNumberOfDests == 0)) { // Don't try to send an empty message. throw new MmsException("Null message body or dest."); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); boolean requestDeliveryReport = prefs.getBoolean( MessagingPreferenceActivity.SMS_DELIVERY_REPORT_MODE, DEFAULT_DELIVERY_REPORT_MODE); boolean splitMessage = MmsConfig.getSplitSmsEnabled(); boolean splitCounter = prefs.getBoolean( MessagingPreferenceActivity.SMS_SPLIT_COUNTER, DEFAULT_SMS_SPLIT_COUNTER); int[] params = SmsMessage.calculateLength(mMessageText, false); /* SmsMessage.calculateLength returns an int[4] with: * int[0] being the number of SMS's required, * int[1] the number of code units used, * int[2] is the number of code units remaining until the next message. * int[3] is the encoding type that should be used for the message. */ int nSmsPages = params[0]; // To split or not to split, that is THE question! if (splitMessage && (nSmsPages > 1)) { // Split the message by encoding ArrayList<String> MessageBody = SmsMessage.fragmentText(mMessageText); // Start send loop for split messages for(int page = 0; page < nSmsPages; page++) { // Adds counter at end of message if(splitCounter) { String counterText = MessageBody.get(page) + "(" + (page + 1) + "/" + nSmsPages + ")"; MessageBody.set(page, counterText); } for (int i = 0; i < mNumberOfDests; i++) { try { Sms.addMessageToUri(mContext.getContentResolver(), Uri.parse("content://sms/queued"), mDests[i], MessageBody.get(page), null, mTimestamp, true /* read */, requestDeliveryReport, mThreadId); } catch (SQLiteException e) { SqliteWrapper.checkSQLiteException(mContext, e); } } } } else { // Send without split or counter for (int i = 0; i < mNumberOfDests; i++) { try { if (LogTag.DEBUG_SEND) { Log.v(TAG, "queueMessage mDests[i]: " + mDests[i] + " mThreadId: " + mThreadId); } Sms.addMessageToUri(mContext.getContentResolver(), Uri.parse("content://sms/queued"), mDests[i], mMessageText, null, mTimestamp, true /* read */, requestDeliveryReport, mThreadId); } catch (SQLiteException e) { if (LogTag.DEBUG_SEND) { Log.e(TAG, "queueMessage SQLiteException", e); } SqliteWrapper.checkSQLiteException(mContext, e); } } } // Notify the SmsReceiverService to send the message out mContext.sendBroadcast(new Intent(SmsReceiverService.ACTION_SEND_MESSAGE, null, mContext, PrivilegedSmsReceiver.class)); return false; }
diff --git a/src/main/java/org/amplafi/flow/utils/LoadTool.java b/src/main/java/org/amplafi/flow/utils/LoadTool.java index b6ea92f..2f1a666 100755 --- a/src/main/java/org/amplafi/flow/utils/LoadTool.java +++ b/src/main/java/org/amplafi/flow/utils/LoadTool.java @@ -1,268 +1,268 @@ package org.amplafi.flow.utils; import java.io.*; import java.net.*; import java.util.LinkedHashMap; import java.util.Map; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.amplafi.dsl.ScriptRunner; import org.apache.commons.cli.ParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import static org.amplafi.flow.utils.LoadToolCommandLineOptions.*; import java.util.EnumSet; /** * Tool for load testing the wire server. * @author paul */ public class LoadTool extends UtilParent{ /** * Main method for proxy server. * See TestGenerationProxyCommandLineOptions for usage. */ public static void main(String[] args) throws IOException { LoadTool proxy = new LoadTool(); try { proxy.processCommandLine(args); } catch (Exception e) { proxy.getLog().error(e); } } private Log log; private static final String THICK_DIVIDER = "*********************************************************************************"; public LoadTool(){ } /** File to write the test report to. If null write to screen. */ private String reportFile; private boolean running = true; /** * Process command line and run the server. * @param args */ public void processCommandLine(String[] args) { // Process command line options. LoadToolCommandLineOptions cmdOptions = null; try { cmdOptions = new LoadToolCommandLineOptions(args); } catch (ParseException e) { getLog().error("Could not parse passed arguments, message:", e); return; } // Print help if there has no args. if (args.length == 0) { cmdOptions.printHelp(); return; } if (!cmdOptions.hasOption(HOST)){ getLog().error("You must specify the host."); } if (!cmdOptions.hasOption(HOST_PORT) ){ getLog().error("You must specify the host post."); } if (!cmdOptions.hasOption(SCRIPT) ){ getLog().error("You must specify the script to run."); } if (cmdOptions.hasOption(HOST) && cmdOptions.hasOption(HOST_PORT) && cmdOptions.hasOption(SCRIPT) ) { int remotePort = -1; int numThreads = 1; int frequency = -1; try { remotePort = Integer.parseInt(cmdOptions.getOptionValue(HOST_PORT)); } catch (NumberFormatException nfe) { getLog().error("Remote port should be in numeric form e.g. 80"); return; } String host = cmdOptions.getOptionValue(HOST); String reportFile = cmdOptions.getOptionValue(REPORT); String scriptName = cmdOptions.getOptionValue(SCRIPT); try { if (cmdOptions.hasOption(NUM_THREADS)){ numThreads = Integer.parseInt(cmdOptions.getOptionValue(NUM_THREADS)); } } catch (NumberFormatException nfe) { getLog().error("numThreads should be in numeric form e.g. 10 , defaulting to 1."); } try { if (cmdOptions.hasOption(FREQUENCY)){ frequency = Integer.parseInt(cmdOptions.getOptionValue(FREQUENCY)); } } catch (NumberFormatException nfe) { getLog().error("frequency should be in numeric form e.g. 10 , defaulting to -1 = max possible."); } // Register shutdown handler. Runtime.getRuntime().addShutdownHook(new Thread(){ public void run() { getLog().info("Generating Report. Please Wait..."); // signal threads to stop running = false; // Wait for all threads to stop for (Thread t : threads){ try { t.join(); } catch (InterruptedException ie){ getLog().error("Error",ie); } } // Loop over the ThreadReports int threadNum = 1; - long totalTime = 0; - long totalCalls = 0; + double totalTime = 0; + double totalCalls = 0; getLog().info(THICK_DIVIDER); for (Thread t : threads){ ThreadReport rep = threadReports.get(t); totalTime = rep.endTime - rep.startTime; getLog().info("threadNum" + threadNum + ": calls " + rep.callCount + " in " + (totalTime/1000) + "s. average = " + (rep.callCount*1000/totalTime) + " calls per second. Error count " + rep.errorCount); totalCalls += rep.callCount; threadNum++; } getLog().info(THICK_DIVIDER); getLog().info("Total calls in all threads=" + totalCalls + " " + (totalCalls*1000/totalTime) + " calls per second" ); getLog().info(THICK_DIVIDER); // TODO output above to file or speadsheet // TODO output time variant call data to speadsheet } }); String key = ""; try { key = getOption(cmdOptions, API_KEY, ""); } catch (IOException ioe) { getLog().error("Reading API Key", ioe); return; } try { runLoadTest(host, key, remotePort, scriptName, numThreads, frequency ); // never returns } catch (IOException ioe) { getLog().error("Error running proxy", ioe); return; } } } // Never accessed by multiple threads private List<Thread> threads = new ArrayList<Thread>(); // Never accessed by multiple threads private Map<Thread,ThreadReport> threadReports = new LinkedHashMap(); /** * runs a single-threaded proxy server on * the specified local port. It never returns. */ public void runLoadTest(final String host,final String key,final int port,final String scriptName,final int numThreads,final int frequency ) throws IOException { getLog().info("Running LoadTest with host=" + host + " host port=" + port + " script=" + scriptName + " numThreads=" + numThreads + " frequency=" + frequency); getLog().info("Press Ctrl+C to stop"); for (int i=0; i<numThreads ; i++ ){ final ThreadReport report = new ThreadReport(); Thread thread = new Thread(new Runnable(){ public void run() { ScriptRunner scriptRunner = new ScriptRunner(host, ""+port, "apiv1", key); try { // don't include the first run because this includes // constructing gropvy runtime. scriptRunner.loadAndRunOneScript(scriptName); report.startTime = System.currentTimeMillis(); while (running){ try { report.callCount++; long startTime = System.currentTimeMillis(); scriptRunner.reRunLastScript(); long endTime = System.currentTimeMillis(); long duration = (endTime - startTime); if (frequency != -1 ){ int requiredDurationMS = 1000/frequency; if (duration < requiredDurationMS){ long pause = requiredDurationMS - duration; Thread.currentThread().sleep(pause); } } report.callTimes.add(duration); } catch (Throwable t){ report.errors.add(t); report.errorCount++; } } report.endTime = System.currentTimeMillis(); } catch (Throwable t){ getLog().error("Error on first run",t); } }// End run }); threads.add(thread); threadReports.put(thread, report); } for (Thread t : threads){ t.start(); } } /** * Get the logger for this class. */ public Log getLog() { if ( this.log == null ) { this.log = LogFactory.getLog(this.getClass()); } return this.log; } /** * This class holds the load test for a single thread. */ private class ThreadReport { int callCount = 0; int errorCount = 0; List<Throwable> errors = new ArrayList<Throwable>(); long startTime = 0; long endTime = 0; List<Long> callTimes = new ArrayList<Long>(); } }
true
true
public void processCommandLine(String[] args) { // Process command line options. LoadToolCommandLineOptions cmdOptions = null; try { cmdOptions = new LoadToolCommandLineOptions(args); } catch (ParseException e) { getLog().error("Could not parse passed arguments, message:", e); return; } // Print help if there has no args. if (args.length == 0) { cmdOptions.printHelp(); return; } if (!cmdOptions.hasOption(HOST)){ getLog().error("You must specify the host."); } if (!cmdOptions.hasOption(HOST_PORT) ){ getLog().error("You must specify the host post."); } if (!cmdOptions.hasOption(SCRIPT) ){ getLog().error("You must specify the script to run."); } if (cmdOptions.hasOption(HOST) && cmdOptions.hasOption(HOST_PORT) && cmdOptions.hasOption(SCRIPT) ) { int remotePort = -1; int numThreads = 1; int frequency = -1; try { remotePort = Integer.parseInt(cmdOptions.getOptionValue(HOST_PORT)); } catch (NumberFormatException nfe) { getLog().error("Remote port should be in numeric form e.g. 80"); return; } String host = cmdOptions.getOptionValue(HOST); String reportFile = cmdOptions.getOptionValue(REPORT); String scriptName = cmdOptions.getOptionValue(SCRIPT); try { if (cmdOptions.hasOption(NUM_THREADS)){ numThreads = Integer.parseInt(cmdOptions.getOptionValue(NUM_THREADS)); } } catch (NumberFormatException nfe) { getLog().error("numThreads should be in numeric form e.g. 10 , defaulting to 1."); } try { if (cmdOptions.hasOption(FREQUENCY)){ frequency = Integer.parseInt(cmdOptions.getOptionValue(FREQUENCY)); } } catch (NumberFormatException nfe) { getLog().error("frequency should be in numeric form e.g. 10 , defaulting to -1 = max possible."); } // Register shutdown handler. Runtime.getRuntime().addShutdownHook(new Thread(){ public void run() { getLog().info("Generating Report. Please Wait..."); // signal threads to stop running = false; // Wait for all threads to stop for (Thread t : threads){ try { t.join(); } catch (InterruptedException ie){ getLog().error("Error",ie); } } // Loop over the ThreadReports int threadNum = 1; long totalTime = 0; long totalCalls = 0; getLog().info(THICK_DIVIDER); for (Thread t : threads){ ThreadReport rep = threadReports.get(t); totalTime = rep.endTime - rep.startTime; getLog().info("threadNum" + threadNum + ": calls " + rep.callCount + " in " + (totalTime/1000) + "s. average = " + (rep.callCount*1000/totalTime) + " calls per second. Error count " + rep.errorCount); totalCalls += rep.callCount; threadNum++; } getLog().info(THICK_DIVIDER); getLog().info("Total calls in all threads=" + totalCalls + " " + (totalCalls*1000/totalTime) + " calls per second" ); getLog().info(THICK_DIVIDER); // TODO output above to file or speadsheet // TODO output time variant call data to speadsheet } }); String key = ""; try { key = getOption(cmdOptions, API_KEY, ""); } catch (IOException ioe) { getLog().error("Reading API Key", ioe); return; } try { runLoadTest(host, key, remotePort, scriptName, numThreads, frequency ); // never returns } catch (IOException ioe) { getLog().error("Error running proxy", ioe); return; } } }
public void processCommandLine(String[] args) { // Process command line options. LoadToolCommandLineOptions cmdOptions = null; try { cmdOptions = new LoadToolCommandLineOptions(args); } catch (ParseException e) { getLog().error("Could not parse passed arguments, message:", e); return; } // Print help if there has no args. if (args.length == 0) { cmdOptions.printHelp(); return; } if (!cmdOptions.hasOption(HOST)){ getLog().error("You must specify the host."); } if (!cmdOptions.hasOption(HOST_PORT) ){ getLog().error("You must specify the host post."); } if (!cmdOptions.hasOption(SCRIPT) ){ getLog().error("You must specify the script to run."); } if (cmdOptions.hasOption(HOST) && cmdOptions.hasOption(HOST_PORT) && cmdOptions.hasOption(SCRIPT) ) { int remotePort = -1; int numThreads = 1; int frequency = -1; try { remotePort = Integer.parseInt(cmdOptions.getOptionValue(HOST_PORT)); } catch (NumberFormatException nfe) { getLog().error("Remote port should be in numeric form e.g. 80"); return; } String host = cmdOptions.getOptionValue(HOST); String reportFile = cmdOptions.getOptionValue(REPORT); String scriptName = cmdOptions.getOptionValue(SCRIPT); try { if (cmdOptions.hasOption(NUM_THREADS)){ numThreads = Integer.parseInt(cmdOptions.getOptionValue(NUM_THREADS)); } } catch (NumberFormatException nfe) { getLog().error("numThreads should be in numeric form e.g. 10 , defaulting to 1."); } try { if (cmdOptions.hasOption(FREQUENCY)){ frequency = Integer.parseInt(cmdOptions.getOptionValue(FREQUENCY)); } } catch (NumberFormatException nfe) { getLog().error("frequency should be in numeric form e.g. 10 , defaulting to -1 = max possible."); } // Register shutdown handler. Runtime.getRuntime().addShutdownHook(new Thread(){ public void run() { getLog().info("Generating Report. Please Wait..."); // signal threads to stop running = false; // Wait for all threads to stop for (Thread t : threads){ try { t.join(); } catch (InterruptedException ie){ getLog().error("Error",ie); } } // Loop over the ThreadReports int threadNum = 1; double totalTime = 0; double totalCalls = 0; getLog().info(THICK_DIVIDER); for (Thread t : threads){ ThreadReport rep = threadReports.get(t); totalTime = rep.endTime - rep.startTime; getLog().info("threadNum" + threadNum + ": calls " + rep.callCount + " in " + (totalTime/1000) + "s. average = " + (rep.callCount*1000/totalTime) + " calls per second. Error count " + rep.errorCount); totalCalls += rep.callCount; threadNum++; } getLog().info(THICK_DIVIDER); getLog().info("Total calls in all threads=" + totalCalls + " " + (totalCalls*1000/totalTime) + " calls per second" ); getLog().info(THICK_DIVIDER); // TODO output above to file or speadsheet // TODO output time variant call data to speadsheet } }); String key = ""; try { key = getOption(cmdOptions, API_KEY, ""); } catch (IOException ioe) { getLog().error("Reading API Key", ioe); return; } try { runLoadTest(host, key, remotePort, scriptName, numThreads, frequency ); // never returns } catch (IOException ioe) { getLog().error("Error running proxy", ioe); return; } } }
diff --git a/jwf.struts1/src/strutsdemo/InsertAction.java b/jwf.struts1/src/strutsdemo/InsertAction.java index 38aae8f..6263279 100644 --- a/jwf.struts1/src/strutsdemo/InsertAction.java +++ b/jwf.struts1/src/strutsdemo/InsertAction.java @@ -1,69 +1,68 @@ package struts; import beans.Person; import beans.PersonDAO; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.DynaActionForm; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import java.util.List; import javax.servlet.http.*; /** The Struts "Action" to do the insert of a Person into the Database. * @author Ian F. Darwin * @version $Id$ */ public class InsertAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ActionErrors errors = new ActionErrors(); // Get the ActionForm DynaActionForm f = (DynaActionForm)form; // Populate a Person bean Person person = new Person(); person.setFirstName((String)f.get("firstName")); person.setLastName((String)f.get("lastName")); person.setEmail((String)f.get("email")); person.setAddress1((String)f.get("address1")); person.setAddress2((String)f.get("address2")); person.setCity((String)f.get("city")); person.setProvince((String)f.get("province")); person.setPostcode((String)f.get("postcode")); person.setCountry((String)f.get("country")); // If inputs not valid, process as error. if (!person.isValid()) { List errs = person.getErrors(); StringBuffer fields = new StringBuffer(); for (int i = 0; i < errs.size(); i++) { if (i > 0) fields.append(", "); fields.append(errs.get(i)); } errors.add(ActionErrors.GLOBAL_ERROR, - // XXX get this string from the global resources... - new ActionError("Fields need attention: " + fields)); + new ActionError("error.fields.attention", fields)); saveErrors(request, errors); return new ActionForward(mapping.getInput()); } // Data is OK, so try to store it in the database. try { new PersonDAO().insert(person); } catch (Exception ex) { errors.add(ActionErrors.GLOBAL_ERROR, - new ActionError("Database problem: " + ex)); + new ActionError("error.database.problem", ex.toString())); saveErrors(request, errors); return new ActionForward(mapping.getInput()); } return mapping.findForward("success"); } }
false
true
public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ActionErrors errors = new ActionErrors(); // Get the ActionForm DynaActionForm f = (DynaActionForm)form; // Populate a Person bean Person person = new Person(); person.setFirstName((String)f.get("firstName")); person.setLastName((String)f.get("lastName")); person.setEmail((String)f.get("email")); person.setAddress1((String)f.get("address1")); person.setAddress2((String)f.get("address2")); person.setCity((String)f.get("city")); person.setProvince((String)f.get("province")); person.setPostcode((String)f.get("postcode")); person.setCountry((String)f.get("country")); // If inputs not valid, process as error. if (!person.isValid()) { List errs = person.getErrors(); StringBuffer fields = new StringBuffer(); for (int i = 0; i < errs.size(); i++) { if (i > 0) fields.append(", "); fields.append(errs.get(i)); } errors.add(ActionErrors.GLOBAL_ERROR, // XXX get this string from the global resources... new ActionError("Fields need attention: " + fields)); saveErrors(request, errors); return new ActionForward(mapping.getInput()); } // Data is OK, so try to store it in the database. try { new PersonDAO().insert(person); } catch (Exception ex) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("Database problem: " + ex)); saveErrors(request, errors); return new ActionForward(mapping.getInput()); } return mapping.findForward("success"); }
public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ActionErrors errors = new ActionErrors(); // Get the ActionForm DynaActionForm f = (DynaActionForm)form; // Populate a Person bean Person person = new Person(); person.setFirstName((String)f.get("firstName")); person.setLastName((String)f.get("lastName")); person.setEmail((String)f.get("email")); person.setAddress1((String)f.get("address1")); person.setAddress2((String)f.get("address2")); person.setCity((String)f.get("city")); person.setProvince((String)f.get("province")); person.setPostcode((String)f.get("postcode")); person.setCountry((String)f.get("country")); // If inputs not valid, process as error. if (!person.isValid()) { List errs = person.getErrors(); StringBuffer fields = new StringBuffer(); for (int i = 0; i < errs.size(); i++) { if (i > 0) fields.append(", "); fields.append(errs.get(i)); } errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.fields.attention", fields)); saveErrors(request, errors); return new ActionForward(mapping.getInput()); } // Data is OK, so try to store it in the database. try { new PersonDAO().insert(person); } catch (Exception ex) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.database.problem", ex.toString())); saveErrors(request, errors); return new ActionForward(mapping.getInput()); } return mapping.findForward("success"); }
diff --git a/src/eu/bryants/anthony/plinth/ast/LexicalPhrase.java b/src/eu/bryants/anthony/plinth/ast/LexicalPhrase.java index 35c7732..25b2d95 100644 --- a/src/eu/bryants/anthony/plinth/ast/LexicalPhrase.java +++ b/src/eu/bryants/anthony/plinth/ast/LexicalPhrase.java @@ -1,155 +1,154 @@ package eu.bryants.anthony.plinth.ast; /* * Created on 5 Aug 2010 */ /** * An immutable class which stores information from the parser, such as the location in a file that something came from. * @author Anthony Bryant */ public class LexicalPhrase { private String path; private int line; private String lineText; private int startColumn; private int endColumn; /** * Creates a new LexicalPhrase object to represent the specified location. * @param path - the path to the file that this LexicalPhrase is inside * @param line - the line number * @param lineText - the text of the line * @param column - the column on the line to represent */ public LexicalPhrase(String path, int line, String lineText, int column) { this(path, line, lineText, column, column + 1); } /** * Creates a new LexicalPhrase object to represent the specified range of characters on a single line * @param path - the path to the file that this LexicalPhrase is inside * @param line - the line number * @param lineText - the text of the line * @param startColumn - the start column on the line * @param endColumn - the end column on the line + 1 (so that end - start == length) */ public LexicalPhrase(String path, int line, String lineText, int startColumn, int endColumn) { this.path = path; this.line = line; this.lineText = lineText; this.startColumn = startColumn; this.endColumn = endColumn; } /** * Creates a new LexicalPhrase object containing the line number from the first object, and the start and end column info the range of columns used on the first line * @param lexicalPhrases - the LexicalPhrase objects to combine * @return a LexicalPhrase object representing all of the specified LexicalPhrase objects, or null if all specified inputs are null */ public static LexicalPhrase combine(LexicalPhrase... lexicalPhrases) { LexicalPhrase combined = null; for (LexicalPhrase phrase : lexicalPhrases) { if (phrase == null) { continue; } - {} // TODO: fix multi-line phrases if (combined == null) { combined = new LexicalPhrase(phrase.getPath(), phrase.getLine(), phrase.getLineText(), phrase.getStartColumn(), phrase.getEndColumn()); } - else + else if (combined.getLine() == phrase.getLine()) { combined.startColumn = Math.min(combined.getStartColumn(), phrase.getStartColumn()); combined.endColumn = Math.max(combined.getEndColumn(), phrase.getEndColumn()); } } return combined; } /** * @return the path */ public String getPath() { return path; } /** * @return the line */ public int getLine() { return line; } /** * @return the lineText */ public String getLineText() { return lineText; } /** * @return the startColumn */ public int getStartColumn() { return startColumn; } /** * @return the endColumn */ public int getEndColumn() { return endColumn; } /** * @return the location information that this object represents, as a human readable string */ public String getLocationText() { StringBuffer buffer = new StringBuffer(); buffer.append(path); buffer.append(": "); buffer.append(line); buffer.append(':'); buffer.append(startColumn); if (startColumn < endColumn - 1) { buffer.append('-'); buffer.append(endColumn); } return buffer.toString(); } /** * @return the line text of this object, concatenated with a newline and some space and caret ('^') characters pointing to the part of the line that this object represents */ public String getHighlightedLine() { StringBuffer buffer = new StringBuffer(); buffer.append(lineText); buffer.append('\n'); for (int i = 1; i < startColumn && i <= lineText.length(); i++) { buffer.append(' '); } for (int i = startColumn; i < endColumn && i <= lineText.length() + 1; i++) { buffer.append('^'); } return buffer.toString(); } }
false
true
public static LexicalPhrase combine(LexicalPhrase... lexicalPhrases) { LexicalPhrase combined = null; for (LexicalPhrase phrase : lexicalPhrases) { if (phrase == null) { continue; } {} // TODO: fix multi-line phrases if (combined == null) { combined = new LexicalPhrase(phrase.getPath(), phrase.getLine(), phrase.getLineText(), phrase.getStartColumn(), phrase.getEndColumn()); } else { combined.startColumn = Math.min(combined.getStartColumn(), phrase.getStartColumn()); combined.endColumn = Math.max(combined.getEndColumn(), phrase.getEndColumn()); } } return combined; }
public static LexicalPhrase combine(LexicalPhrase... lexicalPhrases) { LexicalPhrase combined = null; for (LexicalPhrase phrase : lexicalPhrases) { if (phrase == null) { continue; } if (combined == null) { combined = new LexicalPhrase(phrase.getPath(), phrase.getLine(), phrase.getLineText(), phrase.getStartColumn(), phrase.getEndColumn()); } else if (combined.getLine() == phrase.getLine()) { combined.startColumn = Math.min(combined.getStartColumn(), phrase.getStartColumn()); combined.endColumn = Math.max(combined.getEndColumn(), phrase.getEndColumn()); } } return combined; }
diff --git a/src/test/org/apache/hadoop/mapred/TestTrackerBlacklistAcrossJobs.java b/src/test/org/apache/hadoop/mapred/TestTrackerBlacklistAcrossJobs.java index ef4fa5540..453da1371 100644 --- a/src/test/org/apache/hadoop/mapred/TestTrackerBlacklistAcrossJobs.java +++ b/src/test/org/apache/hadoop/mapred/TestTrackerBlacklistAcrossJobs.java @@ -1,108 +1,108 @@ /** * 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.mapred; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.examples.SleepJob.SleepInputFormat; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapred.lib.NullOutputFormat; import junit.framework.TestCase; public class TestTrackerBlacklistAcrossJobs extends TestCase { private static final String hosts[] = new String[] { "host1.rack.com", "host2.rack.com", "host3.rack.com" }; final Path inDir = new Path("/testing"); final Path outDir = new Path("/output"); public static class SleepJobFailOnHost extends MapReduceBase implements Mapper<IntWritable, IntWritable, IntWritable, NullWritable> { String hostname = ""; public void configure(JobConf job) { this.hostname = job.get("slave.host.name"); } public void map(IntWritable key, IntWritable value, OutputCollector<IntWritable, NullWritable> output, Reporter reporter) throws IOException { if (this.hostname.equals(hosts[0])) { // fail here throw new IOException("failing on host: " + hosts[0]); } } } public void testBlacklistAcrossJobs() throws IOException { MiniDFSCluster dfs = null; MiniMRCluster mr = null; FileSystem fileSys = null; Configuration conf = new Configuration(); // setup dfs and input dfs = new MiniDFSCluster(conf, 1, true, null, hosts); fileSys = dfs.getFileSystem(); if (!fileSys.mkdirs(inDir)) { throw new IOException("Mkdirs failed to create " + inDir.toString()); } - TestRackAwareTaskPlacement.writeFile(dfs.getNameNode(), conf, + UtilsForTests.writeFile(dfs.getNameNode(), conf, new Path(inDir + "/file"), (short) 1); // start mr cluster JobConf jtConf = new JobConf(); jtConf.setInt("mapred.max.tracker.failures", 1); jtConf.setInt("mapred.max.tracker.blacklists", 1); mr = new MiniMRCluster(3, fileSys.getUri().toString(), 1, null, hosts, jtConf); // setup job configuration JobConf mrConf = mr.createJobConf(); JobConf job = new JobConf(mrConf); job.setNumMapTasks(30); job.setNumReduceTasks(0); job.setMapperClass(SleepJobFailOnHost.class); job.setMapOutputKeyClass(IntWritable.class); job.setMapOutputValueClass(NullWritable.class); job.setOutputFormat(NullOutputFormat.class); job.setInputFormat(SleepInputFormat.class); FileInputFormat.setInputPaths(job, inDir); FileOutputFormat.setOutputPath(job, outDir); // run the job JobClient jc = new JobClient(mrConf); RunningJob running = JobClient.runJob(job); assertEquals("Job failed", JobStatus.SUCCEEDED, running.getJobState()); assertEquals("Didn't blacklist the host", 1, jc.getClusterStatus().getBlacklistedTrackers()); assertEquals("Fault count should be 1", 1, mr.getFaultCount(hosts[0])); // run the same job once again // there should be no change in blacklist count running = JobClient.runJob(job); assertEquals("Job failed", JobStatus.SUCCEEDED, running.getJobState()); assertEquals("Didn't blacklist the host", 1, jc.getClusterStatus().getBlacklistedTrackers()); assertEquals("Fault count should be 1", 1, mr.getFaultCount(hosts[0])); } }
true
true
public void testBlacklistAcrossJobs() throws IOException { MiniDFSCluster dfs = null; MiniMRCluster mr = null; FileSystem fileSys = null; Configuration conf = new Configuration(); // setup dfs and input dfs = new MiniDFSCluster(conf, 1, true, null, hosts); fileSys = dfs.getFileSystem(); if (!fileSys.mkdirs(inDir)) { throw new IOException("Mkdirs failed to create " + inDir.toString()); } TestRackAwareTaskPlacement.writeFile(dfs.getNameNode(), conf, new Path(inDir + "/file"), (short) 1); // start mr cluster JobConf jtConf = new JobConf(); jtConf.setInt("mapred.max.tracker.failures", 1); jtConf.setInt("mapred.max.tracker.blacklists", 1); mr = new MiniMRCluster(3, fileSys.getUri().toString(), 1, null, hosts, jtConf); // setup job configuration JobConf mrConf = mr.createJobConf(); JobConf job = new JobConf(mrConf); job.setNumMapTasks(30); job.setNumReduceTasks(0); job.setMapperClass(SleepJobFailOnHost.class); job.setMapOutputKeyClass(IntWritable.class); job.setMapOutputValueClass(NullWritable.class); job.setOutputFormat(NullOutputFormat.class); job.setInputFormat(SleepInputFormat.class); FileInputFormat.setInputPaths(job, inDir); FileOutputFormat.setOutputPath(job, outDir); // run the job JobClient jc = new JobClient(mrConf); RunningJob running = JobClient.runJob(job); assertEquals("Job failed", JobStatus.SUCCEEDED, running.getJobState()); assertEquals("Didn't blacklist the host", 1, jc.getClusterStatus().getBlacklistedTrackers()); assertEquals("Fault count should be 1", 1, mr.getFaultCount(hosts[0])); // run the same job once again // there should be no change in blacklist count running = JobClient.runJob(job); assertEquals("Job failed", JobStatus.SUCCEEDED, running.getJobState()); assertEquals("Didn't blacklist the host", 1, jc.getClusterStatus().getBlacklistedTrackers()); assertEquals("Fault count should be 1", 1, mr.getFaultCount(hosts[0])); }
public void testBlacklistAcrossJobs() throws IOException { MiniDFSCluster dfs = null; MiniMRCluster mr = null; FileSystem fileSys = null; Configuration conf = new Configuration(); // setup dfs and input dfs = new MiniDFSCluster(conf, 1, true, null, hosts); fileSys = dfs.getFileSystem(); if (!fileSys.mkdirs(inDir)) { throw new IOException("Mkdirs failed to create " + inDir.toString()); } UtilsForTests.writeFile(dfs.getNameNode(), conf, new Path(inDir + "/file"), (short) 1); // start mr cluster JobConf jtConf = new JobConf(); jtConf.setInt("mapred.max.tracker.failures", 1); jtConf.setInt("mapred.max.tracker.blacklists", 1); mr = new MiniMRCluster(3, fileSys.getUri().toString(), 1, null, hosts, jtConf); // setup job configuration JobConf mrConf = mr.createJobConf(); JobConf job = new JobConf(mrConf); job.setNumMapTasks(30); job.setNumReduceTasks(0); job.setMapperClass(SleepJobFailOnHost.class); job.setMapOutputKeyClass(IntWritable.class); job.setMapOutputValueClass(NullWritable.class); job.setOutputFormat(NullOutputFormat.class); job.setInputFormat(SleepInputFormat.class); FileInputFormat.setInputPaths(job, inDir); FileOutputFormat.setOutputPath(job, outDir); // run the job JobClient jc = new JobClient(mrConf); RunningJob running = JobClient.runJob(job); assertEquals("Job failed", JobStatus.SUCCEEDED, running.getJobState()); assertEquals("Didn't blacklist the host", 1, jc.getClusterStatus().getBlacklistedTrackers()); assertEquals("Fault count should be 1", 1, mr.getFaultCount(hosts[0])); // run the same job once again // there should be no change in blacklist count running = JobClient.runJob(job); assertEquals("Job failed", JobStatus.SUCCEEDED, running.getJobState()); assertEquals("Didn't blacklist the host", 1, jc.getClusterStatus().getBlacklistedTrackers()); assertEquals("Fault count should be 1", 1, mr.getFaultCount(hosts[0])); }
diff --git a/src/edu/vub/at/nfcpoker/ui/CardAnimation.java b/src/edu/vub/at/nfcpoker/ui/CardAnimation.java index d23a291..9cac929 100644 --- a/src/edu/vub/at/nfcpoker/ui/CardAnimation.java +++ b/src/edu/vub/at/nfcpoker/ui/CardAnimation.java @@ -1,65 +1,65 @@ package edu.vub.at.nfcpoker.ui; import edu.vub.at.nfcpoker.R; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.os.Build; import android.widget.ImageButton; public class CardAnimation { static boolean isHoneyComb = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB); private static ICardAnimation cardInstance = null; static public void setCardImage(ImageButton ib, int drawable) { getCardAnimation().setCardImage(ib, drawable); } private static ICardAnimation getCardAnimation() { if (cardInstance == null) { cardInstance = isHoneyComb ? new CardAnimationHC() : new CardAnimationGB(); } return cardInstance; } private interface ICardAnimation { public void setCardImage(ImageButton ib, int drawable); } public static class CardAnimationGB implements ICardAnimation { @Override public void setCardImage(ImageButton ib, int drawable) { ib.setImageResource(drawable); } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class CardAnimationHC implements ICardAnimation { @Override - public void setCardImage(final ImageButton ib, int drawable) { + public void setCardImage(final ImageButton ib, final int drawable) { ObjectAnimator animX = ObjectAnimator.ofFloat(ib, "scaleX", 1.f, 0.f); ObjectAnimator animY = ObjectAnimator.ofFloat(ib, "scaleY", 1.f, 0.f); animX.setDuration(500); animY.setDuration(500); final AnimatorSet scalers = new AnimatorSet(); scalers.play(animX).with(animY); scalers.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { ib.setScaleX(1.f); ib.setScaleY(1.f); - ib.setImageResource(R.drawable.backside); + ib.setImageResource(drawable); } }); - scalers.start(); + scalers.start(); } } }
false
true
public void setCardImage(final ImageButton ib, int drawable) { ObjectAnimator animX = ObjectAnimator.ofFloat(ib, "scaleX", 1.f, 0.f); ObjectAnimator animY = ObjectAnimator.ofFloat(ib, "scaleY", 1.f, 0.f); animX.setDuration(500); animY.setDuration(500); final AnimatorSet scalers = new AnimatorSet(); scalers.play(animX).with(animY); scalers.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { ib.setScaleX(1.f); ib.setScaleY(1.f); ib.setImageResource(R.drawable.backside); } }); scalers.start(); }
public void setCardImage(final ImageButton ib, final int drawable) { ObjectAnimator animX = ObjectAnimator.ofFloat(ib, "scaleX", 1.f, 0.f); ObjectAnimator animY = ObjectAnimator.ofFloat(ib, "scaleY", 1.f, 0.f); animX.setDuration(500); animY.setDuration(500); final AnimatorSet scalers = new AnimatorSet(); scalers.play(animX).with(animY); scalers.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { ib.setScaleX(1.f); ib.setScaleY(1.f); ib.setImageResource(drawable); } }); scalers.start(); }
diff --git a/src/edu/agh/tunev/model/kkm/Model.java b/src/edu/agh/tunev/model/kkm/Model.java index 1565881..9ecd924 100644 --- a/src/edu/agh/tunev/model/kkm/Model.java +++ b/src/edu/agh/tunev/model/kkm/Model.java @@ -1,75 +1,80 @@ package edu.agh.tunev.model.kkm; import java.util.Vector; import edu.agh.tunev.model.AbstractModel; import edu.agh.tunev.model.PersonProfile; import edu.agh.tunev.model.PersonState; import edu.agh.tunev.statistics.LifeStatistics; import edu.agh.tunev.statistics.Statistics.AddCallback; import edu.agh.tunev.world.World; import edu.agh.tunev.world.World.ProgressCallback; public final class Model extends AbstractModel { public final static String MODEL_NAME = "Autorski (\u00a9 2012 Jakub Rakoczy)"; public Model(World world) { super(world); } private static final double DT = 0.05; @Override public void simulate(double duration, Vector<PersonProfile> profiles, ProgressCallback progressCallback, AddCallback addCallback) { // number of iterations int num = (int) Math.round(Math.ceil(world.getDuration() / DT)); progressCallback.update(0, num, "Initializing..."); // init charts LifeStatistics lifeStatistics = new LifeStatistics(); addCallback.add(lifeStatistics); // init board Board board = new Board(world); // init people for (PersonProfile profile : profiles) board.addAgent(new Agent(board, profile)); // simulate double t = 0; for (int iteration = 1; iteration <= num; iteration++) { // update t += DT; board.update(t, DT); // chart inputs int currentNumDead = 0; int currentNumAlive = 0; int currentNumRescued = 0; // save states for (Agent p : board.getAgents()) { - interpolator.saveState(p.profile, t, new PersonState( - p.position, p.phi, p.getStance())); - if (p.isExited()) + PersonState.Movement stance = p.getStance(); + if (p.isExited()) { currentNumRescued++; - else if (!p.isAlive()) + stance = PersonState.Movement.HIDDEN; + } + else if (!p.isAlive()) { currentNumDead++; + stance = PersonState.Movement.DEAD; + } else currentNumAlive++; + interpolator.saveState(p.profile, t, new PersonState( + p.position, p.phi, stance)); } // update charts lifeStatistics.add(t, currentNumAlive, currentNumRescued, currentNumDead); // UI simulation progress bar progressCallback.update(iteration, num, (iteration < num ? "Simulating..." : "Done.")); } } }
false
true
public void simulate(double duration, Vector<PersonProfile> profiles, ProgressCallback progressCallback, AddCallback addCallback) { // number of iterations int num = (int) Math.round(Math.ceil(world.getDuration() / DT)); progressCallback.update(0, num, "Initializing..."); // init charts LifeStatistics lifeStatistics = new LifeStatistics(); addCallback.add(lifeStatistics); // init board Board board = new Board(world); // init people for (PersonProfile profile : profiles) board.addAgent(new Agent(board, profile)); // simulate double t = 0; for (int iteration = 1; iteration <= num; iteration++) { // update t += DT; board.update(t, DT); // chart inputs int currentNumDead = 0; int currentNumAlive = 0; int currentNumRescued = 0; // save states for (Agent p : board.getAgents()) { interpolator.saveState(p.profile, t, new PersonState( p.position, p.phi, p.getStance())); if (p.isExited()) currentNumRescued++; else if (!p.isAlive()) currentNumDead++; else currentNumAlive++; } // update charts lifeStatistics.add(t, currentNumAlive, currentNumRescued, currentNumDead); // UI simulation progress bar progressCallback.update(iteration, num, (iteration < num ? "Simulating..." : "Done.")); } }
public void simulate(double duration, Vector<PersonProfile> profiles, ProgressCallback progressCallback, AddCallback addCallback) { // number of iterations int num = (int) Math.round(Math.ceil(world.getDuration() / DT)); progressCallback.update(0, num, "Initializing..."); // init charts LifeStatistics lifeStatistics = new LifeStatistics(); addCallback.add(lifeStatistics); // init board Board board = new Board(world); // init people for (PersonProfile profile : profiles) board.addAgent(new Agent(board, profile)); // simulate double t = 0; for (int iteration = 1; iteration <= num; iteration++) { // update t += DT; board.update(t, DT); // chart inputs int currentNumDead = 0; int currentNumAlive = 0; int currentNumRescued = 0; // save states for (Agent p : board.getAgents()) { PersonState.Movement stance = p.getStance(); if (p.isExited()) { currentNumRescued++; stance = PersonState.Movement.HIDDEN; } else if (!p.isAlive()) { currentNumDead++; stance = PersonState.Movement.DEAD; } else currentNumAlive++; interpolator.saveState(p.profile, t, new PersonState( p.position, p.phi, stance)); } // update charts lifeStatistics.add(t, currentNumAlive, currentNumRescued, currentNumDead); // UI simulation progress bar progressCallback.update(iteration, num, (iteration < num ? "Simulating..." : "Done.")); } }
diff --git a/src/com/oux/SmartGPSLogger/SmartGPSLogger.java b/src/com/oux/SmartGPSLogger/SmartGPSLogger.java index ed55153..0c972e6 100644 --- a/src/com/oux/SmartGPSLogger/SmartGPSLogger.java +++ b/src/com/oux/SmartGPSLogger/SmartGPSLogger.java @@ -1,182 +1,184 @@ /* * Copyright (C) 2012 Michel Sébastien & Jérémy Compostella * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.oux.SmartGPSLogger; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.content.Context; import android.content.Intent; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import android.app.SearchManager; import android.content.ServiceConnection; import java.util.LinkedList; import android.content.ComponentName; import android.os.IBinder; import android.location.Location; import com.google.android.maps.MyLocationOverlay; import android.graphics.Color; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import android.text.format.DateFormat; public class SmartGPSLogger extends MapActivity implements LocationUpdate { private static final String TAG = "SmartGPSLogger"; // Identifiers for option menu items private static final int MENU_RECLOG = Menu.FIRST; private static final int MENU_STOPLOG = MENU_RECLOG + 1; private static final int MENU_FORCE = MENU_STOPLOG + 1; private static final int MENU_SETTINGS = MENU_FORCE + 1; private Intent mService; private MyLocationOverlay me; private MapView map; private TextView text; private GPSService.MyBinder binder; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Settings.getInstance(this); setContentView(R.layout.main); map = (MapView)findViewById(R.id.map); me = new MyLocationOverlay(this, map); map.getOverlays().add(me); map.setBuiltInZoomControls(true); text = (TextView)findViewById(R.id.text_area); mService = new Intent(this, GPSService.class); bindService(mService, connection, Context.BIND_AUTO_CREATE); } @Override protected boolean isRouteDisplayed() { return false; } @Override protected void onDestroy() { super.onDestroy(); unbindService(connection); } @Override protected void onPause() { super.onPause(); me.disableCompass(); } @Override protected void onResume() { super.onResume(); me.enableCompass(); } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); - if (!binder.isRunning()) - menu.add(0, MENU_RECLOG, 0, R.string.menu_reclog) - .setIcon(R.drawable.ic_reclog) - .setAlphabeticShortcut(SearchManager.MENU_KEY); - else { - menu.add(0, MENU_STOPLOG, 0, R.string.menu_stoplog) - .setIcon(R.drawable.ic_stoplog) - .setAlphabeticShortcut(SearchManager.MENU_KEY); - menu.add(0, MENU_FORCE, 0, R.string.menu_force) - .setIcon(R.drawable.ic_reclog) - .setAlphabeticShortcut(SearchManager.MENU_KEY); + if (binder != null) { + if (!binder.isRunning()) + menu.add(0, MENU_RECLOG, 0, R.string.menu_reclog) + .setIcon(R.drawable.ic_reclog) + .setAlphabeticShortcut(SearchManager.MENU_KEY); + else { + menu.add(0, MENU_STOPLOG, 0, R.string.menu_stoplog) + .setIcon(R.drawable.ic_stoplog) + .setAlphabeticShortcut(SearchManager.MENU_KEY); + menu.add(0, MENU_FORCE, 0, R.string.menu_force) + .setIcon(R.drawable.ic_reclog) + .setAlphabeticShortcut(SearchManager.MENU_KEY); + } } menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings) .setIcon(android.R.drawable.ic_menu_preferences) .setIntent(new Intent(this,Preferences.class)) .setAlphabeticShortcut(SearchManager.MENU_KEY); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_RECLOG: case MENU_FORCE: this.startService(mService); return true; case MENU_STOPLOG: this.binder.stopUpdates(); Log.d(TAG, "stopped"); return true; } return super.onOptionsItemSelected(item); } public void newLocation(Location loc) { updateText(System.currentTimeMillis()); } private void updateText(long lastGPSFixTime) { if (lastGPSFixTime == 0) text.setText("Last GPS fix information is not available"); else text.setText("Last GPS fix at + " + DateFormat.format("yyyy:MM:dd kk:mm:ss", lastGPSFixTime)); if (lastGPSFixTime >= System.currentTimeMillis() - Settings.getInstance().maxPeriod() * 60 * 1000) text.setTextColor(Color.GREEN); else text.setTextColor(Color.RED); } private ServiceConnection connection = new ServiceConnection() { private PathOverlay path; public void onServiceConnected(ComponentName className, IBinder binder) { SmartGPSLogger.this.binder = (GPSService.MyBinder)binder; LinkedList<Location> locations = SmartGPSLogger.this.binder.getLocations(); path = new PathOverlay(locations); map.getOverlays().add(path); SmartGPSLogger.this.updateText(SmartGPSLogger.this.binder.getLastGPSFixTime()); SmartGPSLogger.this.binder.registerLocationUpdate(SmartGPSLogger.this); SmartGPSLogger.this.binder.registerLocationUpdate(path); } public void onServiceDisconnected(ComponentName className) { map.getOverlays().remove(path); SmartGPSLogger.this.binder.unregisterLocationUpdate(SmartGPSLogger.this); SmartGPSLogger.this.binder.unregisterLocationUpdate(path); } }; } // vi:et
true
true
public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); if (!binder.isRunning()) menu.add(0, MENU_RECLOG, 0, R.string.menu_reclog) .setIcon(R.drawable.ic_reclog) .setAlphabeticShortcut(SearchManager.MENU_KEY); else { menu.add(0, MENU_STOPLOG, 0, R.string.menu_stoplog) .setIcon(R.drawable.ic_stoplog) .setAlphabeticShortcut(SearchManager.MENU_KEY); menu.add(0, MENU_FORCE, 0, R.string.menu_force) .setIcon(R.drawable.ic_reclog) .setAlphabeticShortcut(SearchManager.MENU_KEY); } menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings) .setIcon(android.R.drawable.ic_menu_preferences) .setIntent(new Intent(this,Preferences.class)) .setAlphabeticShortcut(SearchManager.MENU_KEY); return true; }
public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); if (binder != null) { if (!binder.isRunning()) menu.add(0, MENU_RECLOG, 0, R.string.menu_reclog) .setIcon(R.drawable.ic_reclog) .setAlphabeticShortcut(SearchManager.MENU_KEY); else { menu.add(0, MENU_STOPLOG, 0, R.string.menu_stoplog) .setIcon(R.drawable.ic_stoplog) .setAlphabeticShortcut(SearchManager.MENU_KEY); menu.add(0, MENU_FORCE, 0, R.string.menu_force) .setIcon(R.drawable.ic_reclog) .setAlphabeticShortcut(SearchManager.MENU_KEY); } } menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings) .setIcon(android.R.drawable.ic_menu_preferences) .setIntent(new Intent(this,Preferences.class)) .setAlphabeticShortcut(SearchManager.MENU_KEY); return true; }
diff --git a/src/biz/bokhorst/xprivacy/PrivacyService.java b/src/biz/bokhorst/xprivacy/PrivacyService.java index 473ed8bd..0356018c 100644 --- a/src/biz/bokhorst/xprivacy/PrivacyService.java +++ b/src/biz/bokhorst/xprivacy/PrivacyService.java @@ -1,2175 +1,2174 @@ package biz.bokhorst.xprivacy; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantReadWriteLock; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteStatement; import android.os.Binder; import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.PowerManager; import android.os.Process; import android.os.RemoteException; import android.os.StrictMode; import android.os.StrictMode.ThreadPolicy; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; public class PrivacyService { private static int mXUid = -1; private static boolean mRegistered = false; private static boolean mUseCache = false; private static String mSecret = null; private static Thread mWorker = null; private static Handler mHandler = null; private static Semaphore mOndemandSemaphore = new Semaphore(1, true); private static List<String> mListError = new ArrayList<String>(); private static IPrivacyService mClient = null; private static final String cTableRestriction = "restriction"; private static final String cTableUsage = "usage"; private static final String cTableSetting = "setting"; private static final int cCurrentVersion = 296; private static final String cServiceName = "xprivacy296"; // TODO: define column names // sqlite3 /data/system/xprivacy/xprivacy.db public static void register(List<String> listError, String secret) { // Store secret and errors mSecret = secret; mListError.addAll(listError); try { // Register privacy service // @formatter:off // public static void addService(String name, IBinder service) // public static void addService(String name, IBinder service, boolean allowIsolated) // @formatter:on Class<?> cServiceManager = Class.forName("android.os.ServiceManager"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { Method mAddService = cServiceManager.getDeclaredMethod("addService", String.class, IBinder.class, boolean.class); mAddService.invoke(null, cServiceName, mPrivacyService, true); } else { Method mAddService = cServiceManager.getDeclaredMethod("addService", String.class, IBinder.class); mAddService.invoke(null, cServiceName, mPrivacyService); } // This will and should open the database mRegistered = true; Util.log(null, Log.WARN, "Service registered name=" + cServiceName); // Publish semaphore to activity manager service XActivityManagerService.setSemaphore(mOndemandSemaphore); // Get memory class to enable/disable caching // http://stackoverflow.com/questions/2630158/detect-application-heap-size-in-android int memoryClass = (int) (Runtime.getRuntime().maxMemory() / 1024L / 1024L); mUseCache = (memoryClass >= 32); Util.log(null, Log.WARN, "Memory class=" + memoryClass + " cache=" + mUseCache); // Start a worker thread mWorker = new Thread(new Runnable() { @Override public void run() { try { Looper.prepare(); mHandler = new Handler(); Looper.loop(); } catch (Throwable ex) { Util.bug(null, ex); } } }); mWorker.start(); } catch (Throwable ex) { Util.bug(null, ex); } } public static boolean isRegistered() { return mRegistered; } public static boolean checkClient() { // Runs client side try { IPrivacyService client = getClient(); if (client != null) return (client.getVersion() == cCurrentVersion); } catch (RemoteException ex) { Util.bug(null, ex); } return false; } public static IPrivacyService getClient() { // Runs client side if (mClient == null) try { // public static IBinder getService(String name) Class<?> cServiceManager = Class.forName("android.os.ServiceManager"); Method mGetService = cServiceManager.getDeclaredMethod("getService", String.class); mClient = IPrivacyService.Stub.asInterface((IBinder) mGetService.invoke(null, cServiceName)); } catch (Throwable ex) { Util.bug(null, ex); } // Disable disk/network strict mode // TODO: hook setThreadPolicy try { ThreadPolicy oldPolicy = StrictMode.getThreadPolicy(); ThreadPolicy newpolicy = new ThreadPolicy.Builder(oldPolicy).permitDiskReads().permitDiskWrites() .permitNetwork().build(); StrictMode.setThreadPolicy(newpolicy); } catch (Throwable ex) { Util.bug(null, ex); } return mClient; } public static void reportErrorInternal(String message) { synchronized (mListError) { mListError.add(message); } } public static PRestriction getRestriction(final PRestriction restriction, boolean usage, String secret) throws RemoteException { if (isRegistered()) return mPrivacyService.getRestriction(restriction, usage, secret); else { IPrivacyService client = getClient(); if (client == null) { Log.w("XPrivacy", "No client for " + restriction); Log.w("XPrivacy", Log.getStackTraceString(new Exception("StackTrace"))); PRestriction result = new PRestriction(restriction); result.restricted = false; return result; } else return client.getRestriction(restriction, usage, secret); } } public static PSetting getSetting(PSetting setting) throws RemoteException { if (isRegistered()) return mPrivacyService.getSetting(setting); else { IPrivacyService client = getClient(); if (client == null) { Log.w("XPrivacy", "No client for " + setting + " uid=" + Process.myUid() + " pid=" + Process.myPid()); Log.w("XPrivacy", Log.getStackTraceString(new Exception("StackTrace"))); return setting; } else return client.getSetting(setting); } } private static final IPrivacyService.Stub mPrivacyService = new IPrivacyService.Stub() { private SQLiteDatabase mDb = null; private SQLiteDatabase mDbUsage = null; private SQLiteStatement stmtGetRestriction = null; private SQLiteStatement stmtGetSetting = null; private SQLiteStatement stmtGetUsageRestriction = null; private SQLiteStatement stmtGetUsageMethod = null; private ReentrantReadWriteLock mLock = new ReentrantReadWriteLock(true); private ReentrantReadWriteLock mLockUsage = new ReentrantReadWriteLock(true); private boolean mSelectCategory = true; private boolean mSelectOnce = false; private Map<CSetting, CSetting> mSettingCache = new HashMap<CSetting, CSetting>(); private Map<CRestriction, CRestriction> mAskedOnceCache = new HashMap<CRestriction, CRestriction>(); private Map<CRestriction, CRestriction> mRestrictionCache = new HashMap<CRestriction, CRestriction>(); private final int cMaxUsageData = 500; // entries private final int cMaxOnDemandDialog = 20; // seconds private ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new PriorityThreadFactory()); final class PriorityThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); return t; } } // Management @Override public int getVersion() throws RemoteException { return cCurrentVersion; } @Override public List<String> check() throws RemoteException { enforcePermission(); List<String> listError = new ArrayList<String>(); synchronized (mListError) { int c = 0; int i = 0; while (i < mListError.size()) { String msg = mListError.get(i); c += msg.length(); if (c < 5000) listError.add(msg); else break; i++; } } File dbFile = getDbFile(); if (!dbFile.exists()) listError.add("Database does not exists"); if (!dbFile.canRead()) listError.add("Database not readable"); if (!dbFile.canWrite()) listError.add("Database not writable"); SQLiteDatabase db = getDb(); if (db == null) listError.add("Database not available"); else if (!db.isOpen()) listError.add("Database not open"); return listError; } @Override public void reportError(String message) throws RemoteException { reportErrorInternal(message); } // Restrictions @Override public void setRestriction(PRestriction restriction) throws RemoteException { try { enforcePermission(); setRestrictionInternal(restriction); } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } private void setRestrictionInternal(PRestriction restriction) throws RemoteException { // Validate if (restriction.restrictionName == null) { Util.log(null, Log.ERROR, "Set invalid restriction " + restriction); Util.logStack(null, Log.ERROR); throw new RemoteException("Invalid restriction"); } try { SQLiteDatabase db = getDb(); if (db == null) return; // 0 not restricted, ask // 1 restricted, ask // 2 not restricted, asked // 3 restricted, asked mLock.writeLock().lock(); db.beginTransaction(); try { // Create category record if (restriction.methodName == null) { ContentValues cvalues = new ContentValues(); cvalues.put("uid", restriction.uid); cvalues.put("restriction", restriction.restrictionName); cvalues.put("method", ""); cvalues.put("restricted", (restriction.restricted ? 1 : 0) + (restriction.asked ? 2 : 0)); db.insertWithOnConflict(cTableRestriction, null, cvalues, SQLiteDatabase.CONFLICT_REPLACE); } // Create method exception record if (restriction.methodName != null) { ContentValues mvalues = new ContentValues(); mvalues.put("uid", restriction.uid); mvalues.put("restriction", restriction.restrictionName); mvalues.put("method", restriction.methodName); mvalues.put("restricted", (restriction.restricted ? 0 : 1) + (restriction.asked ? 2 : 0)); db.insertWithOnConflict(cTableRestriction, null, mvalues, SQLiteDatabase.CONFLICT_REPLACE); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Update cache if (mUseCache) synchronized (mRestrictionCache) { if (restriction.methodName == null || restriction.extra == null) for (CRestriction key : new ArrayList<CRestriction>(mRestrictionCache.keySet())) if (key.isSameMethod(restriction)) mRestrictionCache.remove(key); CRestriction key = new CRestriction(restriction, restriction.extra); if (mRestrictionCache.containsKey(key)) mRestrictionCache.remove(key); mRestrictionCache.put(key, key); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void setRestrictionList(List<PRestriction> listRestriction) throws RemoteException { enforcePermission(); for (PRestriction restriction : listRestriction) setRestrictionInternal(restriction); } @Override public PRestriction getRestriction(final PRestriction restriction, boolean usage, String secret) throws RemoteException { long start = System.currentTimeMillis(); boolean cached = false; final PRestriction mresult = new PRestriction(restriction); try { // No permissions enforced, but usage data requires a secret // Sanity checks if (restriction.restrictionName == null) { Util.log(null, Log.ERROR, "Get invalid restriction " + restriction); return mresult; } if (usage && restriction.methodName == null) { Util.log(null, Log.ERROR, "Get invalid restriction " + restriction); return mresult; } // Check for self if (Util.getAppId(restriction.uid) == getXUid()) { if (PrivacyManager.cIdentification.equals(restriction.restrictionName) && "getString".equals(restriction.methodName)) { mresult.asked = true; return mresult; } if (PrivacyManager.cIPC.equals(restriction.restrictionName)) { mresult.asked = true; return mresult; } else if (PrivacyManager.cStorage.equals(restriction.restrictionName)) { mresult.asked = true; return mresult; } else if (PrivacyManager.cSystem.equals(restriction.restrictionName)) { mresult.asked = true; return mresult; } else if (PrivacyManager.cView.equals(restriction.restrictionName)) { mresult.asked = true; return mresult; } } // Get meta data Hook hook = null; if (restriction.methodName != null) { hook = PrivacyManager.getHook(restriction.restrictionName, restriction.methodName); if (hook == null) // Can happen after replacing apk Util.log(null, Log.WARN, "Hook not found in service: " + restriction); } // Check for system component if (usage && !PrivacyManager.isApplication(restriction.uid)) if (!getSettingBool(0, PrivacyManager.cSettingSystem, false)) return mresult; // Check if restrictions enabled if (usage && !getSettingBool(restriction.uid, PrivacyManager.cSettingRestricted, true)) return mresult; // Check cache if (mUseCache) { CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) { cached = true; CRestriction cache = mRestrictionCache.get(key); mresult.restricted = cache.restricted; mresult.asked = cache.asked; } } } if (!cached) { PRestriction cresult = new PRestriction(restriction.uid, restriction.restrictionName, null); boolean methodFound = false; // No permissions required SQLiteDatabase db = getDb(); if (db == null) return mresult; // Precompile statement when needed if (stmtGetRestriction == null) { String sql = "SELECT restricted FROM " + cTableRestriction + " WHERE uid=? AND restriction=? AND method=?"; stmtGetRestriction = db.compileStatement(sql); } // Execute statement mLock.readLock().lock(); db.beginTransaction(); try { try { synchronized (stmtGetRestriction) { stmtGetRestriction.clearBindings(); stmtGetRestriction.bindLong(1, restriction.uid); stmtGetRestriction.bindString(2, restriction.restrictionName); stmtGetRestriction.bindString(3, ""); long state = stmtGetRestriction.simpleQueryForLong(); cresult.restricted = ((state & 1) != 0); cresult.asked = ((state & 2) != 0); mresult.restricted = cresult.restricted; mresult.asked = cresult.asked; } } catch (SQLiteDoneException ignored) { } if (restriction.methodName != null) try { synchronized (stmtGetRestriction) { stmtGetRestriction.clearBindings(); stmtGetRestriction.bindLong(1, restriction.uid); stmtGetRestriction.bindString(2, restriction.restrictionName); stmtGetRestriction.bindString(3, restriction.methodName); long state = stmtGetRestriction.simpleQueryForLong(); // Method can be excepted if (mresult.restricted) mresult.restricted = ((state & 1) == 0); // Category asked=true takes precedence if (!mresult.asked) mresult.asked = ((state & 2) != 0); methodFound = true; } } catch (SQLiteDoneException ignored) { } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } // Default dangerous if (!methodFound && hook != null && hook.isDangerous()) if (!getSettingBool(0, PrivacyManager.cSettingDangerous, false)) { mresult.restricted = false; mresult.asked = true; } // Check whitelist if (usage && hook != null && hook.whitelist() != null && restriction.extra != null) { String value = getSetting(new PSetting(restriction.uid, hook.whitelist(), restriction.extra, null)).value; if (value == null) { String xextra = getXExtra(restriction, hook); if (xextra != null) value = getSetting(new PSetting(restriction.uid, hook.whitelist(), xextra, null)).value; } if (value != null) { // true means allow, false means block mresult.restricted = !Boolean.parseBoolean(value); mresult.asked = true; } } // Fallback if (!mresult.restricted && usage && PrivacyManager.isApplication(restriction.uid) && !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) { if (hook != null && !hook.isDangerous()) { mresult.restricted = PrivacyProvider.getRestrictedFallback(null, restriction.uid, restriction.restrictionName, restriction.methodName); Util.log(null, Log.WARN, "Fallback " + mresult); } } // Update cache if (mUseCache) { CRestriction key = new CRestriction(mresult, restriction.extra); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) mRestrictionCache.remove(key); mRestrictionCache.put(key, key); } } } // Ask to restrict boolean ondemand = false; if (!mresult.asked && usage && PrivacyManager.isApplication(restriction.uid)) ondemand = onDemandDialog(hook, restriction, mresult); // Notify user if (!ondemand && mresult.restricted && usage && hook != null && hook.shouldNotify()) notifyRestricted(restriction); // Store usage data if (usage && hook != null && hook.hasUsageData()) storeUsageData(restriction, secret, mresult); } catch (Throwable ex) { Util.bug(null, ex); } long ms = System.currentTimeMillis() - start; Util.log(null, Log.INFO, String.format("get service %s%s %d ms", restriction, (cached ? " (cached)" : ""), ms)); return mresult; } private void storeUsageData(final PRestriction restriction, String secret, final PRestriction mresult) throws RemoteException { // Check if enabled if (getSettingBool(0, PrivacyManager.cSettingUsage, true)) { // Check secret boolean allowed = true; if (Util.getAppId(Binder.getCallingUid()) != getXUid()) { if (mSecret == null || !mSecret.equals(secret)) { allowed = false; Util.log(null, Log.WARN, "Invalid secret"); } } if (allowed) { mExecutor.execute(new Runnable() { public void run() { try { if (XActivityManagerService.canWriteUsageData()) { SQLiteDatabase dbUsage = getDbUsage(); if (dbUsage == null) return; mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { String extra = ""; if (restriction.extra != null) if (getSettingBool(0, PrivacyManager.cSettingParameters, false)) extra = restriction.extra; ContentValues values = new ContentValues(); values.put("uid", restriction.uid); values.put("restriction", restriction.restrictionName); values.put("method", restriction.methodName); values.put("restricted", mresult.restricted); values.put("time", new Date().getTime()); values.put("extra", extra); dbUsage.insertWithOnConflict(cTableUsage, null, values, SQLiteDatabase.CONFLICT_REPLACE); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } } catch (Throwable ex) { Util.bug(null, ex); } } }); } } } @Override public List<PRestriction> getRestrictionList(PRestriction selector) throws RemoteException { List<PRestriction> result = new ArrayList<PRestriction>(); try { enforcePermission(); PRestriction query; if (selector.restrictionName == null) for (String sRestrictionName : PrivacyManager.getRestrictions()) { PRestriction restriction = new PRestriction(selector.uid, sRestrictionName, null, false); query = getRestriction(restriction, false, null); restriction.restricted = query.restricted; restriction.asked = query.asked; result.add(restriction); } else for (Hook md : PrivacyManager.getHooks(selector.restrictionName)) { PRestriction restriction = new PRestriction(selector.uid, selector.restrictionName, md.getName(), false); query = getRestriction(restriction, false, null); restriction.restricted = query.restricted; restriction.asked = query.asked; result.add(restriction); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return result; } @Override public void deleteRestrictions(int uid, String restrictionName) throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { if ("".equals(restrictionName)) db.delete(cTableRestriction, "uid=?", new String[] { Integer.toString(uid) }); else db.delete(cTableRestriction, "uid=? AND restriction=?", new String[] { Integer.toString(uid), restrictionName }); Util.log(null, Log.WARN, "Restrictions deleted uid=" + uid + " category=" + restrictionName); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear caches if (mUseCache) synchronized (mRestrictionCache) { mRestrictionCache.clear(); } synchronized (mAskedOnceCache) { mAskedOnceCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } // Usage @Override public long getUsage(List<PRestriction> listRestriction) throws RemoteException { long lastUsage = 0; try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); // Precompile statement when needed if (stmtGetUsageRestriction == null) { String sql = "SELECT MAX(time) FROM " + cTableUsage + " WHERE uid=? AND restriction=?"; stmtGetUsageRestriction = dbUsage.compileStatement(sql); } if (stmtGetUsageMethod == null) { String sql = "SELECT MAX(time) FROM " + cTableUsage + " WHERE uid=? AND restriction=? AND method=?"; stmtGetUsageMethod = dbUsage.compileStatement(sql); } mLockUsage.readLock().lock(); dbUsage.beginTransaction(); try { for (PRestriction restriction : listRestriction) { if (restriction.methodName == null) try { synchronized (stmtGetUsageRestriction) { stmtGetUsageRestriction.clearBindings(); stmtGetUsageRestriction.bindLong(1, restriction.uid); stmtGetUsageRestriction.bindString(2, restriction.restrictionName); lastUsage = Math.max(lastUsage, stmtGetUsageRestriction.simpleQueryForLong()); } } catch (SQLiteDoneException ignored) { } else try { synchronized (stmtGetUsageMethod) { stmtGetUsageMethod.clearBindings(); stmtGetUsageMethod.bindLong(1, restriction.uid); stmtGetUsageMethod.bindString(2, restriction.restrictionName); stmtGetUsageMethod.bindString(3, restriction.methodName); lastUsage = Math.max(lastUsage, stmtGetUsageMethod.simpleQueryForLong()); } } catch (SQLiteDoneException ignored) { } } dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return lastUsage; } @Override public List<PRestriction> getUsageList(int uid, String restrictionName) throws RemoteException { List<PRestriction> result = new ArrayList<PRestriction>(); try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); mLockUsage.readLock().lock(); dbUsage.beginTransaction(); try { Cursor cursor; if (uid == 0) { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, null, new String[] {}, null, null, "time DESC LIMIT " + cMaxUsageData); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "restriction=?", new String[] { restrictionName }, null, null, "time DESC LIMIT " + cMaxUsageData); } else { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, "time DESC LIMIT " + cMaxUsageData); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "uid=? AND restriction=?", new String[] { Integer.toString(uid), restrictionName }, null, null, "time DESC LIMIT " + cMaxUsageData); } if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (usage data)"); else try { while (cursor.moveToNext()) { PRestriction data = new PRestriction(); data.uid = cursor.getInt(0); data.restrictionName = cursor.getString(1); data.methodName = cursor.getString(2); data.restricted = (cursor.getInt(3) > 0); data.time = cursor.getLong(4); data.extra = cursor.getString(5); result.add(data); } } finally { cursor.close(); } dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return result; } @Override public void deleteUsage(int uid) throws RemoteException { try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { if (uid == 0) dbUsage.delete(cTableUsage, null, new String[] {}); else dbUsage.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Usage data deleted uid=" + uid); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } // Settings @Override public void setSetting(PSetting setting) throws RemoteException { try { enforcePermission(); setSettingInternal(setting); } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } private void setSettingInternal(PSetting setting) throws RemoteException { try { SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Update cache if (mUseCache) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); key.setValue(setting.value); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); if (setting.value != null) mSettingCache.put(key, key); } } // Clear restrictions for white list if (Meta.isWhitelist(setting.type)) for (String restrictionName : PrivacyManager.getRestrictions()) for (Hook hook : PrivacyManager.getHooks(restrictionName)) if (setting.type.equals(hook.whitelist())) { PRestriction restriction = new PRestriction(setting.uid, hook.getRestrictionName(), hook.getName()); Util.log(null, Log.WARN, "Clearing cache for " + restriction); synchronized (mRestrictionCache) { for (CRestriction key : new ArrayList<CRestriction>(mRestrictionCache.keySet())) if (key.isSameMethod(restriction)) { Util.log(null, Log.WARN, "Removing " + key); mRestrictionCache.remove(key); } } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void setSettingList(List<PSetting> listSetting) throws RemoteException { enforcePermission(); for (PSetting setting : listSetting) setSettingInternal(setting); } @Override @SuppressLint("DefaultLocale") public PSetting getSetting(PSetting setting) throws RemoteException { PSetting result = new PSetting(setting.uid, setting.type, setting.name, setting.value); try { // No permissions enforced // Check cache if (mUseCache && setting.value != null) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) { result.value = mSettingCache.get(key).getValue(); return result; } } } // No persmissions required SQLiteDatabase db = getDb(); if (db == null) return result; // Fallback if (!PrivacyManager.cSettingMigrated.equals(setting.name) && !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) { if (setting.uid == 0) result.value = PrivacyProvider.getSettingFallback(setting.name, null, false); if (result.value == null) { result.value = PrivacyProvider.getSettingFallback( String.format("%s.%d", setting.name, setting.uid), setting.value, false); return result; } } // Precompile statement when needed if (stmtGetSetting == null) { String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND type=? AND name=?"; stmtGetSetting = db.compileStatement(sql); } // Execute statement mLock.readLock().lock(); db.beginTransaction(); try { try { synchronized (stmtGetSetting) { stmtGetSetting.clearBindings(); stmtGetSetting.bindLong(1, setting.uid); stmtGetSetting.bindString(2, setting.type); stmtGetSetting.bindString(3, setting.name); String value = stmtGetSetting.simpleQueryForString(); if (value != null) result.value = value; } } catch (SQLiteDoneException ignored) { } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } // Add to cache if (mUseCache && result.value != null) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); key.setValue(result.value); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); mSettingCache.put(key, key); } } } catch (Throwable ex) { Util.bug(null, ex); } return result; } @Override public List<PSetting> getSettingList(int uid) throws RemoteException { List<PSetting> listSetting = new ArrayList<PSetting>(); try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return listSetting; mLock.readLock().lock(); db.beginTransaction(); try { Cursor cursor = db.query(cTableSetting, new String[] { "type", "name", "value" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, null); if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (settings)"); else try { while (cursor.moveToNext()) listSetting.add(new PSetting(uid, cursor.getString(0), cursor.getString(1), cursor .getString(2))); } finally { cursor.close(); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return listSetting; } @Override public void deleteSettings(int uid) throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Settings deleted uid=" + uid); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear cache if (mUseCache) synchronized (mSettingCache) { mSettingCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void clear() throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); SQLiteDatabase dbUsage = getDbUsage(); if (db == null || dbUsage == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM " + cTableRestriction); db.execSQL("DELETE FROM " + cTableSetting); Util.log(null, Log.WARN, "Database cleared"); // Reset migrated ContentValues values = new ContentValues(); values.put("uid", 0); values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear caches if (mUseCache) { synchronized (mRestrictionCache) { mRestrictionCache.clear(); } synchronized (mSettingCache) { mSettingCache.clear(); } } synchronized (mAskedOnceCache) { mAskedOnceCache.clear(); } Util.log(null, Log.WARN, "Caches cleared"); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { dbUsage.execSQL("DELETE FROM " + cTableUsage); Util.log(null, Log.WARN, "Usage database cleared"); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void reboot() throws RemoteException { try { enforcePermission(); Binder.clearCallingIdentity(); ((PowerManager) getContext().getSystemService(Context.POWER_SERVICE)).reboot(null); } catch (Throwable ex) { Util.bug(null, ex); } } @Override public void dump(int uid) throws RemoteException { if (uid == 0) { } else { synchronized (mRestrictionCache) { for (CRestriction crestriction : mRestrictionCache.keySet()) if (crestriction.getUid() == uid) Util.log(null, Log.WARN, "Dump crestriction=" + crestriction); } synchronized (mAskedOnceCache) { for (CRestriction crestriction : mAskedOnceCache.keySet()) if (crestriction.getUid() == uid && !crestriction.isExpired()) Util.log(null, Log.WARN, "Dump asked=" + crestriction); } synchronized (mSettingCache) { for (CSetting csetting : mSettingCache.keySet()) if (csetting.getUid() == uid) Util.log(null, Log.WARN, "Dump csetting=" + csetting); } } } // Helper methods private boolean onDemandDialog(final Hook hook, final PRestriction restriction, final PRestriction result) { try { // Without handler nothing can be done if (mHandler == null) return false; // Check for exceptions if (hook != null && !hook.canOnDemand()) return false; // Check if enabled if (!getSettingBool(0, PrivacyManager.cSettingOnDemand, true)) return false; if (!getSettingBool(restriction.uid, PrivacyManager.cSettingOnDemand, false)) return false; // Skip dangerous methods final boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false); if (!dangerous && hook != null && hook.isDangerous()) return false; // Get am context final Context context = getContext(); if (context == null) return false; long token = 0; try { token = Binder.clearCallingIdentity(); // Get application info final ApplicationInfoEx appInfo = new ApplicationInfoEx(context, restriction.uid); // Check if system application if (!dangerous && appInfo.isSystem()) return false; // Check if activity manager agrees if (!XActivityManagerService.canOnDemand()) return false; // Go ask Util.log(null, Log.WARN, "On demand " + restriction); mOndemandSemaphore.acquireUninterruptibly(); try { // Check if activity manager still agrees if (!XActivityManagerService.canOnDemand()) return false; Util.log(null, Log.WARN, "On demanding " + restriction); // Check if not asked before CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) if (mRestrictionCache.get(key).asked) { Util.log(null, Log.WARN, "Already asked " + restriction); return false; } } synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(key) && !mAskedOnceCache.get(key).isExpired()) { Util.log(null, Log.WARN, "Already asked once " + restriction); return false; } } if (restriction.extra != null && hook != null && hook.whitelist() != null) { CSetting skey = new CSetting(restriction.uid, hook.whitelist(), restriction.extra); CSetting xkey = null; String xextra = getXExtra(restriction, hook); if (xextra != null) xkey = new CSetting(restriction.uid, hook.whitelist(), xextra); synchronized (mSettingCache) { if (mSettingCache.containsKey(skey) || (xkey != null && mSettingCache.containsKey(xkey))) { Util.log(null, Log.WARN, "Already asked " + skey); return false; } } } final AlertDialogHolder holder = new AlertDialogHolder(); final CountDownLatch latch = new CountDownLatch(1); // Run dialog in looper mHandler.post(new Runnable() { @Override public void run() { try { // Dialog AlertDialog.Builder builder = getOnDemandDialogBuilder(restriction, hook, appInfo, dangerous, result, context, latch); AlertDialog alertDialog = builder.create(); alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE); alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); - alertDialog.getWindow().setSoftInputMode( - WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); + alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); alertDialog.setCancelable(false); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); holder.dialog = alertDialog; // Progress bar final ProgressBar mProgress = (ProgressBar) alertDialog .findViewById(R.id.pbProgress); mProgress.setMax(cMaxOnDemandDialog * 20); mProgress.setProgress(cMaxOnDemandDialog * 20); Runnable rProgress = new Runnable() { @Override public void run() { AlertDialog dialog = holder.dialog; if (dialog != null && dialog.isShowing() && mProgress.getProgress() > 0) { mProgress.incrementProgressBy(-1); mHandler.postDelayed(this, 50); } } }; mHandler.postDelayed(rProgress, 50); } catch (Throwable ex) { Util.bug(null, ex); latch.countDown(); } } }); // Wait for dialog to complete if (!latch.await(cMaxOnDemandDialog, TimeUnit.SECONDS)) { Util.log(null, Log.WARN, "On demand dialog timeout " + restriction); mHandler.post(new Runnable() { @Override public void run() { AlertDialog dialog = holder.dialog; if (dialog != null) dialog.cancel(); } }); } } finally { mOndemandSemaphore.release(); } } finally { Binder.restoreCallingIdentity(token); } } catch (Throwable ex) { Util.bug(null, ex); } return true; } final class AlertDialogHolder { public AlertDialog dialog = null; } private AlertDialog.Builder getOnDemandDialogBuilder(final PRestriction restriction, final Hook hook, ApplicationInfoEx appInfo, boolean dangerous, final PRestriction result, Context context, final CountDownLatch latch) throws NameNotFoundException { // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Reference views View view = LayoutInflater.from(context.createPackageContext(self, 0)).inflate(R.layout.ondemand, null); ImageView ivAppIcon = (ImageView) view.findViewById(R.id.ivAppIcon); TextView tvAppName = (TextView) view.findViewById(R.id.tvAppName); TextView tvAttempt = (TextView) view.findViewById(R.id.tvAttempt); TextView tvCategory = (TextView) view.findViewById(R.id.tvCategory); TextView tvFunction = (TextView) view.findViewById(R.id.tvFunction); TextView tvParameters = (TextView) view.findViewById(R.id.tvParameters); TableRow rowParameters = (TableRow) view.findViewById(R.id.rowParameters); final CheckBox cbCategory = (CheckBox) view.findViewById(R.id.cbCategory); final CheckBox cbOnce = (CheckBox) view.findViewById(R.id.cbOnce); final CheckBox cbWhitelist = (CheckBox) view.findViewById(R.id.cbWhitelist); final CheckBox cbWhitelistExtra = (CheckBox) view.findViewById(R.id.cbWhitelistExtra); // Set values if ((hook != null && hook.isDangerous()) || appInfo.isSystem()) view.setBackgroundColor(resources.getColor(R.color.color_dangerous_dark)); ivAppIcon.setImageDrawable(appInfo.getIcon(context)); tvAppName.setText(TextUtils.join(", ", appInfo.getApplicationName())); String defaultAction = resources.getString(result.restricted ? R.string.title_deny : R.string.title_allow); tvAttempt.setText(resources.getString(R.string.title_attempt) + " (" + defaultAction + ")"); int catId = resources.getIdentifier("restrict_" + restriction.restrictionName, "string", self); tvCategory.setText(resources.getString(catId)); tvFunction.setText(restriction.methodName); if (restriction.extra == null) rowParameters.setVisibility(View.GONE); else tvParameters.setText(restriction.extra); cbCategory.setChecked(mSelectCategory); cbOnce.setChecked(mSelectOnce); cbOnce.setText(String.format(resources.getString(R.string.title_once), PrivacyManager.cRestrictionCacheTimeoutMs / 1000)); if (hook != null && hook.whitelist() != null && restriction.extra != null) { cbWhitelist.setText(resources.getString(R.string.title_whitelist, restriction.extra)); cbWhitelist.setVisibility(View.VISIBLE); String xextra = getXExtra(restriction, hook); if (xextra != null) { cbWhitelistExtra.setText(resources.getString(R.string.title_whitelist, xextra)); cbWhitelistExtra.setVisibility(View.VISIBLE); } } // Category, once and whitelist exclude each other cbCategory.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbOnce.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbOnce.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbWhitelist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbWhitelistExtra.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelist.setChecked(false); } } }); // Ask AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle(resources.getString(R.string.app_name)); alertDialogBuilder.setView(view); alertDialogBuilder.setIcon(resources.getDrawable(R.drawable.ic_launcher)); alertDialogBuilder.setPositiveButton(resources.getString(R.string.title_deny), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Deny result.restricted = true; mSelectCategory = cbCategory.isChecked(); mSelectOnce = cbOnce.isChecked(); if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, hook); else if (cbWhitelistExtra.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook); else if (cbOnce.isChecked()) onDemandOnce(restriction, result); else onDemandChoice(restriction, cbCategory.isChecked(), true); latch.countDown(); } }); alertDialogBuilder.setNegativeButton(resources.getString(R.string.title_allow), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Allow result.restricted = false; mSelectCategory = cbCategory.isChecked(); mSelectOnce = cbOnce.isChecked(); if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, hook); else if (cbWhitelistExtra.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook); else if (cbOnce.isChecked()) onDemandOnce(restriction, result); else onDemandChoice(restriction, cbCategory.isChecked(), false); latch.countDown(); } }); return alertDialogBuilder; } private String getXExtra(PRestriction restriction, Hook hook) { if (hook != null) if (hook.whitelist().equals(Meta.cTypeFilename)) { String folder = new File(restriction.extra).getParent(); if (!TextUtils.isEmpty(folder)) return folder + File.separatorChar + "*"; } else if (hook.whitelist().equals(Meta.cTypeIPAddress)) { int dot = restriction.extra.indexOf('.'); if (dot > 0) return '*' + restriction.extra.substring(dot); } return null; } private void onDemandWhitelist(final PRestriction restriction, String xextra, final PRestriction result, Hook hook) { try { // Set the whitelist Util.log(null, Log.WARN, (result.restricted ? "Black" : "White") + "listing " + restriction + " xextra=" + xextra); setSettingInternal(new PSetting(restriction.uid, hook.whitelist(), (xextra == null ? restriction.extra : xextra), Boolean.toString(!result.restricted))); } catch (Throwable ex) { Util.bug(null, ex); } } private void onDemandOnce(final PRestriction restriction, final PRestriction result) { Util.log(null, Log.WARN, (result.restricted ? "Deny" : "Allow") + " once " + restriction); result.time = new Date().getTime() + PrivacyManager.cRestrictionCacheTimeoutMs; CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(key)) mAskedOnceCache.remove(key); mAskedOnceCache.put(key, key); } } private void onDemandChoice(PRestriction restriction, boolean category, boolean restrict) { try { PRestriction result = new PRestriction(restriction); // Get current category restriction state boolean prevRestricted = false; CRestriction key = new CRestriction(restriction.uid, restriction.restrictionName, null, null); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) prevRestricted = mRestrictionCache.get(key).restricted; } Util.log(null, Log.WARN, "On demand choice " + restriction + " category=" + category + "/" + prevRestricted + " restrict=" + restrict); if (category || (restrict && restrict != prevRestricted)) { // Set category restriction result.methodName = null; result.restricted = restrict; result.asked = category; setRestrictionInternal(result); // Clear category on change boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false); for (Hook md : PrivacyManager.getHooks(restriction.restrictionName)) { result.methodName = md.getName(); result.restricted = (md.isDangerous() && !dangerous ? false : restrict); result.asked = category; setRestrictionInternal(result); } } if (!category) { // Set method restriction result.methodName = restriction.methodName; result.restricted = restrict; result.asked = true; result.extra = restriction.extra; setRestrictionInternal(result); } // Mark state as changed setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingState, Integer.toString(ActivityMain.STATE_CHANGED))); // Update modification time setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingModifyTime, Long.toString(System.currentTimeMillis()))); } catch (Throwable ex) { Util.bug(null, ex); } } private void notifyRestricted(final PRestriction restriction) { final Context context = getContext(); if (context != null && mHandler != null) mHandler.post(new Runnable() { @Override public void run() { long token = 0; try { token = Binder.clearCallingIdentity(); // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Notify user String text = resources.getString(R.string.msg_restrictedby); text += " (" + restriction.restrictionName + "/" + restriction.methodName + ")"; Toast.makeText(context, text, Toast.LENGTH_LONG).show(); } catch (NameNotFoundException ex) { Util.bug(null, ex); } finally { Binder.restoreCallingIdentity(token); } } }); } private boolean getSettingBool(int uid, String name, boolean defaultValue) throws RemoteException { return getSettingBool(uid, "", name, defaultValue); } private boolean getSettingBool(int uid, String type, String name, boolean defaultValue) throws RemoteException { String value = getSetting(new PSetting(uid, type, name, Boolean.toString(defaultValue))).value; return Boolean.parseBoolean(value); } private void enforcePermission() { int callingUid = Util.getAppId(Binder.getCallingUid()); if (callingUid != getXUid() && callingUid != Process.SYSTEM_UID) throw new SecurityException("xuid=" + mXUid + " calling=" + Binder.getCallingUid()); } private Context getContext() { // public static ActivityManagerService self() // frameworks/base/services/java/com/android/server/am/ActivityManagerService.java try { Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService"); Object am = cam.getMethod("self").invoke(null); if (am == null) return null; return (Context) cam.getDeclaredField("mContext").get(am); } catch (Throwable ex) { Util.bug(null, ex); return null; } } private int getXUid() { if (mXUid < 0) try { Context context = getContext(); if (context != null) { PackageManager pm = context.getPackageManager(); if (pm != null) { String self = PrivacyService.class.getPackage().getName(); ApplicationInfo xInfo = pm.getApplicationInfo(self, 0); mXUid = xInfo.uid; } } } catch (Throwable ignored) { // The package manager may not be up-to-date yet } return mXUid; } private File getDbFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "xprivacy.db"); } private File getDbUsageFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "usage.db"); } private void setupDatabase() { try { File dbFile = getDbFile(); // Create database folder dbFile.getParentFile().mkdirs(); // Check database folder if (dbFile.getParentFile().isDirectory()) Util.log(null, Log.WARN, "Database folder=" + dbFile.getParentFile()); else Util.log(null, Log.ERROR, "Does not exist folder=" + dbFile.getParentFile()); // Move database from data/xprivacy folder File folder = new File(Environment.getDataDirectory() + File.separator + "xprivacy"); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } folder.delete(); } // Move database from data/application folder folder = new File(Environment.getDataDirectory() + File.separator + "data" + File.separator + PrivacyService.class.getPackage().getName()); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } folder.delete(); } // Set database file permissions // Owner: rwx (system) // Group: rwx (system) // World: --- Util.setPermissions(dbFile.getParentFile().getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); File[] files = dbFile.getParentFile().listFiles(); if (files != null) for (File file : files) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) Util.setPermissions(file.getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); } catch (Throwable ex) { Util.bug(null, ex); } } private SQLiteDatabase getDb() { synchronized (this) { // Check current reference if (mDb != null && !mDb.isOpen()) { mDb = null; Util.log(null, Log.ERROR, "Database not open"); } mLock.readLock().lock(); try { if (mDb != null && mDb.getVersion() != 11) { mDb = null; Util.log(null, Log.ERROR, "Database wrong version=" + mDb.getVersion()); } } finally { mLock.readLock().unlock(); } if (mDb == null) try { setupDatabase(); // Create/upgrade database when needed File dbFile = getDbFile(); SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); // Check database integrity if (db.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Database integrity ok"); else { // http://www.sqlite.org/howtocorrupt.html Util.log(null, Log.ERROR, "Database corrupt"); Cursor cursor = db.rawQuery("PRAGMA integrity_check", null); try { while (cursor.moveToNext()) { String message = cursor.getString(0); Util.log(null, Log.ERROR, message); } } finally { cursor.close(); } db.close(); // Backup database file File dbBackup = new File(dbFile.getParentFile() + File.separator + "xprivacy.backup"); dbBackup.delete(); dbFile.renameTo(dbBackup); File dbJournal = new File(dbFile.getAbsolutePath() + "-journal"); File dbJournalBackup = new File(dbBackup.getAbsolutePath() + "-journal"); dbJournalBackup.delete(); dbJournal.renameTo(dbJournalBackup); Util.log(null, Log.ERROR, "Old database backup: " + dbBackup.getAbsolutePath()); // Create new database db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); Util.log(null, Log.ERROR, "New, empty database created"); } // Update migration status if (db.getVersion() > 1) { Util.log(null, Log.WARN, "Updating migration status"); mLock.writeLock().lock(); db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("uid", 0); if (db.getVersion() > 9) values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } // Upgrade database if needed if (db.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating database"); mLock.writeLock().lock(); db.beginTransaction(); try { // http://www.sqlite.org/lang_createtable.html db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)"); db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)"); db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)"); db.setVersion(1); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(2)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); // Old migrated indication db.setVersion(2); } if (db.needUpgrade(3)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM usage WHERE method=''"); db.setVersion(3); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(4)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value IS NULL"); db.setVersion(4); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(5)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value = ''"); db.execSQL("DELETE FROM setting WHERE name = 'Random@boot' AND value = 'false'"); db.setVersion(5); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(6)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE name LIKE 'OnDemand.%'"); db.setVersion(6); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(7)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("ALTER TABLE usage ADD COLUMN extra TEXT"); db.setVersion(7); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(8)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DROP INDEX idx_usage"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); db.setVersion(8); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(9)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DROP TABLE usage"); db.setVersion(9); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(10)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("ALTER TABLE setting ADD COLUMN type TEXT"); db.execSQL("DROP INDEX idx_setting"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, type, name)"); db.execSQL("UPDATE setting SET type=''"); db.setVersion(10); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(11)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { List<PSetting> listSetting = new ArrayList<PSetting>(); Cursor cursor = db.query(cTableSetting, new String[] { "uid", "name", "value" }, null, null, null, null, null); if (cursor != null) try { while (cursor.moveToNext()) { int uid = cursor.getInt(0); String name = cursor.getString(1); String value = cursor.getString(2); if (name.startsWith("Account.") || name.startsWith("Application.") || name.startsWith("Contact.") || name.startsWith("Template.")) { int dot = name.indexOf('.'); String type = name.substring(0, dot); listSetting .add(new PSetting(uid, type, name.substring(dot + 1), value)); listSetting.add(new PSetting(uid, "", name, null)); } else if (name.startsWith("Whitelist.")) { String[] component = name.split("\\."); listSetting.add(new PSetting(uid, component[1], name.replace( component[0] + "." + component[1] + ".", ""), value)); listSetting.add(new PSetting(uid, "", name, null)); } } } finally { cursor.close(); } for (PSetting setting : listSetting) { Util.log(null, Log.WARN, "Converting " + setting); if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } } db.setVersion(11); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } Util.log(null, Log.WARN, "Running VACUUM"); mLock.writeLock().lock(); try { db.execSQL("VACUUM"); } catch (Throwable ex) { Util.bug(null, ex); } finally { mLock.writeLock().unlock(); } Util.log(null, Log.WARN, "Database version=" + db.getVersion()); mDb = db; } catch (Throwable ex) { mDb = null; // retry Util.bug(null, ex); try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream( "/cache/xprivacy.log", true)); outputStreamWriter.write(ex.toString()); outputStreamWriter.write("\n"); outputStreamWriter.write(Log.getStackTraceString(ex)); outputStreamWriter.write("\n"); outputStreamWriter.close(); } catch (IOException exex) { Util.bug(null, exex); } } return mDb; } } private SQLiteDatabase getDbUsage() { synchronized (this) { // Check current reference if (mDbUsage != null && !mDbUsage.isOpen()) { mDbUsage = null; Util.log(null, Log.ERROR, "Usage database not open"); } if (mDbUsage == null) try { // Create/upgrade database when needed File dbUsageFile = getDbUsageFile(); SQLiteDatabase dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); // Check database integrity if (dbUsage.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Usage database integrity ok"); else { dbUsage.close(); dbUsageFile.delete(); new File(dbUsageFile + "-journal").delete(); dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); Util.log(null, Log.ERROR, "Deleted corrupt usage data database"); } // Upgrade database if needed if (dbUsage.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating usage database"); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { dbUsage.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, extra TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); dbUsage.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); dbUsage.setVersion(1); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } Util.log(null, Log.WARN, "Running VACUUM"); mLockUsage.writeLock().lock(); try { dbUsage.execSQL("VACUUM"); } catch (Throwable ex) { Util.bug(null, ex); } finally { mLockUsage.writeLock().unlock(); } Util.log(null, Log.WARN, "Changing to asynchronous mode"); try { dbUsage.rawQuery("PRAGMA synchronous=OFF", null); } catch (Throwable ex) { Util.bug(null, ex); } Util.log(null, Log.WARN, "Usage database version=" + dbUsage.getVersion()); mDbUsage = dbUsage; } catch (Throwable ex) { mDbUsage = null; // retry Util.bug(null, ex); } return mDbUsage; } } }; }
true
true
public List<PRestriction> getUsageList(int uid, String restrictionName) throws RemoteException { List<PRestriction> result = new ArrayList<PRestriction>(); try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); mLockUsage.readLock().lock(); dbUsage.beginTransaction(); try { Cursor cursor; if (uid == 0) { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, null, new String[] {}, null, null, "time DESC LIMIT " + cMaxUsageData); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "restriction=?", new String[] { restrictionName }, null, null, "time DESC LIMIT " + cMaxUsageData); } else { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, "time DESC LIMIT " + cMaxUsageData); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "uid=? AND restriction=?", new String[] { Integer.toString(uid), restrictionName }, null, null, "time DESC LIMIT " + cMaxUsageData); } if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (usage data)"); else try { while (cursor.moveToNext()) { PRestriction data = new PRestriction(); data.uid = cursor.getInt(0); data.restrictionName = cursor.getString(1); data.methodName = cursor.getString(2); data.restricted = (cursor.getInt(3) > 0); data.time = cursor.getLong(4); data.extra = cursor.getString(5); result.add(data); } } finally { cursor.close(); } dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return result; } @Override public void deleteUsage(int uid) throws RemoteException { try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { if (uid == 0) dbUsage.delete(cTableUsage, null, new String[] {}); else dbUsage.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Usage data deleted uid=" + uid); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } // Settings @Override public void setSetting(PSetting setting) throws RemoteException { try { enforcePermission(); setSettingInternal(setting); } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } private void setSettingInternal(PSetting setting) throws RemoteException { try { SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Update cache if (mUseCache) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); key.setValue(setting.value); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); if (setting.value != null) mSettingCache.put(key, key); } } // Clear restrictions for white list if (Meta.isWhitelist(setting.type)) for (String restrictionName : PrivacyManager.getRestrictions()) for (Hook hook : PrivacyManager.getHooks(restrictionName)) if (setting.type.equals(hook.whitelist())) { PRestriction restriction = new PRestriction(setting.uid, hook.getRestrictionName(), hook.getName()); Util.log(null, Log.WARN, "Clearing cache for " + restriction); synchronized (mRestrictionCache) { for (CRestriction key : new ArrayList<CRestriction>(mRestrictionCache.keySet())) if (key.isSameMethod(restriction)) { Util.log(null, Log.WARN, "Removing " + key); mRestrictionCache.remove(key); } } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void setSettingList(List<PSetting> listSetting) throws RemoteException { enforcePermission(); for (PSetting setting : listSetting) setSettingInternal(setting); } @Override @SuppressLint("DefaultLocale") public PSetting getSetting(PSetting setting) throws RemoteException { PSetting result = new PSetting(setting.uid, setting.type, setting.name, setting.value); try { // No permissions enforced // Check cache if (mUseCache && setting.value != null) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) { result.value = mSettingCache.get(key).getValue(); return result; } } } // No persmissions required SQLiteDatabase db = getDb(); if (db == null) return result; // Fallback if (!PrivacyManager.cSettingMigrated.equals(setting.name) && !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) { if (setting.uid == 0) result.value = PrivacyProvider.getSettingFallback(setting.name, null, false); if (result.value == null) { result.value = PrivacyProvider.getSettingFallback( String.format("%s.%d", setting.name, setting.uid), setting.value, false); return result; } } // Precompile statement when needed if (stmtGetSetting == null) { String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND type=? AND name=?"; stmtGetSetting = db.compileStatement(sql); } // Execute statement mLock.readLock().lock(); db.beginTransaction(); try { try { synchronized (stmtGetSetting) { stmtGetSetting.clearBindings(); stmtGetSetting.bindLong(1, setting.uid); stmtGetSetting.bindString(2, setting.type); stmtGetSetting.bindString(3, setting.name); String value = stmtGetSetting.simpleQueryForString(); if (value != null) result.value = value; } } catch (SQLiteDoneException ignored) { } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } // Add to cache if (mUseCache && result.value != null) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); key.setValue(result.value); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); mSettingCache.put(key, key); } } } catch (Throwable ex) { Util.bug(null, ex); } return result; } @Override public List<PSetting> getSettingList(int uid) throws RemoteException { List<PSetting> listSetting = new ArrayList<PSetting>(); try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return listSetting; mLock.readLock().lock(); db.beginTransaction(); try { Cursor cursor = db.query(cTableSetting, new String[] { "type", "name", "value" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, null); if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (settings)"); else try { while (cursor.moveToNext()) listSetting.add(new PSetting(uid, cursor.getString(0), cursor.getString(1), cursor .getString(2))); } finally { cursor.close(); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return listSetting; } @Override public void deleteSettings(int uid) throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Settings deleted uid=" + uid); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear cache if (mUseCache) synchronized (mSettingCache) { mSettingCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void clear() throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); SQLiteDatabase dbUsage = getDbUsage(); if (db == null || dbUsage == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM " + cTableRestriction); db.execSQL("DELETE FROM " + cTableSetting); Util.log(null, Log.WARN, "Database cleared"); // Reset migrated ContentValues values = new ContentValues(); values.put("uid", 0); values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear caches if (mUseCache) { synchronized (mRestrictionCache) { mRestrictionCache.clear(); } synchronized (mSettingCache) { mSettingCache.clear(); } } synchronized (mAskedOnceCache) { mAskedOnceCache.clear(); } Util.log(null, Log.WARN, "Caches cleared"); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { dbUsage.execSQL("DELETE FROM " + cTableUsage); Util.log(null, Log.WARN, "Usage database cleared"); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void reboot() throws RemoteException { try { enforcePermission(); Binder.clearCallingIdentity(); ((PowerManager) getContext().getSystemService(Context.POWER_SERVICE)).reboot(null); } catch (Throwable ex) { Util.bug(null, ex); } } @Override public void dump(int uid) throws RemoteException { if (uid == 0) { } else { synchronized (mRestrictionCache) { for (CRestriction crestriction : mRestrictionCache.keySet()) if (crestriction.getUid() == uid) Util.log(null, Log.WARN, "Dump crestriction=" + crestriction); } synchronized (mAskedOnceCache) { for (CRestriction crestriction : mAskedOnceCache.keySet()) if (crestriction.getUid() == uid && !crestriction.isExpired()) Util.log(null, Log.WARN, "Dump asked=" + crestriction); } synchronized (mSettingCache) { for (CSetting csetting : mSettingCache.keySet()) if (csetting.getUid() == uid) Util.log(null, Log.WARN, "Dump csetting=" + csetting); } } } // Helper methods private boolean onDemandDialog(final Hook hook, final PRestriction restriction, final PRestriction result) { try { // Without handler nothing can be done if (mHandler == null) return false; // Check for exceptions if (hook != null && !hook.canOnDemand()) return false; // Check if enabled if (!getSettingBool(0, PrivacyManager.cSettingOnDemand, true)) return false; if (!getSettingBool(restriction.uid, PrivacyManager.cSettingOnDemand, false)) return false; // Skip dangerous methods final boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false); if (!dangerous && hook != null && hook.isDangerous()) return false; // Get am context final Context context = getContext(); if (context == null) return false; long token = 0; try { token = Binder.clearCallingIdentity(); // Get application info final ApplicationInfoEx appInfo = new ApplicationInfoEx(context, restriction.uid); // Check if system application if (!dangerous && appInfo.isSystem()) return false; // Check if activity manager agrees if (!XActivityManagerService.canOnDemand()) return false; // Go ask Util.log(null, Log.WARN, "On demand " + restriction); mOndemandSemaphore.acquireUninterruptibly(); try { // Check if activity manager still agrees if (!XActivityManagerService.canOnDemand()) return false; Util.log(null, Log.WARN, "On demanding " + restriction); // Check if not asked before CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) if (mRestrictionCache.get(key).asked) { Util.log(null, Log.WARN, "Already asked " + restriction); return false; } } synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(key) && !mAskedOnceCache.get(key).isExpired()) { Util.log(null, Log.WARN, "Already asked once " + restriction); return false; } } if (restriction.extra != null && hook != null && hook.whitelist() != null) { CSetting skey = new CSetting(restriction.uid, hook.whitelist(), restriction.extra); CSetting xkey = null; String xextra = getXExtra(restriction, hook); if (xextra != null) xkey = new CSetting(restriction.uid, hook.whitelist(), xextra); synchronized (mSettingCache) { if (mSettingCache.containsKey(skey) || (xkey != null && mSettingCache.containsKey(xkey))) { Util.log(null, Log.WARN, "Already asked " + skey); return false; } } } final AlertDialogHolder holder = new AlertDialogHolder(); final CountDownLatch latch = new CountDownLatch(1); // Run dialog in looper mHandler.post(new Runnable() { @Override public void run() { try { // Dialog AlertDialog.Builder builder = getOnDemandDialogBuilder(restriction, hook, appInfo, dangerous, result, context, latch); AlertDialog alertDialog = builder.create(); alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE); alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); alertDialog.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); alertDialog.setCancelable(false); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); holder.dialog = alertDialog; // Progress bar final ProgressBar mProgress = (ProgressBar) alertDialog .findViewById(R.id.pbProgress); mProgress.setMax(cMaxOnDemandDialog * 20); mProgress.setProgress(cMaxOnDemandDialog * 20); Runnable rProgress = new Runnable() { @Override public void run() { AlertDialog dialog = holder.dialog; if (dialog != null && dialog.isShowing() && mProgress.getProgress() > 0) { mProgress.incrementProgressBy(-1); mHandler.postDelayed(this, 50); } } }; mHandler.postDelayed(rProgress, 50); } catch (Throwable ex) { Util.bug(null, ex); latch.countDown(); } } }); // Wait for dialog to complete if (!latch.await(cMaxOnDemandDialog, TimeUnit.SECONDS)) { Util.log(null, Log.WARN, "On demand dialog timeout " + restriction); mHandler.post(new Runnable() { @Override public void run() { AlertDialog dialog = holder.dialog; if (dialog != null) dialog.cancel(); } }); } } finally { mOndemandSemaphore.release(); } } finally { Binder.restoreCallingIdentity(token); } } catch (Throwable ex) { Util.bug(null, ex); } return true; } final class AlertDialogHolder { public AlertDialog dialog = null; } private AlertDialog.Builder getOnDemandDialogBuilder(final PRestriction restriction, final Hook hook, ApplicationInfoEx appInfo, boolean dangerous, final PRestriction result, Context context, final CountDownLatch latch) throws NameNotFoundException { // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Reference views View view = LayoutInflater.from(context.createPackageContext(self, 0)).inflate(R.layout.ondemand, null); ImageView ivAppIcon = (ImageView) view.findViewById(R.id.ivAppIcon); TextView tvAppName = (TextView) view.findViewById(R.id.tvAppName); TextView tvAttempt = (TextView) view.findViewById(R.id.tvAttempt); TextView tvCategory = (TextView) view.findViewById(R.id.tvCategory); TextView tvFunction = (TextView) view.findViewById(R.id.tvFunction); TextView tvParameters = (TextView) view.findViewById(R.id.tvParameters); TableRow rowParameters = (TableRow) view.findViewById(R.id.rowParameters); final CheckBox cbCategory = (CheckBox) view.findViewById(R.id.cbCategory); final CheckBox cbOnce = (CheckBox) view.findViewById(R.id.cbOnce); final CheckBox cbWhitelist = (CheckBox) view.findViewById(R.id.cbWhitelist); final CheckBox cbWhitelistExtra = (CheckBox) view.findViewById(R.id.cbWhitelistExtra); // Set values if ((hook != null && hook.isDangerous()) || appInfo.isSystem()) view.setBackgroundColor(resources.getColor(R.color.color_dangerous_dark)); ivAppIcon.setImageDrawable(appInfo.getIcon(context)); tvAppName.setText(TextUtils.join(", ", appInfo.getApplicationName())); String defaultAction = resources.getString(result.restricted ? R.string.title_deny : R.string.title_allow); tvAttempt.setText(resources.getString(R.string.title_attempt) + " (" + defaultAction + ")"); int catId = resources.getIdentifier("restrict_" + restriction.restrictionName, "string", self); tvCategory.setText(resources.getString(catId)); tvFunction.setText(restriction.methodName); if (restriction.extra == null) rowParameters.setVisibility(View.GONE); else tvParameters.setText(restriction.extra); cbCategory.setChecked(mSelectCategory); cbOnce.setChecked(mSelectOnce); cbOnce.setText(String.format(resources.getString(R.string.title_once), PrivacyManager.cRestrictionCacheTimeoutMs / 1000)); if (hook != null && hook.whitelist() != null && restriction.extra != null) { cbWhitelist.setText(resources.getString(R.string.title_whitelist, restriction.extra)); cbWhitelist.setVisibility(View.VISIBLE); String xextra = getXExtra(restriction, hook); if (xextra != null) { cbWhitelistExtra.setText(resources.getString(R.string.title_whitelist, xextra)); cbWhitelistExtra.setVisibility(View.VISIBLE); } } // Category, once and whitelist exclude each other cbCategory.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbOnce.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbOnce.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbWhitelist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbWhitelistExtra.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelist.setChecked(false); } } }); // Ask AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle(resources.getString(R.string.app_name)); alertDialogBuilder.setView(view); alertDialogBuilder.setIcon(resources.getDrawable(R.drawable.ic_launcher)); alertDialogBuilder.setPositiveButton(resources.getString(R.string.title_deny), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Deny result.restricted = true; mSelectCategory = cbCategory.isChecked(); mSelectOnce = cbOnce.isChecked(); if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, hook); else if (cbWhitelistExtra.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook); else if (cbOnce.isChecked()) onDemandOnce(restriction, result); else onDemandChoice(restriction, cbCategory.isChecked(), true); latch.countDown(); } }); alertDialogBuilder.setNegativeButton(resources.getString(R.string.title_allow), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Allow result.restricted = false; mSelectCategory = cbCategory.isChecked(); mSelectOnce = cbOnce.isChecked(); if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, hook); else if (cbWhitelistExtra.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook); else if (cbOnce.isChecked()) onDemandOnce(restriction, result); else onDemandChoice(restriction, cbCategory.isChecked(), false); latch.countDown(); } }); return alertDialogBuilder; } private String getXExtra(PRestriction restriction, Hook hook) { if (hook != null) if (hook.whitelist().equals(Meta.cTypeFilename)) { String folder = new File(restriction.extra).getParent(); if (!TextUtils.isEmpty(folder)) return folder + File.separatorChar + "*"; } else if (hook.whitelist().equals(Meta.cTypeIPAddress)) { int dot = restriction.extra.indexOf('.'); if (dot > 0) return '*' + restriction.extra.substring(dot); } return null; } private void onDemandWhitelist(final PRestriction restriction, String xextra, final PRestriction result, Hook hook) { try { // Set the whitelist Util.log(null, Log.WARN, (result.restricted ? "Black" : "White") + "listing " + restriction + " xextra=" + xextra); setSettingInternal(new PSetting(restriction.uid, hook.whitelist(), (xextra == null ? restriction.extra : xextra), Boolean.toString(!result.restricted))); } catch (Throwable ex) { Util.bug(null, ex); } } private void onDemandOnce(final PRestriction restriction, final PRestriction result) { Util.log(null, Log.WARN, (result.restricted ? "Deny" : "Allow") + " once " + restriction); result.time = new Date().getTime() + PrivacyManager.cRestrictionCacheTimeoutMs; CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(key)) mAskedOnceCache.remove(key); mAskedOnceCache.put(key, key); } } private void onDemandChoice(PRestriction restriction, boolean category, boolean restrict) { try { PRestriction result = new PRestriction(restriction); // Get current category restriction state boolean prevRestricted = false; CRestriction key = new CRestriction(restriction.uid, restriction.restrictionName, null, null); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) prevRestricted = mRestrictionCache.get(key).restricted; } Util.log(null, Log.WARN, "On demand choice " + restriction + " category=" + category + "/" + prevRestricted + " restrict=" + restrict); if (category || (restrict && restrict != prevRestricted)) { // Set category restriction result.methodName = null; result.restricted = restrict; result.asked = category; setRestrictionInternal(result); // Clear category on change boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false); for (Hook md : PrivacyManager.getHooks(restriction.restrictionName)) { result.methodName = md.getName(); result.restricted = (md.isDangerous() && !dangerous ? false : restrict); result.asked = category; setRestrictionInternal(result); } } if (!category) { // Set method restriction result.methodName = restriction.methodName; result.restricted = restrict; result.asked = true; result.extra = restriction.extra; setRestrictionInternal(result); } // Mark state as changed setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingState, Integer.toString(ActivityMain.STATE_CHANGED))); // Update modification time setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingModifyTime, Long.toString(System.currentTimeMillis()))); } catch (Throwable ex) { Util.bug(null, ex); } } private void notifyRestricted(final PRestriction restriction) { final Context context = getContext(); if (context != null && mHandler != null) mHandler.post(new Runnable() { @Override public void run() { long token = 0; try { token = Binder.clearCallingIdentity(); // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Notify user String text = resources.getString(R.string.msg_restrictedby); text += " (" + restriction.restrictionName + "/" + restriction.methodName + ")"; Toast.makeText(context, text, Toast.LENGTH_LONG).show(); } catch (NameNotFoundException ex) { Util.bug(null, ex); } finally { Binder.restoreCallingIdentity(token); } } }); } private boolean getSettingBool(int uid, String name, boolean defaultValue) throws RemoteException { return getSettingBool(uid, "", name, defaultValue); } private boolean getSettingBool(int uid, String type, String name, boolean defaultValue) throws RemoteException { String value = getSetting(new PSetting(uid, type, name, Boolean.toString(defaultValue))).value; return Boolean.parseBoolean(value); } private void enforcePermission() { int callingUid = Util.getAppId(Binder.getCallingUid()); if (callingUid != getXUid() && callingUid != Process.SYSTEM_UID) throw new SecurityException("xuid=" + mXUid + " calling=" + Binder.getCallingUid()); } private Context getContext() { // public static ActivityManagerService self() // frameworks/base/services/java/com/android/server/am/ActivityManagerService.java try { Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService"); Object am = cam.getMethod("self").invoke(null); if (am == null) return null; return (Context) cam.getDeclaredField("mContext").get(am); } catch (Throwable ex) { Util.bug(null, ex); return null; } } private int getXUid() { if (mXUid < 0) try { Context context = getContext(); if (context != null) { PackageManager pm = context.getPackageManager(); if (pm != null) { String self = PrivacyService.class.getPackage().getName(); ApplicationInfo xInfo = pm.getApplicationInfo(self, 0); mXUid = xInfo.uid; } } } catch (Throwable ignored) { // The package manager may not be up-to-date yet } return mXUid; } private File getDbFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "xprivacy.db"); } private File getDbUsageFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "usage.db"); } private void setupDatabase() { try { File dbFile = getDbFile(); // Create database folder dbFile.getParentFile().mkdirs(); // Check database folder if (dbFile.getParentFile().isDirectory()) Util.log(null, Log.WARN, "Database folder=" + dbFile.getParentFile()); else Util.log(null, Log.ERROR, "Does not exist folder=" + dbFile.getParentFile()); // Move database from data/xprivacy folder File folder = new File(Environment.getDataDirectory() + File.separator + "xprivacy"); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } folder.delete(); } // Move database from data/application folder folder = new File(Environment.getDataDirectory() + File.separator + "data" + File.separator + PrivacyService.class.getPackage().getName()); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } folder.delete(); } // Set database file permissions // Owner: rwx (system) // Group: rwx (system) // World: --- Util.setPermissions(dbFile.getParentFile().getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); File[] files = dbFile.getParentFile().listFiles(); if (files != null) for (File file : files) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) Util.setPermissions(file.getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); } catch (Throwable ex) { Util.bug(null, ex); } } private SQLiteDatabase getDb() { synchronized (this) { // Check current reference if (mDb != null && !mDb.isOpen()) { mDb = null; Util.log(null, Log.ERROR, "Database not open"); } mLock.readLock().lock(); try { if (mDb != null && mDb.getVersion() != 11) { mDb = null; Util.log(null, Log.ERROR, "Database wrong version=" + mDb.getVersion()); } } finally { mLock.readLock().unlock(); } if (mDb == null) try { setupDatabase(); // Create/upgrade database when needed File dbFile = getDbFile(); SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); // Check database integrity if (db.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Database integrity ok"); else { // http://www.sqlite.org/howtocorrupt.html Util.log(null, Log.ERROR, "Database corrupt"); Cursor cursor = db.rawQuery("PRAGMA integrity_check", null); try { while (cursor.moveToNext()) { String message = cursor.getString(0); Util.log(null, Log.ERROR, message); } } finally { cursor.close(); } db.close(); // Backup database file File dbBackup = new File(dbFile.getParentFile() + File.separator + "xprivacy.backup"); dbBackup.delete(); dbFile.renameTo(dbBackup); File dbJournal = new File(dbFile.getAbsolutePath() + "-journal"); File dbJournalBackup = new File(dbBackup.getAbsolutePath() + "-journal"); dbJournalBackup.delete(); dbJournal.renameTo(dbJournalBackup); Util.log(null, Log.ERROR, "Old database backup: " + dbBackup.getAbsolutePath()); // Create new database db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); Util.log(null, Log.ERROR, "New, empty database created"); } // Update migration status if (db.getVersion() > 1) { Util.log(null, Log.WARN, "Updating migration status"); mLock.writeLock().lock(); db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("uid", 0); if (db.getVersion() > 9) values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } // Upgrade database if needed if (db.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating database"); mLock.writeLock().lock(); db.beginTransaction(); try { // http://www.sqlite.org/lang_createtable.html db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)"); db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)"); db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)"); db.setVersion(1); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(2)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); // Old migrated indication db.setVersion(2); } if (db.needUpgrade(3)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM usage WHERE method=''"); db.setVersion(3); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(4)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value IS NULL"); db.setVersion(4); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(5)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value = ''"); db.execSQL("DELETE FROM setting WHERE name = 'Random@boot' AND value = 'false'"); db.setVersion(5); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(6)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE name LIKE 'OnDemand.%'"); db.setVersion(6); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(7)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("ALTER TABLE usage ADD COLUMN extra TEXT"); db.setVersion(7); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(8)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DROP INDEX idx_usage"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); db.setVersion(8); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(9)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DROP TABLE usage"); db.setVersion(9); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(10)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("ALTER TABLE setting ADD COLUMN type TEXT"); db.execSQL("DROP INDEX idx_setting"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, type, name)"); db.execSQL("UPDATE setting SET type=''"); db.setVersion(10); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(11)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { List<PSetting> listSetting = new ArrayList<PSetting>(); Cursor cursor = db.query(cTableSetting, new String[] { "uid", "name", "value" }, null, null, null, null, null); if (cursor != null) try { while (cursor.moveToNext()) { int uid = cursor.getInt(0); String name = cursor.getString(1); String value = cursor.getString(2); if (name.startsWith("Account.") || name.startsWith("Application.") || name.startsWith("Contact.") || name.startsWith("Template.")) { int dot = name.indexOf('.'); String type = name.substring(0, dot); listSetting .add(new PSetting(uid, type, name.substring(dot + 1), value)); listSetting.add(new PSetting(uid, "", name, null)); } else if (name.startsWith("Whitelist.")) { String[] component = name.split("\\."); listSetting.add(new PSetting(uid, component[1], name.replace( component[0] + "." + component[1] + ".", ""), value)); listSetting.add(new PSetting(uid, "", name, null)); } } } finally { cursor.close(); } for (PSetting setting : listSetting) { Util.log(null, Log.WARN, "Converting " + setting); if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } } db.setVersion(11); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } Util.log(null, Log.WARN, "Running VACUUM"); mLock.writeLock().lock(); try { db.execSQL("VACUUM"); } catch (Throwable ex) { Util.bug(null, ex); } finally { mLock.writeLock().unlock(); } Util.log(null, Log.WARN, "Database version=" + db.getVersion()); mDb = db; } catch (Throwable ex) { mDb = null; // retry Util.bug(null, ex); try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream( "/cache/xprivacy.log", true)); outputStreamWriter.write(ex.toString()); outputStreamWriter.write("\n"); outputStreamWriter.write(Log.getStackTraceString(ex)); outputStreamWriter.write("\n"); outputStreamWriter.close(); } catch (IOException exex) { Util.bug(null, exex); } } return mDb; } } private SQLiteDatabase getDbUsage() { synchronized (this) { // Check current reference if (mDbUsage != null && !mDbUsage.isOpen()) { mDbUsage = null; Util.log(null, Log.ERROR, "Usage database not open"); } if (mDbUsage == null) try { // Create/upgrade database when needed File dbUsageFile = getDbUsageFile(); SQLiteDatabase dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); // Check database integrity if (dbUsage.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Usage database integrity ok"); else { dbUsage.close(); dbUsageFile.delete(); new File(dbUsageFile + "-journal").delete(); dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); Util.log(null, Log.ERROR, "Deleted corrupt usage data database"); } // Upgrade database if needed if (dbUsage.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating usage database"); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { dbUsage.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, extra TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); dbUsage.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); dbUsage.setVersion(1); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } Util.log(null, Log.WARN, "Running VACUUM"); mLockUsage.writeLock().lock(); try { dbUsage.execSQL("VACUUM"); } catch (Throwable ex) { Util.bug(null, ex); } finally { mLockUsage.writeLock().unlock(); } Util.log(null, Log.WARN, "Changing to asynchronous mode"); try { dbUsage.rawQuery("PRAGMA synchronous=OFF", null); } catch (Throwable ex) { Util.bug(null, ex); } Util.log(null, Log.WARN, "Usage database version=" + dbUsage.getVersion()); mDbUsage = dbUsage; } catch (Throwable ex) { mDbUsage = null; // retry Util.bug(null, ex); } return mDbUsage; } } }; }
public List<PRestriction> getUsageList(int uid, String restrictionName) throws RemoteException { List<PRestriction> result = new ArrayList<PRestriction>(); try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); mLockUsage.readLock().lock(); dbUsage.beginTransaction(); try { Cursor cursor; if (uid == 0) { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, null, new String[] {}, null, null, "time DESC LIMIT " + cMaxUsageData); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "restriction=?", new String[] { restrictionName }, null, null, "time DESC LIMIT " + cMaxUsageData); } else { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, "time DESC LIMIT " + cMaxUsageData); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra" }, "uid=? AND restriction=?", new String[] { Integer.toString(uid), restrictionName }, null, null, "time DESC LIMIT " + cMaxUsageData); } if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (usage data)"); else try { while (cursor.moveToNext()) { PRestriction data = new PRestriction(); data.uid = cursor.getInt(0); data.restrictionName = cursor.getString(1); data.methodName = cursor.getString(2); data.restricted = (cursor.getInt(3) > 0); data.time = cursor.getLong(4); data.extra = cursor.getString(5); result.add(data); } } finally { cursor.close(); } dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return result; } @Override public void deleteUsage(int uid) throws RemoteException { try { enforcePermission(); SQLiteDatabase dbUsage = getDbUsage(); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { if (uid == 0) dbUsage.delete(cTableUsage, null, new String[] {}); else dbUsage.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Usage data deleted uid=" + uid); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } // Settings @Override public void setSetting(PSetting setting) throws RemoteException { try { enforcePermission(); setSettingInternal(setting); } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } private void setSettingInternal(PSetting setting) throws RemoteException { try { SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Update cache if (mUseCache) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); key.setValue(setting.value); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); if (setting.value != null) mSettingCache.put(key, key); } } // Clear restrictions for white list if (Meta.isWhitelist(setting.type)) for (String restrictionName : PrivacyManager.getRestrictions()) for (Hook hook : PrivacyManager.getHooks(restrictionName)) if (setting.type.equals(hook.whitelist())) { PRestriction restriction = new PRestriction(setting.uid, hook.getRestrictionName(), hook.getName()); Util.log(null, Log.WARN, "Clearing cache for " + restriction); synchronized (mRestrictionCache) { for (CRestriction key : new ArrayList<CRestriction>(mRestrictionCache.keySet())) if (key.isSameMethod(restriction)) { Util.log(null, Log.WARN, "Removing " + key); mRestrictionCache.remove(key); } } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void setSettingList(List<PSetting> listSetting) throws RemoteException { enforcePermission(); for (PSetting setting : listSetting) setSettingInternal(setting); } @Override @SuppressLint("DefaultLocale") public PSetting getSetting(PSetting setting) throws RemoteException { PSetting result = new PSetting(setting.uid, setting.type, setting.name, setting.value); try { // No permissions enforced // Check cache if (mUseCache && setting.value != null) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) { result.value = mSettingCache.get(key).getValue(); return result; } } } // No persmissions required SQLiteDatabase db = getDb(); if (db == null) return result; // Fallback if (!PrivacyManager.cSettingMigrated.equals(setting.name) && !getSettingBool(0, PrivacyManager.cSettingMigrated, false)) { if (setting.uid == 0) result.value = PrivacyProvider.getSettingFallback(setting.name, null, false); if (result.value == null) { result.value = PrivacyProvider.getSettingFallback( String.format("%s.%d", setting.name, setting.uid), setting.value, false); return result; } } // Precompile statement when needed if (stmtGetSetting == null) { String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND type=? AND name=?"; stmtGetSetting = db.compileStatement(sql); } // Execute statement mLock.readLock().lock(); db.beginTransaction(); try { try { synchronized (stmtGetSetting) { stmtGetSetting.clearBindings(); stmtGetSetting.bindLong(1, setting.uid); stmtGetSetting.bindString(2, setting.type); stmtGetSetting.bindString(3, setting.name); String value = stmtGetSetting.simpleQueryForString(); if (value != null) result.value = value; } } catch (SQLiteDoneException ignored) { } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } // Add to cache if (mUseCache && result.value != null) { CSetting key = new CSetting(setting.uid, setting.type, setting.name); key.setValue(result.value); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); mSettingCache.put(key, key); } } } catch (Throwable ex) { Util.bug(null, ex); } return result; } @Override public List<PSetting> getSettingList(int uid) throws RemoteException { List<PSetting> listSetting = new ArrayList<PSetting>(); try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return listSetting; mLock.readLock().lock(); db.beginTransaction(); try { Cursor cursor = db.query(cTableSetting, new String[] { "type", "name", "value" }, "uid=?", new String[] { Integer.toString(uid) }, null, null, null); if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (settings)"); else try { while (cursor.moveToNext()) listSetting.add(new PSetting(uid, cursor.getString(0), cursor.getString(1), cursor .getString(2))); } finally { cursor.close(); } db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.readLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return listSetting; } @Override public void deleteSettings(int uid) throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Settings deleted uid=" + uid); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear cache if (mUseCache) synchronized (mSettingCache) { mSettingCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void clear() throws RemoteException { try { enforcePermission(); SQLiteDatabase db = getDb(); SQLiteDatabase dbUsage = getDbUsage(); if (db == null || dbUsage == null) return; mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM " + cTableRestriction); db.execSQL("DELETE FROM " + cTableSetting); Util.log(null, Log.WARN, "Database cleared"); // Reset migrated ContentValues values = new ContentValues(); values.put("uid", 0); values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } // Clear caches if (mUseCache) { synchronized (mRestrictionCache) { mRestrictionCache.clear(); } synchronized (mSettingCache) { mSettingCache.clear(); } } synchronized (mAskedOnceCache) { mAskedOnceCache.clear(); } Util.log(null, Log.WARN, "Caches cleared"); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { dbUsage.execSQL("DELETE FROM " + cTableUsage); Util.log(null, Log.WARN, "Usage database cleared"); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void reboot() throws RemoteException { try { enforcePermission(); Binder.clearCallingIdentity(); ((PowerManager) getContext().getSystemService(Context.POWER_SERVICE)).reboot(null); } catch (Throwable ex) { Util.bug(null, ex); } } @Override public void dump(int uid) throws RemoteException { if (uid == 0) { } else { synchronized (mRestrictionCache) { for (CRestriction crestriction : mRestrictionCache.keySet()) if (crestriction.getUid() == uid) Util.log(null, Log.WARN, "Dump crestriction=" + crestriction); } synchronized (mAskedOnceCache) { for (CRestriction crestriction : mAskedOnceCache.keySet()) if (crestriction.getUid() == uid && !crestriction.isExpired()) Util.log(null, Log.WARN, "Dump asked=" + crestriction); } synchronized (mSettingCache) { for (CSetting csetting : mSettingCache.keySet()) if (csetting.getUid() == uid) Util.log(null, Log.WARN, "Dump csetting=" + csetting); } } } // Helper methods private boolean onDemandDialog(final Hook hook, final PRestriction restriction, final PRestriction result) { try { // Without handler nothing can be done if (mHandler == null) return false; // Check for exceptions if (hook != null && !hook.canOnDemand()) return false; // Check if enabled if (!getSettingBool(0, PrivacyManager.cSettingOnDemand, true)) return false; if (!getSettingBool(restriction.uid, PrivacyManager.cSettingOnDemand, false)) return false; // Skip dangerous methods final boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false); if (!dangerous && hook != null && hook.isDangerous()) return false; // Get am context final Context context = getContext(); if (context == null) return false; long token = 0; try { token = Binder.clearCallingIdentity(); // Get application info final ApplicationInfoEx appInfo = new ApplicationInfoEx(context, restriction.uid); // Check if system application if (!dangerous && appInfo.isSystem()) return false; // Check if activity manager agrees if (!XActivityManagerService.canOnDemand()) return false; // Go ask Util.log(null, Log.WARN, "On demand " + restriction); mOndemandSemaphore.acquireUninterruptibly(); try { // Check if activity manager still agrees if (!XActivityManagerService.canOnDemand()) return false; Util.log(null, Log.WARN, "On demanding " + restriction); // Check if not asked before CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) if (mRestrictionCache.get(key).asked) { Util.log(null, Log.WARN, "Already asked " + restriction); return false; } } synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(key) && !mAskedOnceCache.get(key).isExpired()) { Util.log(null, Log.WARN, "Already asked once " + restriction); return false; } } if (restriction.extra != null && hook != null && hook.whitelist() != null) { CSetting skey = new CSetting(restriction.uid, hook.whitelist(), restriction.extra); CSetting xkey = null; String xextra = getXExtra(restriction, hook); if (xextra != null) xkey = new CSetting(restriction.uid, hook.whitelist(), xextra); synchronized (mSettingCache) { if (mSettingCache.containsKey(skey) || (xkey != null && mSettingCache.containsKey(xkey))) { Util.log(null, Log.WARN, "Already asked " + skey); return false; } } } final AlertDialogHolder holder = new AlertDialogHolder(); final CountDownLatch latch = new CountDownLatch(1); // Run dialog in looper mHandler.post(new Runnable() { @Override public void run() { try { // Dialog AlertDialog.Builder builder = getOnDemandDialogBuilder(restriction, hook, appInfo, dangerous, result, context, latch); AlertDialog alertDialog = builder.create(); alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE); alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); alertDialog.setCancelable(false); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); holder.dialog = alertDialog; // Progress bar final ProgressBar mProgress = (ProgressBar) alertDialog .findViewById(R.id.pbProgress); mProgress.setMax(cMaxOnDemandDialog * 20); mProgress.setProgress(cMaxOnDemandDialog * 20); Runnable rProgress = new Runnable() { @Override public void run() { AlertDialog dialog = holder.dialog; if (dialog != null && dialog.isShowing() && mProgress.getProgress() > 0) { mProgress.incrementProgressBy(-1); mHandler.postDelayed(this, 50); } } }; mHandler.postDelayed(rProgress, 50); } catch (Throwable ex) { Util.bug(null, ex); latch.countDown(); } } }); // Wait for dialog to complete if (!latch.await(cMaxOnDemandDialog, TimeUnit.SECONDS)) { Util.log(null, Log.WARN, "On demand dialog timeout " + restriction); mHandler.post(new Runnable() { @Override public void run() { AlertDialog dialog = holder.dialog; if (dialog != null) dialog.cancel(); } }); } } finally { mOndemandSemaphore.release(); } } finally { Binder.restoreCallingIdentity(token); } } catch (Throwable ex) { Util.bug(null, ex); } return true; } final class AlertDialogHolder { public AlertDialog dialog = null; } private AlertDialog.Builder getOnDemandDialogBuilder(final PRestriction restriction, final Hook hook, ApplicationInfoEx appInfo, boolean dangerous, final PRestriction result, Context context, final CountDownLatch latch) throws NameNotFoundException { // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Reference views View view = LayoutInflater.from(context.createPackageContext(self, 0)).inflate(R.layout.ondemand, null); ImageView ivAppIcon = (ImageView) view.findViewById(R.id.ivAppIcon); TextView tvAppName = (TextView) view.findViewById(R.id.tvAppName); TextView tvAttempt = (TextView) view.findViewById(R.id.tvAttempt); TextView tvCategory = (TextView) view.findViewById(R.id.tvCategory); TextView tvFunction = (TextView) view.findViewById(R.id.tvFunction); TextView tvParameters = (TextView) view.findViewById(R.id.tvParameters); TableRow rowParameters = (TableRow) view.findViewById(R.id.rowParameters); final CheckBox cbCategory = (CheckBox) view.findViewById(R.id.cbCategory); final CheckBox cbOnce = (CheckBox) view.findViewById(R.id.cbOnce); final CheckBox cbWhitelist = (CheckBox) view.findViewById(R.id.cbWhitelist); final CheckBox cbWhitelistExtra = (CheckBox) view.findViewById(R.id.cbWhitelistExtra); // Set values if ((hook != null && hook.isDangerous()) || appInfo.isSystem()) view.setBackgroundColor(resources.getColor(R.color.color_dangerous_dark)); ivAppIcon.setImageDrawable(appInfo.getIcon(context)); tvAppName.setText(TextUtils.join(", ", appInfo.getApplicationName())); String defaultAction = resources.getString(result.restricted ? R.string.title_deny : R.string.title_allow); tvAttempt.setText(resources.getString(R.string.title_attempt) + " (" + defaultAction + ")"); int catId = resources.getIdentifier("restrict_" + restriction.restrictionName, "string", self); tvCategory.setText(resources.getString(catId)); tvFunction.setText(restriction.methodName); if (restriction.extra == null) rowParameters.setVisibility(View.GONE); else tvParameters.setText(restriction.extra); cbCategory.setChecked(mSelectCategory); cbOnce.setChecked(mSelectOnce); cbOnce.setText(String.format(resources.getString(R.string.title_once), PrivacyManager.cRestrictionCacheTimeoutMs / 1000)); if (hook != null && hook.whitelist() != null && restriction.extra != null) { cbWhitelist.setText(resources.getString(R.string.title_whitelist, restriction.extra)); cbWhitelist.setVisibility(View.VISIBLE); String xextra = getXExtra(restriction, hook); if (xextra != null) { cbWhitelistExtra.setText(resources.getString(R.string.title_whitelist, xextra)); cbWhitelistExtra.setVisibility(View.VISIBLE); } } // Category, once and whitelist exclude each other cbCategory.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbOnce.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbOnce.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbWhitelist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelistExtra.setChecked(false); } } }); cbWhitelistExtra.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelist.setChecked(false); } } }); // Ask AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle(resources.getString(R.string.app_name)); alertDialogBuilder.setView(view); alertDialogBuilder.setIcon(resources.getDrawable(R.drawable.ic_launcher)); alertDialogBuilder.setPositiveButton(resources.getString(R.string.title_deny), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Deny result.restricted = true; mSelectCategory = cbCategory.isChecked(); mSelectOnce = cbOnce.isChecked(); if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, hook); else if (cbWhitelistExtra.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook); else if (cbOnce.isChecked()) onDemandOnce(restriction, result); else onDemandChoice(restriction, cbCategory.isChecked(), true); latch.countDown(); } }); alertDialogBuilder.setNegativeButton(resources.getString(R.string.title_allow), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Allow result.restricted = false; mSelectCategory = cbCategory.isChecked(); mSelectOnce = cbOnce.isChecked(); if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, hook); else if (cbWhitelistExtra.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook), result, hook); else if (cbOnce.isChecked()) onDemandOnce(restriction, result); else onDemandChoice(restriction, cbCategory.isChecked(), false); latch.countDown(); } }); return alertDialogBuilder; } private String getXExtra(PRestriction restriction, Hook hook) { if (hook != null) if (hook.whitelist().equals(Meta.cTypeFilename)) { String folder = new File(restriction.extra).getParent(); if (!TextUtils.isEmpty(folder)) return folder + File.separatorChar + "*"; } else if (hook.whitelist().equals(Meta.cTypeIPAddress)) { int dot = restriction.extra.indexOf('.'); if (dot > 0) return '*' + restriction.extra.substring(dot); } return null; } private void onDemandWhitelist(final PRestriction restriction, String xextra, final PRestriction result, Hook hook) { try { // Set the whitelist Util.log(null, Log.WARN, (result.restricted ? "Black" : "White") + "listing " + restriction + " xextra=" + xextra); setSettingInternal(new PSetting(restriction.uid, hook.whitelist(), (xextra == null ? restriction.extra : xextra), Boolean.toString(!result.restricted))); } catch (Throwable ex) { Util.bug(null, ex); } } private void onDemandOnce(final PRestriction restriction, final PRestriction result) { Util.log(null, Log.WARN, (result.restricted ? "Deny" : "Allow") + " once " + restriction); result.time = new Date().getTime() + PrivacyManager.cRestrictionCacheTimeoutMs; CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(key)) mAskedOnceCache.remove(key); mAskedOnceCache.put(key, key); } } private void onDemandChoice(PRestriction restriction, boolean category, boolean restrict) { try { PRestriction result = new PRestriction(restriction); // Get current category restriction state boolean prevRestricted = false; CRestriction key = new CRestriction(restriction.uid, restriction.restrictionName, null, null); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) prevRestricted = mRestrictionCache.get(key).restricted; } Util.log(null, Log.WARN, "On demand choice " + restriction + " category=" + category + "/" + prevRestricted + " restrict=" + restrict); if (category || (restrict && restrict != prevRestricted)) { // Set category restriction result.methodName = null; result.restricted = restrict; result.asked = category; setRestrictionInternal(result); // Clear category on change boolean dangerous = getSettingBool(0, PrivacyManager.cSettingDangerous, false); for (Hook md : PrivacyManager.getHooks(restriction.restrictionName)) { result.methodName = md.getName(); result.restricted = (md.isDangerous() && !dangerous ? false : restrict); result.asked = category; setRestrictionInternal(result); } } if (!category) { // Set method restriction result.methodName = restriction.methodName; result.restricted = restrict; result.asked = true; result.extra = restriction.extra; setRestrictionInternal(result); } // Mark state as changed setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingState, Integer.toString(ActivityMain.STATE_CHANGED))); // Update modification time setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingModifyTime, Long.toString(System.currentTimeMillis()))); } catch (Throwable ex) { Util.bug(null, ex); } } private void notifyRestricted(final PRestriction restriction) { final Context context = getContext(); if (context != null && mHandler != null) mHandler.post(new Runnable() { @Override public void run() { long token = 0; try { token = Binder.clearCallingIdentity(); // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Notify user String text = resources.getString(R.string.msg_restrictedby); text += " (" + restriction.restrictionName + "/" + restriction.methodName + ")"; Toast.makeText(context, text, Toast.LENGTH_LONG).show(); } catch (NameNotFoundException ex) { Util.bug(null, ex); } finally { Binder.restoreCallingIdentity(token); } } }); } private boolean getSettingBool(int uid, String name, boolean defaultValue) throws RemoteException { return getSettingBool(uid, "", name, defaultValue); } private boolean getSettingBool(int uid, String type, String name, boolean defaultValue) throws RemoteException { String value = getSetting(new PSetting(uid, type, name, Boolean.toString(defaultValue))).value; return Boolean.parseBoolean(value); } private void enforcePermission() { int callingUid = Util.getAppId(Binder.getCallingUid()); if (callingUid != getXUid() && callingUid != Process.SYSTEM_UID) throw new SecurityException("xuid=" + mXUid + " calling=" + Binder.getCallingUid()); } private Context getContext() { // public static ActivityManagerService self() // frameworks/base/services/java/com/android/server/am/ActivityManagerService.java try { Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService"); Object am = cam.getMethod("self").invoke(null); if (am == null) return null; return (Context) cam.getDeclaredField("mContext").get(am); } catch (Throwable ex) { Util.bug(null, ex); return null; } } private int getXUid() { if (mXUid < 0) try { Context context = getContext(); if (context != null) { PackageManager pm = context.getPackageManager(); if (pm != null) { String self = PrivacyService.class.getPackage().getName(); ApplicationInfo xInfo = pm.getApplicationInfo(self, 0); mXUid = xInfo.uid; } } } catch (Throwable ignored) { // The package manager may not be up-to-date yet } return mXUid; } private File getDbFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "xprivacy.db"); } private File getDbUsageFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "usage.db"); } private void setupDatabase() { try { File dbFile = getDbFile(); // Create database folder dbFile.getParentFile().mkdirs(); // Check database folder if (dbFile.getParentFile().isDirectory()) Util.log(null, Log.WARN, "Database folder=" + dbFile.getParentFile()); else Util.log(null, Log.ERROR, "Does not exist folder=" + dbFile.getParentFile()); // Move database from data/xprivacy folder File folder = new File(Environment.getDataDirectory() + File.separator + "xprivacy"); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } folder.delete(); } // Move database from data/application folder folder = new File(Environment.getDataDirectory() + File.separator + "data" + File.separator + PrivacyService.class.getPackage().getName()); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } folder.delete(); } // Set database file permissions // Owner: rwx (system) // Group: rwx (system) // World: --- Util.setPermissions(dbFile.getParentFile().getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); File[] files = dbFile.getParentFile().listFiles(); if (files != null) for (File file : files) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) Util.setPermissions(file.getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); } catch (Throwable ex) { Util.bug(null, ex); } } private SQLiteDatabase getDb() { synchronized (this) { // Check current reference if (mDb != null && !mDb.isOpen()) { mDb = null; Util.log(null, Log.ERROR, "Database not open"); } mLock.readLock().lock(); try { if (mDb != null && mDb.getVersion() != 11) { mDb = null; Util.log(null, Log.ERROR, "Database wrong version=" + mDb.getVersion()); } } finally { mLock.readLock().unlock(); } if (mDb == null) try { setupDatabase(); // Create/upgrade database when needed File dbFile = getDbFile(); SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); // Check database integrity if (db.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Database integrity ok"); else { // http://www.sqlite.org/howtocorrupt.html Util.log(null, Log.ERROR, "Database corrupt"); Cursor cursor = db.rawQuery("PRAGMA integrity_check", null); try { while (cursor.moveToNext()) { String message = cursor.getString(0); Util.log(null, Log.ERROR, message); } } finally { cursor.close(); } db.close(); // Backup database file File dbBackup = new File(dbFile.getParentFile() + File.separator + "xprivacy.backup"); dbBackup.delete(); dbFile.renameTo(dbBackup); File dbJournal = new File(dbFile.getAbsolutePath() + "-journal"); File dbJournalBackup = new File(dbBackup.getAbsolutePath() + "-journal"); dbJournalBackup.delete(); dbJournal.renameTo(dbJournalBackup); Util.log(null, Log.ERROR, "Old database backup: " + dbBackup.getAbsolutePath()); // Create new database db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); Util.log(null, Log.ERROR, "New, empty database created"); } // Update migration status if (db.getVersion() > 1) { Util.log(null, Log.WARN, "Updating migration status"); mLock.writeLock().lock(); db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("uid", 0); if (db.getVersion() > 9) values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } // Upgrade database if needed if (db.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating database"); mLock.writeLock().lock(); db.beginTransaction(); try { // http://www.sqlite.org/lang_createtable.html db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)"); db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)"); db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)"); db.setVersion(1); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(2)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); // Old migrated indication db.setVersion(2); } if (db.needUpgrade(3)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM usage WHERE method=''"); db.setVersion(3); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(4)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value IS NULL"); db.setVersion(4); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(5)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value = ''"); db.execSQL("DELETE FROM setting WHERE name = 'Random@boot' AND value = 'false'"); db.setVersion(5); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(6)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE name LIKE 'OnDemand.%'"); db.setVersion(6); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(7)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("ALTER TABLE usage ADD COLUMN extra TEXT"); db.setVersion(7); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(8)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DROP INDEX idx_usage"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); db.setVersion(8); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(9)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("DROP TABLE usage"); db.setVersion(9); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(10)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { db.execSQL("ALTER TABLE setting ADD COLUMN type TEXT"); db.execSQL("DROP INDEX idx_setting"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, type, name)"); db.execSQL("UPDATE setting SET type=''"); db.setVersion(10); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } if (db.needUpgrade(11)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); db.beginTransaction(); try { List<PSetting> listSetting = new ArrayList<PSetting>(); Cursor cursor = db.query(cTableSetting, new String[] { "uid", "name", "value" }, null, null, null, null, null); if (cursor != null) try { while (cursor.moveToNext()) { int uid = cursor.getInt(0); String name = cursor.getString(1); String value = cursor.getString(2); if (name.startsWith("Account.") || name.startsWith("Application.") || name.startsWith("Contact.") || name.startsWith("Template.")) { int dot = name.indexOf('.'); String type = name.substring(0, dot); listSetting .add(new PSetting(uid, type, name.substring(dot + 1), value)); listSetting.add(new PSetting(uid, "", name, null)); } else if (name.startsWith("Whitelist.")) { String[] component = name.split("\\."); listSetting.add(new PSetting(uid, component[1], name.replace( component[0] + "." + component[1] + ".", ""), value)); listSetting.add(new PSetting(uid, "", name, null)); } } } finally { cursor.close(); } for (PSetting setting : listSetting) { Util.log(null, Log.WARN, "Converting " + setting); if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } } db.setVersion(11); db.setTransactionSuccessful(); } finally { try { db.endTransaction(); } finally { mLock.writeLock().unlock(); } } } Util.log(null, Log.WARN, "Running VACUUM"); mLock.writeLock().lock(); try { db.execSQL("VACUUM"); } catch (Throwable ex) { Util.bug(null, ex); } finally { mLock.writeLock().unlock(); } Util.log(null, Log.WARN, "Database version=" + db.getVersion()); mDb = db; } catch (Throwable ex) { mDb = null; // retry Util.bug(null, ex); try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream( "/cache/xprivacy.log", true)); outputStreamWriter.write(ex.toString()); outputStreamWriter.write("\n"); outputStreamWriter.write(Log.getStackTraceString(ex)); outputStreamWriter.write("\n"); outputStreamWriter.close(); } catch (IOException exex) { Util.bug(null, exex); } } return mDb; } } private SQLiteDatabase getDbUsage() { synchronized (this) { // Check current reference if (mDbUsage != null && !mDbUsage.isOpen()) { mDbUsage = null; Util.log(null, Log.ERROR, "Usage database not open"); } if (mDbUsage == null) try { // Create/upgrade database when needed File dbUsageFile = getDbUsageFile(); SQLiteDatabase dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); // Check database integrity if (dbUsage.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Usage database integrity ok"); else { dbUsage.close(); dbUsageFile.delete(); new File(dbUsageFile + "-journal").delete(); dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); Util.log(null, Log.ERROR, "Deleted corrupt usage data database"); } // Upgrade database if needed if (dbUsage.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating usage database"); mLockUsage.writeLock().lock(); dbUsage.beginTransaction(); try { dbUsage.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, extra TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); dbUsage.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); dbUsage.setVersion(1); dbUsage.setTransactionSuccessful(); } finally { try { dbUsage.endTransaction(); } finally { mLockUsage.writeLock().unlock(); } } } Util.log(null, Log.WARN, "Running VACUUM"); mLockUsage.writeLock().lock(); try { dbUsage.execSQL("VACUUM"); } catch (Throwable ex) { Util.bug(null, ex); } finally { mLockUsage.writeLock().unlock(); } Util.log(null, Log.WARN, "Changing to asynchronous mode"); try { dbUsage.rawQuery("PRAGMA synchronous=OFF", null); } catch (Throwable ex) { Util.bug(null, ex); } Util.log(null, Log.WARN, "Usage database version=" + dbUsage.getVersion()); mDbUsage = dbUsage; } catch (Throwable ex) { mDbUsage = null; // retry Util.bug(null, ex); } return mDbUsage; } } }; }
diff --git a/logdoc-core/src/main/java/org/znerd/logdoc/internal/Resolver.java b/logdoc-core/src/main/java/org/znerd/logdoc/internal/Resolver.java index e069c92..fd0a7de 100644 --- a/logdoc-core/src/main/java/org/znerd/logdoc/internal/Resolver.java +++ b/logdoc-core/src/main/java/org/znerd/logdoc/internal/Resolver.java @@ -1,123 +1,124 @@ // See the COPYRIGHT file for copyright and license information package org.znerd.logdoc.internal; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamSource; import org.w3c.dom.Document; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.znerd.logdoc.Library; import org.znerd.util.Preconditions; import org.znerd.util.log.LogLevel; import static org.znerd.util.log.Limb.log; /** * URI resolver that can be used during XSLT transformations to resolve input files and XSLT files. */ public class Resolver implements URIResolver { private final File inputDir; private final String xsltBaseDir; public Resolver(File inputDir, String xsltBaseDir) throws IllegalArgumentException { Preconditions.checkArgument(inputDir == null, "inputDir == null"); Preconditions.checkArgument(xsltBaseDir == null, "xsltBaseDir == null"); this.inputDir = inputDir; this.xsltBaseDir = xsltBaseDir; log(LogLevel.DEBUG, "Created Resolver for input directory \"" + inputDir.getAbsolutePath() + "\" with XSLT base directory \"" + xsltBaseDir + "\"."); } public Document loadInputDocument(String fileName) throws IllegalArgumentException, IOException { Preconditions.checkArgument(fileName == null, "fileName == null"); log(LogLevel.DEBUG, "Loading input document \"" + fileName + "\"."); File file = createFileObject(fileName); return loadInputDocumentImpl(fileName, file); } private final File createFileObject(String fileName) { File file = new File(fileName); if (!file.isAbsolute()) { file = new File(inputDir, fileName); } return file; } private Document loadInputDocumentImpl(String fileName, File file) throws FactoryConfigurationError, IOException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); factory.setValidating(false); DocumentBuilder domBuilder = factory.newDocumentBuilder(); domBuilder.setErrorHandler(new ErrorHandler()); return domBuilder.parse(file); } catch (ParserConfigurationException cause) { throw new IOException("Failed to parse \"" + fileName + "\" file.", cause); } catch (SAXException cause) { throw new IOException("Failed to parse \"" + fileName + "\" file.", cause); } } public Source resolve(String href, String base) throws TransformerException { Preconditions.checkArgument(href == null, "href == null"); log(LogLevel.INFO, "Resolving href \"" + href + "\" (with base \"" + base + "\") during XSLT transformation."); if (href.endsWith(".xslt")) { return resolveXsltFileForTransformation(href); } else if (href.endsWith(".xml")) { return resolveInputFile(href); } else { throw new TransformerException("File with href \"" + href + "\" is not recognized."); } } private Source resolveXsltFileForTransformation(String href) throws TransformerException { try { return resolveXsltFile(href); } catch (IOException cause) { throw new TransformerException("Failed to open meta resource \"" + href + "\".", cause); } } public Source resolveXsltFile(String href) throws IOException { String resultUrl = "xslt/" + xsltBaseDir + href; return new StreamSource(Library.getMetaResourceAsStream(resultUrl)); } private Source resolveInputFile(String href) { return new StreamSource(createFileObject(href)); } private static class ErrorHandler implements org.xml.sax.ErrorHandler { @Override public void warning(SAXParseException exception) throws SAXException { log(LogLevel.WARNING, "Warning during XML parsing.", exception); } @Override public void error(SAXParseException exception) throws SAXException { log(LogLevel.ERROR, "Error during XML parsing.", exception); throw new SAXException(exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { log(LogLevel.ERROR, "Fatal error during XML parsing.", exception); throw new SAXException(exception); } } }
true
true
private Document loadInputDocumentImpl(String fileName, File file) throws FactoryConfigurationError, IOException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder domBuilder = factory.newDocumentBuilder(); domBuilder.setErrorHandler(new ErrorHandler()); return domBuilder.parse(file); } catch (ParserConfigurationException cause) { throw new IOException("Failed to parse \"" + fileName + "\" file.", cause); } catch (SAXException cause) { throw new IOException("Failed to parse \"" + fileName + "\" file.", cause); } }
private Document loadInputDocumentImpl(String fileName, File file) throws FactoryConfigurationError, IOException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); DocumentBuilder domBuilder = factory.newDocumentBuilder(); domBuilder.setErrorHandler(new ErrorHandler()); return domBuilder.parse(file); } catch (ParserConfigurationException cause) { throw new IOException("Failed to parse \"" + fileName + "\" file.", cause); } catch (SAXException cause) { throw new IOException("Failed to parse \"" + fileName + "\" file.", cause); } }
diff --git a/Sweng2012QuizApp/src/epfl/sweng/tasks/SubmitQuestionVerdict.java b/Sweng2012QuizApp/src/epfl/sweng/tasks/SubmitQuestionVerdict.java index b781fc2..0e38dc8 100644 --- a/Sweng2012QuizApp/src/epfl/sweng/tasks/SubmitQuestionVerdict.java +++ b/Sweng2012QuizApp/src/epfl/sweng/tasks/SubmitQuestionVerdict.java @@ -1,114 +1,114 @@ package epfl.sweng.tasks; import java.io.UnsupportedEncodingException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import epfl.sweng.globals.Globals; import epfl.sweng.quizquestions.QuizQuestion; import epfl.sweng.tasks.interfaces.IQuestionPersonalRatingReloadedCallback; import epfl.sweng.tasks.interfaces.IQuestionRatingReloadedCallback; import epfl.sweng.tasks.interfaces.IQuizQuestionVerdictSubmittedCallback; import epfl.sweng.tasks.interfaces.IQuizServerCallback; /** * QuizServerTask realization that fetches the rating of a question */ public class SubmitQuestionVerdict extends QuizServerTask { private QuizQuestion mQuestion; /** * Constructor * @param callback interface defining the methods to be called * for the outcomes of success (onSuccess) or error (onError) */ public SubmitQuestionVerdict(final IQuizQuestionVerdictSubmittedCallback callback, final QuizQuestion question) { super(new IQuizServerCallback() { @Override public void onSuccess(final JSONTokener response) { if (getLastStatusCode() != Globals.STATUSCODE_OK && getLastStatusCode() != Globals.STATUSCODE_CREATED) { onError(); } else { try { JSONObject responseJSON = (JSONObject) response.nextValue(); - if (responseJSON.getString("verdict") != question.getVerdict()){ + if (responseJSON.getString("verdict") != question.getVerdict()) { onError(); } else { callback.onSubmitSuccess(question); new ReloadPersonalRating(new IQuestionPersonalRatingReloadedCallback() { @Override public void onReloadedSuccess(QuizQuestion question) { callback.onReloadedSuccess(question); new ReloadQuestionRating(new IQuestionRatingReloadedCallback() { @Override public void onReloadedSuccess(QuizQuestion question) { callback.onReloadedSuccess(question); } @Override public void onError() { callback.onReloadedError(); } }, question).execute(); } @Override public void onError() { callback.onReloadedError(); } }, question).execute(); } } catch (ClassCastException e) { onError(); } catch (JSONException e) { onError(); } } } @Override public void onError() { callback.onSubmitError(); } }); mQuestion = question; } /** * Method submitting the new question verdict * * @param question the Question containing the new verdict to be submitted */ @Override protected JSONTokener doInBackground(Object... args) { HttpPost post = new HttpPost(Globals.QUESTION_BY_ID_URL + mQuestion.getId() + "/rating"); try { JSONObject verdictJson = new JSONObject(); verdictJson.put("verdict", mQuestion.getVerdict()); post.setEntity(new StringEntity(verdictJson.toString())); } catch (UnsupportedEncodingException e) { cancel(false); } catch (JSONException e) { cancel(false); } post.setHeader("Content-type", "application/json"); return handleQuizServerRequest(post); } }
true
true
public SubmitQuestionVerdict(final IQuizQuestionVerdictSubmittedCallback callback, final QuizQuestion question) { super(new IQuizServerCallback() { @Override public void onSuccess(final JSONTokener response) { if (getLastStatusCode() != Globals.STATUSCODE_OK && getLastStatusCode() != Globals.STATUSCODE_CREATED) { onError(); } else { try { JSONObject responseJSON = (JSONObject) response.nextValue(); if (responseJSON.getString("verdict") != question.getVerdict()){ onError(); } else { callback.onSubmitSuccess(question); new ReloadPersonalRating(new IQuestionPersonalRatingReloadedCallback() { @Override public void onReloadedSuccess(QuizQuestion question) { callback.onReloadedSuccess(question); new ReloadQuestionRating(new IQuestionRatingReloadedCallback() { @Override public void onReloadedSuccess(QuizQuestion question) { callback.onReloadedSuccess(question); } @Override public void onError() { callback.onReloadedError(); } }, question).execute(); } @Override public void onError() { callback.onReloadedError(); } }, question).execute(); } } catch (ClassCastException e) { onError(); } catch (JSONException e) { onError(); } } } @Override public void onError() { callback.onSubmitError(); } }); mQuestion = question; }
public SubmitQuestionVerdict(final IQuizQuestionVerdictSubmittedCallback callback, final QuizQuestion question) { super(new IQuizServerCallback() { @Override public void onSuccess(final JSONTokener response) { if (getLastStatusCode() != Globals.STATUSCODE_OK && getLastStatusCode() != Globals.STATUSCODE_CREATED) { onError(); } else { try { JSONObject responseJSON = (JSONObject) response.nextValue(); if (responseJSON.getString("verdict") != question.getVerdict()) { onError(); } else { callback.onSubmitSuccess(question); new ReloadPersonalRating(new IQuestionPersonalRatingReloadedCallback() { @Override public void onReloadedSuccess(QuizQuestion question) { callback.onReloadedSuccess(question); new ReloadQuestionRating(new IQuestionRatingReloadedCallback() { @Override public void onReloadedSuccess(QuizQuestion question) { callback.onReloadedSuccess(question); } @Override public void onError() { callback.onReloadedError(); } }, question).execute(); } @Override public void onError() { callback.onReloadedError(); } }, question).execute(); } } catch (ClassCastException e) { onError(); } catch (JSONException e) { onError(); } } } @Override public void onError() { callback.onSubmitError(); } }); mQuestion = question; }
diff --git a/src/peergroup/FileHandle.java b/src/peergroup/FileHandle.java index 700b033..e483a7c 100644 --- a/src/peergroup/FileHandle.java +++ b/src/peergroup/FileHandle.java @@ -1,588 +1,587 @@ /* * Peergroup - FileHandle.java * * Peergroup is a P2P Shared Storage System using XMPP for data- and * participantmanagement and Apache Thrift for direct data- * exchange between users. * * Author : Nicolas Inden * Contact: [email protected] * * License: Not for public distribution! */ package peergroup; import java.io.*; import java.util.LinkedList; import java.util.Arrays; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.xml.bind.annotation.adapters.HexBinaryAdapter; /** * A FileHandle includes all information needed to work with * a file. * * @author Nicolas Inden */ public class FileHandle { /** * The Java File object */ private File file; /** * The fileversion is used to maintain the most recent filecontent via lamport clocks */ private int fileVersion; /** * The hash of the file as byte array */ private byte[] hash; /** * The size of the file in bytes */ private long size; /** * A linked list of FileChunk objects which this file consists of */ private LinkedList<FileChunk> chunks; /** * A list of the blocks that changed in the last localUpdate() invocation */ private LinkedList<Integer> updatedBlocks; /** * The size of the filechunks in bytes */ private int chunkSize; /** * This boolean is set true while the file is being updated from network */ private boolean updating; /** * Use this constructor for complete files located on your device */ public FileHandle(String filename) throws Exception{ this.file = new File(filename); this.updating = true; this.fileVersion = 1; this.hash = this.calcHash(this.file); this.size = this.file.length(); this.updatedBlocks = new LinkedList<Integer>(); Constants.log.addMsg("FileHandle: New file from storage: " + this.getPath() + " (Size: " + this.size + ", Hash: " + this.getHexHash() + ")", 3); // Use fixed chunk size for testing this.chunkSize = 512000; /* *if(this.size <= 512000){ // size <= 500kByte -> 100kByte Chunks * this.chunkSize = 102400; *}else if(this.size > 512000 && this.size <= 5120000){ // 500kByte < size <= 5000kByte -> 200kByte Chunks * this.chunkSize = 204800; *}else if(this.size > 5120000 && this.size <= 51200000){ // 5000kByte < size <= 50000kByte -> 1000kByte Chunks * this.chunkSize = 1024000; *}else if(this.size > 51200000){ // 50000kByte < size -> 2000kByte Chunks * this.chunkSize = 2048000; *} */ this.createChunks(this.chunkSize,1); this.updating = false; } /** * Use this constructor for files to be received via network */ public FileHandle(String filename, byte[] fileHash, long fileSize, LinkedList<FileChunk> chunks, int chunkSize) throws Exception{ this.file = new File(Constants.rootDirectory + filename); this.updating = true; this.fileVersion = 1; this.hash = fileHash; this.size = fileSize; this.chunks = chunks; this.chunkSize = chunkSize; this.updatedBlocks = new LinkedList<Integer>(); Constants.log.addMsg("FileHandle: New file from network: " + filename + " (Size: " + this.size + ", Hash: " + this.getHexHash() + ")", 3); this.updating = false; } /** * Creates a linked list of FileChunk for this FileHandle * * @param size the size of a chunk (last one might be smaller) */ private void createChunks(int size, int vers){ if(!(this.chunks == null)){ Constants.log.addMsg("(" + this.file.getName() + ") Chunklist not empty!", 4); return; } Constants.log.addMsg("FileHandle: Creating chunks for " + this.file.getName(), 3); try{ FileInputStream stream = new FileInputStream(this.file); this.chunks = new LinkedList<FileChunk>(); int bytesRead = 0; int id = 0; byte[] buffer = new byte[size]; while((bytesRead = stream.read(buffer)) != -1){ FileChunk next = new FileChunk(id,vers,calcHash(buffer),bytesRead,id*size,true); this.chunks.add(next); id++; } //On empty file, also create one empty chunk if(bytesRead == -1 && id == 0){ FileChunk next = new FileChunk(id,vers,calcHash(buffer),0,id*size,true); this.chunks.add(next); } Constants.log.addMsg("FileHandle: Successfully created chunks for " + this.getPath(),2); }catch(IOException ioe){ Constants.log.addMsg("createChunks: IOException: " + ioe,1); } } /** * General function to calculate the hash of a given file * * @param in the file * @return hash as byte array */ private byte[] calcHash(File in) throws Exception{ FileInputStream stream = new FileInputStream(in); MessageDigest sha = MessageDigest.getInstance("SHA-256"); int bytesRead = 0; byte[] buffer = new byte[1024]; while((bytesRead = stream.read(buffer)) != -1){ sha.update(buffer,0,bytesRead); } return sha.digest(); } /** * General function to calculate the hash of a given byte array * * @param in the byte array * @return hash as byte array */ private byte[] calcHash(byte[] in){ try{ MessageDigest sha = MessageDigest.getInstance("SHA-256"); sha.update(in); return sha.digest(); }catch(NoSuchAlgorithmException na){ Constants.log.addMsg("calcHash Error: " + na,1); System.exit(1); } return null; } /** * This updates all parameters and increments the fileversion, * if a local filechange is detected. * * @return true if file has changed, else false */ public boolean localUpdate() throws Exception{ Constants.log.addMsg("FileHandle: Local update triggered for " + this.file.getName() + ". Scanning for changes!",3); boolean changed = false; FileInputStream stream = new FileInputStream(this.file); int bytesRead = 0; int id = 0; byte[] buffer = new byte[chunkSize]; this.fileVersion += 1; if(!Arrays.equals(this.hash,calcHash(this.file))){ this.hash = calcHash(this.file); changed = true; } this.size = this.file.length(); while((bytesRead = stream.read(buffer)) > 0){ //change is within existent chunks if(id < this.chunks.size()){ // new chunk hash != old chunk hash if(!(Arrays.equals(calcHash(buffer),this.chunks.get(id).getHash()))){ System.out.println(calcHash(buffer) + " " + this.chunks.get(id).getHash()); Constants.log.addMsg("FileHandle: Chunk " + id + " changed! Updating chunklist...",3); FileChunk updated = new FileChunk(id,this.chunks.get(id).getVersion()+1,calcHash(buffer),bytesRead,id*chunkSize,true); this.updatedBlocks.add(new Integer(id)); this.chunks.set(id,updated); changed = true; } // chunk is smaller than others and is not the last chunk -> file got smaller if(bytesRead < chunkSize && id < (this.chunks.size()-1)){ Constants.log.addMsg("FileHandle: Smaller chunk is not last chunk! Pruning following chunks...",3); int i = this.chunks.size()-1; while(i > id){ this.chunks.removeLast(); i--; } changed = true; } // Last chunk got bigger if(bytesRead > this.chunks.get(id).getSize() && id == this.chunks.size()-1){ Constants.log.addMsg("FileHandle: Chunk " + id + " changed! Updating chunklist...",3); FileChunk updated = new FileChunk(id,this.chunks.get(id).getVersion()+1,calcHash(buffer),bytesRead,id*chunkSize,true); this.chunks.set(id,updated); this.updatedBlocks.add(new Integer(id)); changed = true; } }else{ // file is grown and needs more chunks - // TODO: What to do with the Chunk Version here?? Constants.log.addMsg("FileHandle: File needs more chunks than before! Adding new chunks...",3); - FileChunk next = new FileChunk(id,calcHash(buffer),bytesRead,id*chunkSize,true); + FileChunk next = new FileChunk(id,this.fileVersion,calcHash(buffer),bytesRead,id*chunkSize,true); this.chunks.add(next); this.updatedBlocks.add(new Integer(id)); changed = true; } id++; } if(!changed) Constants.log.addMsg("No changes found...",4); return changed; } /** * Insert new hashes and version on changed blocks * * @param blocks The list of blocks that need to be downloaded */ public void updateChunkList(LinkedList<String> blocks, P2Pdevice node){ for(String s : blocks){ updateChunk(s,node); } } public void updateChunk(String chunk, P2Pdevice node){ String[] tmp = chunk.split(":"); int id = (Integer.valueOf(tmp[0])).intValue(); int vers = (Integer.valueOf(tmp[1])).intValue(); String hash = tmp[2]; if(id < this.chunks.size()){ this.chunks.get(id).setHexHash(hash); this.chunks.get(id).setVersion(vers); }else{ this.chunks.add(new FileChunk(id,512000,vers,hash,node)); } } public void addP2PdeviceToBlock(int id, P2Pdevice node){ this.chunks.get(id).addPeer(node); } public void addP2PdeviceToAllBlocks(P2Pdevice node){ for(FileChunk f : this.chunks){ f.addPeer(node); } } public void clearP2Pdevices(){ for(FileChunk f : this.chunks){ f.clearPeers(); } } /** * Creates an empty file to reserve space on local storage */ public void createEmptyLocalFile(){ // Create empty file on disk try{ this.file.createNewFile(); /*RandomAccessFile out = new RandomAccessFile(this.file,"rwd"); out.setLength(this.size); out.close();*/ }catch(IOException ioe){ Constants.log.addMsg("FileHandle: Cannot create new file from network: " + ioe,4); } } /** * Returns the data of the requested file chunk * * @param id the id of the chunk * @return data of the chunk as byte array */ public byte[] getChunkData(int id){ if(this.chunks == null){ Constants.log.addMsg("Cannot return chunkData -> no chunk list available",1); return null; } if(id >= this.chunks.size()){ Constants.log.addMsg("Cannot return chunkData -> ID exceeds list",1); return null; } FileChunk recent = this.chunks.get(id); if(!recent.isComplete()){ Constants.log.addMsg("Cannot return chunkData -> no chunk not complete",1); return null; } try{ FileInputStream stream = new FileInputStream(this.file); long bytesSkipped, bytesRead; byte[] buffer = new byte[(int)recent.getSize()]; bytesSkipped = stream.skip(recent.getOffset()); // Jump to correct part of the file if(bytesSkipped != recent.getOffset()) Constants.log.addMsg("FileHandle: Skipped more or less bytes than offset", 4); bytesRead = stream.read(buffer); if(bytesRead == -1) Constants.log.addMsg("FileHandle: getChunkData EOF - ID: " + id,4); return buffer; }catch(IOException ioe){ Constants.log.addMsg("Error skipping bytes in chunk:" + ioe, 1); return null; } } /** * Writes a chunk of data to the local storage * * @param id The chunk ID * @param data The data as byte array */ public void setChunkData(int id, String hash, P2Pdevice node, byte[] data){ if(this.chunks == null){ Constants.log.addMsg("Cannot set chunkData -> no chunk list available",1); return; } FileChunk recent; if(id >= this.chunks.size()){ recent = new FileChunk(id,512000,this.fileVersion,hash,node); }else{ recent = this.chunks.get(id); } try{ RandomAccessFile stream = new RandomAccessFile(this.file,"rwd"); stream.seek(recent.getOffset()); // Jump to correct part of the file stream.write(data); stream.close(); recent.setHexHash(hash); }catch(IOException ioe){ Constants.log.addMsg("Error writing to file:" + ioe, 1); } } /** * Converts a hash in a byte array into a readable hex string * * @param in the byte array * @return the hex string */ public static String toHexHash(byte[] in){ HexBinaryAdapter adapter = new HexBinaryAdapter(); String hash = adapter.marshal(in); return hash; } /** * Returns the hash of this file as readable hex string * @return the hex string */ public String getHexHash(){ HexBinaryAdapter adapter = new HexBinaryAdapter(); String hash = adapter.marshal(this.hash); return hash; } /** * Returns the SHA256 value for the specified block * * @param no The no of the chunk * @return The hash of the chunk as String */ public String getChunkHash(int no){ return toHexHash(this.chunks.get(no).getHash()); } /** * Returns a list of blocks that have updated with the last call of localUpdate() * * @return A linked list of Integer showing the IDs of updated blocks */ public LinkedList<Integer> getUpdatedBlocks(){ return this.updatedBlocks; } public LinkedList<FileChunk> getChunks(){ return this.chunks; } public void setChunkVersion(int id, int vers){ for(FileChunk f : this.chunks){ if(id == f.getID()){ f.setVersion(vers); return; } } } /** * Clear the list of updated blocks */ public void clearUpdatedBlocks(){ this.updatedBlocks.clear(); } /** * Returns true if filename and hash match * * @param compFH The FileHandle to compare with * @return true if equal, else false */ public boolean equals(FileHandle compFH){ boolean equal = true; if(!this.getPath().equals(compFH.getPath())) equal = false; if(!Arrays.equals(this.hash,compFH.getByteHash())) equal = false; return equal; } /** * Returns a list of strings looking like this: "id:version:hash" * @return the list */ public LinkedList<String> getBlockIDwithHash(){ LinkedList<String> tmp = new LinkedList<String>(); for(FileChunk f : this.chunks){ String newBlock = f.getID() + ":" + f.getVersion() + ":" + f.getHexHash(); System.out.println(newBlock); tmp.add(newBlock); } return tmp; } public void incrVersOnUnchangedBlocks(LinkedList<String> blocks,int vers){ if(blocks.size() == this.chunks.size()){ // Do nothing if all blocks have changed return; } int i = 0; for(FileChunk f : this.chunks){ if(f.getID() != blocks.get(i).charAt(0)-48){ f.setVersion(vers); }else{ if(i < blocks.size()-1) i++; } } } public void trimFile(){ try{ RandomAccessFile thisFile = new RandomAccessFile(this.file,"rws"); thisFile.setLength(this.size); thisFile.close(); double fileSize = (double)this.size; double cSize = (double)this.chunkSize; int blocks = (int)Math.ceil(fileSize/cSize); int diff = this.chunks.size() - blocks; if(diff > 0){ for(int i = 0; i < diff; i++){ this.chunks.removeLast(); } } }catch(FileNotFoundException e){ Constants.log.addMsg("No file to trim, this should not happen!! (" + e + ")",1); }catch(IOException ioe){ Constants.log.addMsg("Error trimming file, this should not happen!! (" + ioe + ")",1); } } /** * Returns a relative path to this file/directory (e.g. /subdir/file.txt) * * @return a path to the file/directory relative to the document root (e.g. /subdir/file.txt) */ public String getPath(){ return this.file.getPath().substring(Constants.rootDirectory.length()); } public LinkedList<FileChunk> getChunkList(){ return this.chunks; } public byte[] getByteHash(){ return this.hash; } public void setByteHash(byte[] newHash){ this.hash = newHash; } public boolean isComplete(){ for(FileChunk f : this.chunks){ if(f.getVersion() != this.getVersion()){ return false; } } return true; } public File getFile(){ return this.file; } public long getSize(){ return this.size; } public int getChunkSize(){ return this.chunkSize; } public void setSize(long newSize){ this.size = newSize; } public int getVersion(){ return this.fileVersion; } public void setVersion(int newVers){ this.fileVersion = newVers; } public void setUpdating(boolean up){ this.updating = up; } public boolean isUpdating(){ return this.updating; } @Override public String toString(){ String out = "\n---------- FileHandle toString ----------\n"; out += "Filename: \t" + this.getPath() + "\n"; out += "Size: \t\t" + this.size + " Byte\n"; out += "Chunks: \t" + this.chunks.size() + " pieces\n"; for(int i = 0; i < this.chunks.size(); i++){ out += "\t" + i + ": \t" + toHexHash(this.chunks.get(i).getHash()) + ", " + this.chunks.get(i).getSize() + " Bytes\n"; } out += "SHA-256: \t" + this.getHexHash() + "\n"; out += "Complete: \t" + this.isComplete() + "\n"; out += "------------ End toString -------------"; return out; } }
false
true
public boolean localUpdate() throws Exception{ Constants.log.addMsg("FileHandle: Local update triggered for " + this.file.getName() + ". Scanning for changes!",3); boolean changed = false; FileInputStream stream = new FileInputStream(this.file); int bytesRead = 0; int id = 0; byte[] buffer = new byte[chunkSize]; this.fileVersion += 1; if(!Arrays.equals(this.hash,calcHash(this.file))){ this.hash = calcHash(this.file); changed = true; } this.size = this.file.length(); while((bytesRead = stream.read(buffer)) > 0){ //change is within existent chunks if(id < this.chunks.size()){ // new chunk hash != old chunk hash if(!(Arrays.equals(calcHash(buffer),this.chunks.get(id).getHash()))){ System.out.println(calcHash(buffer) + " " + this.chunks.get(id).getHash()); Constants.log.addMsg("FileHandle: Chunk " + id + " changed! Updating chunklist...",3); FileChunk updated = new FileChunk(id,this.chunks.get(id).getVersion()+1,calcHash(buffer),bytesRead,id*chunkSize,true); this.updatedBlocks.add(new Integer(id)); this.chunks.set(id,updated); changed = true; } // chunk is smaller than others and is not the last chunk -> file got smaller if(bytesRead < chunkSize && id < (this.chunks.size()-1)){ Constants.log.addMsg("FileHandle: Smaller chunk is not last chunk! Pruning following chunks...",3); int i = this.chunks.size()-1; while(i > id){ this.chunks.removeLast(); i--; } changed = true; } // Last chunk got bigger if(bytesRead > this.chunks.get(id).getSize() && id == this.chunks.size()-1){ Constants.log.addMsg("FileHandle: Chunk " + id + " changed! Updating chunklist...",3); FileChunk updated = new FileChunk(id,this.chunks.get(id).getVersion()+1,calcHash(buffer),bytesRead,id*chunkSize,true); this.chunks.set(id,updated); this.updatedBlocks.add(new Integer(id)); changed = true; } }else{ // file is grown and needs more chunks // TODO: What to do with the Chunk Version here?? Constants.log.addMsg("FileHandle: File needs more chunks than before! Adding new chunks...",3); FileChunk next = new FileChunk(id,calcHash(buffer),bytesRead,id*chunkSize,true); this.chunks.add(next); this.updatedBlocks.add(new Integer(id)); changed = true; } id++; } if(!changed) Constants.log.addMsg("No changes found...",4); return changed; }
public boolean localUpdate() throws Exception{ Constants.log.addMsg("FileHandle: Local update triggered for " + this.file.getName() + ". Scanning for changes!",3); boolean changed = false; FileInputStream stream = new FileInputStream(this.file); int bytesRead = 0; int id = 0; byte[] buffer = new byte[chunkSize]; this.fileVersion += 1; if(!Arrays.equals(this.hash,calcHash(this.file))){ this.hash = calcHash(this.file); changed = true; } this.size = this.file.length(); while((bytesRead = stream.read(buffer)) > 0){ //change is within existent chunks if(id < this.chunks.size()){ // new chunk hash != old chunk hash if(!(Arrays.equals(calcHash(buffer),this.chunks.get(id).getHash()))){ System.out.println(calcHash(buffer) + " " + this.chunks.get(id).getHash()); Constants.log.addMsg("FileHandle: Chunk " + id + " changed! Updating chunklist...",3); FileChunk updated = new FileChunk(id,this.chunks.get(id).getVersion()+1,calcHash(buffer),bytesRead,id*chunkSize,true); this.updatedBlocks.add(new Integer(id)); this.chunks.set(id,updated); changed = true; } // chunk is smaller than others and is not the last chunk -> file got smaller if(bytesRead < chunkSize && id < (this.chunks.size()-1)){ Constants.log.addMsg("FileHandle: Smaller chunk is not last chunk! Pruning following chunks...",3); int i = this.chunks.size()-1; while(i > id){ this.chunks.removeLast(); i--; } changed = true; } // Last chunk got bigger if(bytesRead > this.chunks.get(id).getSize() && id == this.chunks.size()-1){ Constants.log.addMsg("FileHandle: Chunk " + id + " changed! Updating chunklist...",3); FileChunk updated = new FileChunk(id,this.chunks.get(id).getVersion()+1,calcHash(buffer),bytesRead,id*chunkSize,true); this.chunks.set(id,updated); this.updatedBlocks.add(new Integer(id)); changed = true; } }else{ // file is grown and needs more chunks Constants.log.addMsg("FileHandle: File needs more chunks than before! Adding new chunks...",3); FileChunk next = new FileChunk(id,this.fileVersion,calcHash(buffer),bytesRead,id*chunkSize,true); this.chunks.add(next); this.updatedBlocks.add(new Integer(id)); changed = true; } id++; } if(!changed) Constants.log.addMsg("No changes found...",4); return changed; }
diff --git a/src/main/java/com/asascience/ncsos/cdmclasses/CDMUtils.java b/src/main/java/com/asascience/ncsos/cdmclasses/CDMUtils.java index a1684f3..af9d119 100644 --- a/src/main/java/com/asascience/ncsos/cdmclasses/CDMUtils.java +++ b/src/main/java/com/asascience/ncsos/cdmclasses/CDMUtils.java @@ -1,217 +1,217 @@ package com.asascience.ncsos.cdmclasses; import com.asascience.ncsos.getobs.ObservationOffering; import java.util.ArrayList; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Class for common util functions that are used across the CDM classes * @author abird * @version 1.0.0 */ public class CDMUtils { /** * Add the offering to the get caps document * @param offering * @param document * @return */ public static Document addObsOfferingToDoc(ObservationOffering offering,Document document ) { NodeList obsOfferingList = document.getElementsByTagName("ObservationOfferingList"); Element obsOfferEl = (Element) obsOfferingList.item(0); obsOfferEl.appendChild(constructObsOfferingNodes(offering,document)); offering = null; return document; } /** * constructs the node to be added to the document * @param offering * @param document * @return */ public static Element constructObsOfferingNodes(ObservationOffering offering,Document document) { //Create the observation offering Element obsOfferingEl = document.createElement("ObservationOffering"); //add the station ID to the created element obsOfferingEl.setAttribute("gml:id", offering.getObservationStationID()); //create the description and add the offering info Element obsOfferingDescripEl = document.createElement("gml:description"); obsOfferingDescripEl.appendChild(document.createTextNode(offering.getObservationStationDescription())); //create the obs name and add it to the element Element obsOfferingNameEl = document.createElement("gml:name"); obsOfferingNameEl.appendChild(document.createTextNode(offering.getObservationName())); //create the source name el and add data Element obsOfferingSrsNameEl = document.createElement("gml:srsName"); obsOfferingSrsNameEl.appendChild(document.createTextNode(offering.getObservationSrsName())); //create bounded area node Element obsOfferingBoundedByEl = document.createElement("gml:boundedBy"); // create the envelope node and add attribute srs name Element obsOfferingEnvelopeEl = document.createElement("gml:Envelope"); obsOfferingEnvelopeEl.setAttribute("srsName", offering.getObservationSrsName()); //create the lower coner node Element obsOfferinglowerCornerEl = document.createElement("gml:lowerCorner"); obsOfferinglowerCornerEl.appendChild(document.createTextNode(offering.getObservationStationLowerCorner())); //create the upper corner node Element obsOfferingUpperCornerEl = document.createElement("gml:upperCorner"); obsOfferingUpperCornerEl.appendChild(document.createTextNode(offering.getObservationStationUpperCorner())); //add the upper and lower to the envelope node obsOfferingEnvelopeEl.appendChild(obsOfferinglowerCornerEl); obsOfferingEnvelopeEl.appendChild(obsOfferingUpperCornerEl); //add the envelope node to the bounded by node obsOfferingBoundedByEl.appendChild(obsOfferingEnvelopeEl); //create time node Element obsOfferingTimeEl = document.createElement("time"); //create time period node Element obsOfferingTimePeriodEl = document.createElement("gml:TimePeriod"); //create begin position node Element obsOfferingTimeBeginEl = document.createElement("gml:beginPosition"); obsOfferingTimeBeginEl.appendChild(document.createTextNode(offering.getObservationTimeBegin())); //create end position node Element obsOfferingTimeEndEl = document.createElement("gml:endPosition"); checkEndDateElementNode(offering, obsOfferingTimeEndEl,document); //add time begin to time period obsOfferingTimePeriodEl.appendChild(obsOfferingTimeBeginEl); //add time end to time period obsOfferingTimePeriodEl.appendChild(obsOfferingTimeEndEl); //add time period to time obsOfferingTimeEl.appendChild(obsOfferingTimePeriodEl); //create procedure node and add element Element obsOfferingProcedureEl = document.createElement("procedure"); obsOfferingProcedureEl.setAttribute("xlink:href", offering.getObservationProcedureLink()); //create feature of interest node and add element Element obsOfferingFeatureOfInterestEl = document.createElement("featureOfInterest"); obsOfferingFeatureOfInterestEl.setAttribute("xlink:href", offering.getObservationFeatureOfInterest()); //create response format(s) - ArrayList<Element> responseFormats = createResponseFormatNode(document); - if (responseFormats == null) { - System.out.println("Could not find responseFormat in ows:Operation 'GetObservation'"); - } +// ArrayList<Element> responseFormats = createResponseFormatNode(document); +// if (responseFormats == null) { +// System.out.println("Could not find responseFormat in ows:Operation 'GetObservation'"); +// } //create response model Element obsOfferingModelEl = document.createElement("responseModel"); obsOfferingModelEl.appendChild(document.createTextNode(offering.getObservationModel())); //create response model Element obsOfferingModeEl = document.createElement("responseMode"); obsOfferingModeEl.appendChild(document.createTextNode(offering.getObservationResponseMode())); //add the new elements to the XML doc obsOfferingEl.appendChild(obsOfferingDescripEl); obsOfferingEl.appendChild(obsOfferingNameEl); obsOfferingEl.appendChild(obsOfferingSrsNameEl); obsOfferingEl.appendChild(obsOfferingBoundedByEl); obsOfferingEl.appendChild(obsOfferingTimeEl); obsOfferingEl.appendChild(obsOfferingProcedureEl); //create obs property node and add element for (int i = 0; i < offering.getObservationObserveredList().size(); i++) { Element obsOfferingObsPropertyEll = document.createElement("observedProperty"); obsOfferingObsPropertyEll.setAttribute("xlink:href", (String) offering.getObservationObserveredList().get(i)); obsOfferingEl.appendChild(obsOfferingObsPropertyEll); } obsOfferingEl.appendChild(obsOfferingFeatureOfInterestEl); // add our response formats - for (Element elem : responseFormats) { - obsOfferingEl.appendChild(elem); - } +// for (Element elem : responseFormats) { +// obsOfferingEl.appendChild(elem); +// } obsOfferingEl.appendChild(obsOfferingModelEl); obsOfferingEl.appendChild(obsOfferingModeEl); return obsOfferingEl; } /** * Checks the end node for an end date * @param offering * @param obsOfferingTimeEndEl * @param document * @throws DOMException */ private static void checkEndDateElementNode(ObservationOffering offering, Element obsOfferingTimeEndEl,Document document) throws DOMException { //check the string to see if it either needs attribute of element if ((offering.getObservationTimeEnd().isEmpty()) || (offering.getObservationTimeEnd().length() < 2) || (offering.getObservationTimeEnd().contentEquals(""))) { obsOfferingTimeEndEl.setAttribute("indeterminatePosition", "unknown"); } else { obsOfferingTimeEndEl.appendChild(document.createTextNode(offering.getObservationTimeEnd())); } } /** * Creates the response format nodes for each format contained inside the sosGetCapabilities.xml template * @param doc the xml document which holds the get capabilities response * @return node list of each responseFormat node */ private static ArrayList<Element> createResponseFormatNode(Document doc) { ArrayList<Element> retval = null; // get a list of the response formats NodeList nodeList = doc.getElementsByTagName("ows:Operation"); Element getObservation = null; for (int i=0; i<nodeList.getLength(); i++) { if ("GetObservation".equals(nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue())) { getObservation = (Element) nodeList.item(i); break; } } if (getObservation == null) { System.out.println("Could not find GetObservation! node"); return retval; } // now get our "response format" node nodeList = getObservation.getElementsByTagName("ows:Parameter"); Element responseFormat = null; for (int j=0; j<nodeList.getLength(); j++) { if("responseFormat".equals(nodeList.item(j).getAttributes().getNamedItem("name").getNodeValue())) { responseFormat = (Element) nodeList.item(j); break; } } if (responseFormat == null) { System.out.println("Could not find responseFormat node"); return retval; } // now get all of our values nodeList = responseFormat.getElementsByTagName("ows:AllowedValues"); if (nodeList == null) { System.out.println("Could not find ows:AllowedValues"); return retval; } nodeList = ((Element) nodeList.item(0)).getElementsByTagName("ows:Value"); if (nodeList == null) { System.out.println("Could not find ows:Value(s)"); return retval; } // create our array list and populate it with the node list retval = new ArrayList<Element>(nodeList.getLength()); Element respForm = null; for (int k=0; k<nodeList.getLength(); k++) { respForm = doc.createElement("responseFormat"); respForm.setTextContent(((Element) nodeList.item(k)).getTextContent()); retval.add(respForm); } return retval; } }
false
true
public static Element constructObsOfferingNodes(ObservationOffering offering,Document document) { //Create the observation offering Element obsOfferingEl = document.createElement("ObservationOffering"); //add the station ID to the created element obsOfferingEl.setAttribute("gml:id", offering.getObservationStationID()); //create the description and add the offering info Element obsOfferingDescripEl = document.createElement("gml:description"); obsOfferingDescripEl.appendChild(document.createTextNode(offering.getObservationStationDescription())); //create the obs name and add it to the element Element obsOfferingNameEl = document.createElement("gml:name"); obsOfferingNameEl.appendChild(document.createTextNode(offering.getObservationName())); //create the source name el and add data Element obsOfferingSrsNameEl = document.createElement("gml:srsName"); obsOfferingSrsNameEl.appendChild(document.createTextNode(offering.getObservationSrsName())); //create bounded area node Element obsOfferingBoundedByEl = document.createElement("gml:boundedBy"); // create the envelope node and add attribute srs name Element obsOfferingEnvelopeEl = document.createElement("gml:Envelope"); obsOfferingEnvelopeEl.setAttribute("srsName", offering.getObservationSrsName()); //create the lower coner node Element obsOfferinglowerCornerEl = document.createElement("gml:lowerCorner"); obsOfferinglowerCornerEl.appendChild(document.createTextNode(offering.getObservationStationLowerCorner())); //create the upper corner node Element obsOfferingUpperCornerEl = document.createElement("gml:upperCorner"); obsOfferingUpperCornerEl.appendChild(document.createTextNode(offering.getObservationStationUpperCorner())); //add the upper and lower to the envelope node obsOfferingEnvelopeEl.appendChild(obsOfferinglowerCornerEl); obsOfferingEnvelopeEl.appendChild(obsOfferingUpperCornerEl); //add the envelope node to the bounded by node obsOfferingBoundedByEl.appendChild(obsOfferingEnvelopeEl); //create time node Element obsOfferingTimeEl = document.createElement("time"); //create time period node Element obsOfferingTimePeriodEl = document.createElement("gml:TimePeriod"); //create begin position node Element obsOfferingTimeBeginEl = document.createElement("gml:beginPosition"); obsOfferingTimeBeginEl.appendChild(document.createTextNode(offering.getObservationTimeBegin())); //create end position node Element obsOfferingTimeEndEl = document.createElement("gml:endPosition"); checkEndDateElementNode(offering, obsOfferingTimeEndEl,document); //add time begin to time period obsOfferingTimePeriodEl.appendChild(obsOfferingTimeBeginEl); //add time end to time period obsOfferingTimePeriodEl.appendChild(obsOfferingTimeEndEl); //add time period to time obsOfferingTimeEl.appendChild(obsOfferingTimePeriodEl); //create procedure node and add element Element obsOfferingProcedureEl = document.createElement("procedure"); obsOfferingProcedureEl.setAttribute("xlink:href", offering.getObservationProcedureLink()); //create feature of interest node and add element Element obsOfferingFeatureOfInterestEl = document.createElement("featureOfInterest"); obsOfferingFeatureOfInterestEl.setAttribute("xlink:href", offering.getObservationFeatureOfInterest()); //create response format(s) ArrayList<Element> responseFormats = createResponseFormatNode(document); if (responseFormats == null) { System.out.println("Could not find responseFormat in ows:Operation 'GetObservation'"); } //create response model Element obsOfferingModelEl = document.createElement("responseModel"); obsOfferingModelEl.appendChild(document.createTextNode(offering.getObservationModel())); //create response model Element obsOfferingModeEl = document.createElement("responseMode"); obsOfferingModeEl.appendChild(document.createTextNode(offering.getObservationResponseMode())); //add the new elements to the XML doc obsOfferingEl.appendChild(obsOfferingDescripEl); obsOfferingEl.appendChild(obsOfferingNameEl); obsOfferingEl.appendChild(obsOfferingSrsNameEl); obsOfferingEl.appendChild(obsOfferingBoundedByEl); obsOfferingEl.appendChild(obsOfferingTimeEl); obsOfferingEl.appendChild(obsOfferingProcedureEl); //create obs property node and add element for (int i = 0; i < offering.getObservationObserveredList().size(); i++) { Element obsOfferingObsPropertyEll = document.createElement("observedProperty"); obsOfferingObsPropertyEll.setAttribute("xlink:href", (String) offering.getObservationObserveredList().get(i)); obsOfferingEl.appendChild(obsOfferingObsPropertyEll); } obsOfferingEl.appendChild(obsOfferingFeatureOfInterestEl); // add our response formats for (Element elem : responseFormats) { obsOfferingEl.appendChild(elem); } obsOfferingEl.appendChild(obsOfferingModelEl); obsOfferingEl.appendChild(obsOfferingModeEl); return obsOfferingEl; }
public static Element constructObsOfferingNodes(ObservationOffering offering,Document document) { //Create the observation offering Element obsOfferingEl = document.createElement("ObservationOffering"); //add the station ID to the created element obsOfferingEl.setAttribute("gml:id", offering.getObservationStationID()); //create the description and add the offering info Element obsOfferingDescripEl = document.createElement("gml:description"); obsOfferingDescripEl.appendChild(document.createTextNode(offering.getObservationStationDescription())); //create the obs name and add it to the element Element obsOfferingNameEl = document.createElement("gml:name"); obsOfferingNameEl.appendChild(document.createTextNode(offering.getObservationName())); //create the source name el and add data Element obsOfferingSrsNameEl = document.createElement("gml:srsName"); obsOfferingSrsNameEl.appendChild(document.createTextNode(offering.getObservationSrsName())); //create bounded area node Element obsOfferingBoundedByEl = document.createElement("gml:boundedBy"); // create the envelope node and add attribute srs name Element obsOfferingEnvelopeEl = document.createElement("gml:Envelope"); obsOfferingEnvelopeEl.setAttribute("srsName", offering.getObservationSrsName()); //create the lower coner node Element obsOfferinglowerCornerEl = document.createElement("gml:lowerCorner"); obsOfferinglowerCornerEl.appendChild(document.createTextNode(offering.getObservationStationLowerCorner())); //create the upper corner node Element obsOfferingUpperCornerEl = document.createElement("gml:upperCorner"); obsOfferingUpperCornerEl.appendChild(document.createTextNode(offering.getObservationStationUpperCorner())); //add the upper and lower to the envelope node obsOfferingEnvelopeEl.appendChild(obsOfferinglowerCornerEl); obsOfferingEnvelopeEl.appendChild(obsOfferingUpperCornerEl); //add the envelope node to the bounded by node obsOfferingBoundedByEl.appendChild(obsOfferingEnvelopeEl); //create time node Element obsOfferingTimeEl = document.createElement("time"); //create time period node Element obsOfferingTimePeriodEl = document.createElement("gml:TimePeriod"); //create begin position node Element obsOfferingTimeBeginEl = document.createElement("gml:beginPosition"); obsOfferingTimeBeginEl.appendChild(document.createTextNode(offering.getObservationTimeBegin())); //create end position node Element obsOfferingTimeEndEl = document.createElement("gml:endPosition"); checkEndDateElementNode(offering, obsOfferingTimeEndEl,document); //add time begin to time period obsOfferingTimePeriodEl.appendChild(obsOfferingTimeBeginEl); //add time end to time period obsOfferingTimePeriodEl.appendChild(obsOfferingTimeEndEl); //add time period to time obsOfferingTimeEl.appendChild(obsOfferingTimePeriodEl); //create procedure node and add element Element obsOfferingProcedureEl = document.createElement("procedure"); obsOfferingProcedureEl.setAttribute("xlink:href", offering.getObservationProcedureLink()); //create feature of interest node and add element Element obsOfferingFeatureOfInterestEl = document.createElement("featureOfInterest"); obsOfferingFeatureOfInterestEl.setAttribute("xlink:href", offering.getObservationFeatureOfInterest()); //create response format(s) // ArrayList<Element> responseFormats = createResponseFormatNode(document); // if (responseFormats == null) { // System.out.println("Could not find responseFormat in ows:Operation 'GetObservation'"); // } //create response model Element obsOfferingModelEl = document.createElement("responseModel"); obsOfferingModelEl.appendChild(document.createTextNode(offering.getObservationModel())); //create response model Element obsOfferingModeEl = document.createElement("responseMode"); obsOfferingModeEl.appendChild(document.createTextNode(offering.getObservationResponseMode())); //add the new elements to the XML doc obsOfferingEl.appendChild(obsOfferingDescripEl); obsOfferingEl.appendChild(obsOfferingNameEl); obsOfferingEl.appendChild(obsOfferingSrsNameEl); obsOfferingEl.appendChild(obsOfferingBoundedByEl); obsOfferingEl.appendChild(obsOfferingTimeEl); obsOfferingEl.appendChild(obsOfferingProcedureEl); //create obs property node and add element for (int i = 0; i < offering.getObservationObserveredList().size(); i++) { Element obsOfferingObsPropertyEll = document.createElement("observedProperty"); obsOfferingObsPropertyEll.setAttribute("xlink:href", (String) offering.getObservationObserveredList().get(i)); obsOfferingEl.appendChild(obsOfferingObsPropertyEll); } obsOfferingEl.appendChild(obsOfferingFeatureOfInterestEl); // add our response formats // for (Element elem : responseFormats) { // obsOfferingEl.appendChild(elem); // } obsOfferingEl.appendChild(obsOfferingModelEl); obsOfferingEl.appendChild(obsOfferingModeEl); return obsOfferingEl; }
diff --git a/telephony/java/com/android/internal/telephony/PhoneBase.java b/telephony/java/com/android/internal/telephony/PhoneBase.java index 20c54fb9..1ff0f7e9 100644 --- a/telephony/java/com/android/internal/telephony/PhoneBase.java +++ b/telephony/java/com/android/internal/telephony/PhoneBase.java @@ -1,638 +1,633 @@ /* * 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.internal.telephony; import android.app.ActivityManagerNative; import android.app.IActivityManager; import android.content.Context; import android.content.res.Configuration; import android.content.SharedPreferences; import android.os.AsyncResult; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.RegistrantList; import android.os.SystemProperties; import android.preference.PreferenceManager; import android.telephony.ServiceState; import android.text.TextUtils; import android.util.Log; import com.android.internal.R; import com.android.internal.telephony.gsm.PdpConnection; import com.android.internal.telephony.test.SimulatedRadioControl; import java.util.List; import java.util.Locale; /** * (<em>Not for SDK use</em>) * A base implementation for the com.android.internal.telephony.Phone interface. * * Note that implementations of Phone.java are expected to be used * from a single application thread. This should be the same thread that * originally called PhoneFactory to obtain the interface. * * {@hide} * */ public abstract class PhoneBase implements Phone { private static final String LOG_TAG = "PHONE"; private static final boolean LOCAL_DEBUG = true; // Key used to read and write the saved network selection value public static final String NETWORK_SELECTION_KEY = "network_selection_key"; // Key used to read/write "disable data connection on boot" pref (used for testing) public static final String DATA_DISABLED_ON_BOOT_KEY = "disabled_on_boot_key"; //***** Event Constants protected static final int EVENT_RADIO_AVAILABLE = 1; /** Supplementary Service Notification received. */ protected static final int EVENT_SSN = 2; protected static final int EVENT_SIM_RECORDS_LOADED = 3; protected static final int EVENT_MMI_DONE = 4; protected static final int EVENT_RADIO_ON = 5; protected static final int EVENT_GET_BASEBAND_VERSION_DONE = 6; protected static final int EVENT_USSD = 7; protected static final int EVENT_RADIO_OFF_OR_NOT_AVAILABLE = 8; protected static final int EVENT_GET_IMEI_DONE = 9; protected static final int EVENT_GET_IMEISV_DONE = 10; protected static final int EVENT_GET_SIM_STATUS_DONE = 11; protected static final int EVENT_SET_CALL_FORWARD_DONE = 12; protected static final int EVENT_GET_CALL_FORWARD_DONE = 13; protected static final int EVENT_CALL_RING = 14; // Used to intercept the carrier selection calls so that // we can save the values. protected static final int EVENT_SET_NETWORK_MANUAL_COMPLETE = 15; protected static final int EVENT_SET_NETWORK_AUTOMATIC_COMPLETE = 16; protected static final int EVENT_SET_CLIR_COMPLETE = 17; protected static final int EVENT_REGISTERED_TO_NETWORK = 18; protected static final int EVENT_SET_VM_NUMBER_DONE = 19; // Events for CDMA support protected static final int EVENT_GET_DEVICE_IDENTITY_DONE = 20; protected static final int EVENT_RUIM_RECORDS_LOADED = 21; protected static final int EVENT_NV_READY = 22; protected static final int EVENT_SET_ENHANCED_VP = 23; // Key used to read/write current CLIR setting public static final String CLIR_KEY = "clir_key"; // Key used to read/write "disable DNS server check" pref (used for testing) public static final String DNS_SERVER_CHECK_DISABLED_KEY = "dns_server_check_disabled_key"; //***** Instance Variables public CommandsInterface mCM; protected IccFileHandler mIccFileHandler; boolean mDnsCheckDisabled = false; /** * Set a system property, unless we're in unit test mode */ public void setSystemProperty(String property, String value) { if(getUnitTestMode()) { return; } SystemProperties.set(property, value); } protected final RegistrantList mPhoneStateRegistrants = new RegistrantList(); protected final RegistrantList mNewRingingConnectionRegistrants = new RegistrantList(); protected final RegistrantList mIncomingRingRegistrants = new RegistrantList(); protected final RegistrantList mDisconnectRegistrants = new RegistrantList(); protected final RegistrantList mServiceStateRegistrants = new RegistrantList(); protected final RegistrantList mMmiCompleteRegistrants = new RegistrantList(); protected final RegistrantList mMmiRegistrants = new RegistrantList(); protected final RegistrantList mUnknownConnectionRegistrants = new RegistrantList(); protected final RegistrantList mSuppServiceFailedRegistrants = new RegistrantList(); protected Looper mLooper; /* to insure registrants are in correct thread*/ protected Context mContext; /** * PhoneNotifier is an abstraction for all system-wide * state change notification. DefaultPhoneNotifier is * used here unless running we're inside a unit test. */ protected PhoneNotifier mNotifier; protected SimulatedRadioControl mSimulatedRadioControl; boolean mUnitTestMode; /** * Constructs a PhoneBase in normal (non-unit test) mode. * * @param context Context object from hosting application * @param notifier An instance of DefaultPhoneNotifier, * unless unit testing. */ protected PhoneBase(PhoneNotifier notifier, Context context) { this(notifier, context, false); } /** * Constructs a PhoneBase in normal (non-unit test) mode. * * @param context Context object from hosting application * @param notifier An instance of DefaultPhoneNotifier, * unless unit testing. * @param unitTestMode when true, prevents notifications * of state change events */ protected PhoneBase(PhoneNotifier notifier, Context context, boolean unitTestMode) { this.mNotifier = notifier; this.mContext = context; mLooper = Looper.myLooper(); setLocaleByCarrier(); setUnitTestMode(unitTestMode); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); mDnsCheckDisabled = sp.getBoolean(DNS_SERVER_CHECK_DISABLED_KEY, false); } // Inherited documentation suffices. public Context getContext() { return mContext; } /** * Disables the DNS check (i.e., allows "0.0.0.0"). * Useful for lab testing environment. * @param b true disables the check, false enables. */ public void disableDnsCheck(boolean b) { mDnsCheckDisabled = b; SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext()); SharedPreferences.Editor editor = sp.edit(); editor.putBoolean(DNS_SERVER_CHECK_DISABLED_KEY, b); editor.commit(); } /** * Returns true if the DNS check is currently disabled. */ public boolean isDnsCheckDisabled() { return mDnsCheckDisabled; } // Inherited documentation suffices. public void registerForPhoneStateChanged(Handler h, int what, Object obj) { checkCorrectThread(h); mPhoneStateRegistrants.addUnique(h, what, obj); } // Inherited documentation suffices. public void unregisterForPhoneStateChanged(Handler h) { mPhoneStateRegistrants.remove(h); } /** * Notify registrants of a PhoneStateChanged. * Subclasses of Phone probably want to replace this with a * version scoped to their packages */ protected void notifyCallStateChangedP() { AsyncResult ar = new AsyncResult(null, this, null); mPhoneStateRegistrants.notifyRegistrants(ar); } // Inherited documentation suffices. public void registerForUnknownConnection(Handler h, int what, Object obj) { checkCorrectThread(h); mUnknownConnectionRegistrants.addUnique(h, what, obj); } // Inherited documentation suffices. public void unregisterForUnknownConnection(Handler h) { mUnknownConnectionRegistrants.remove(h); } // Inherited documentation suffices. public void registerForNewRingingConnection( Handler h, int what, Object obj) { checkCorrectThread(h); mNewRingingConnectionRegistrants.addUnique(h, what, obj); } // Inherited documentation suffices. public void unregisterForNewRingingConnection(Handler h) { mNewRingingConnectionRegistrants.remove(h); } // Inherited documentation suffices. public void registerForInCallVoicePrivacyOn(Handler h, int what, Object obj){ mCM.registerForInCallVoicePrivacyOn(h,what,obj); } // Inherited documentation suffices. public void unregisterForInCallVoicePrivacyOn(Handler h){ mCM.unregisterForInCallVoicePrivacyOn(h); } // Inherited documentation suffices. public void registerForInCallVoicePrivacyOff(Handler h, int what, Object obj){ mCM.registerForInCallVoicePrivacyOff(h,what,obj); } // Inherited documentation suffices. public void unregisterForInCallVoicePrivacyOff(Handler h){ mCM.unregisterForInCallVoicePrivacyOff(h); } /** * Notifiy registrants of a new ringing Connection. * Subclasses of Phone probably want to replace this with a * version scoped to their packages */ protected void notifyNewRingingConnectionP(Connection cn) { AsyncResult ar = new AsyncResult(null, cn, null); mNewRingingConnectionRegistrants.notifyRegistrants(ar); } // Inherited documentation suffices. public void registerForIncomingRing( Handler h, int what, Object obj) { checkCorrectThread(h); mIncomingRingRegistrants.addUnique(h, what, obj); } // Inherited documentation suffices. public void unregisterForIncomingRing(Handler h) { mIncomingRingRegistrants.remove(h); } // Inherited documentation suffices. public void registerForDisconnect(Handler h, int what, Object obj) { checkCorrectThread(h); mDisconnectRegistrants.addUnique(h, what, obj); } // Inherited documentation suffices. public void unregisterForDisconnect(Handler h) { mDisconnectRegistrants.remove(h); } // Inherited documentation suffices. public void registerForSuppServiceFailed(Handler h, int what, Object obj) { checkCorrectThread(h); mSuppServiceFailedRegistrants.addUnique(h, what, obj); } // Inherited documentation suffices. public void unregisterForSuppServiceFailed(Handler h) { mSuppServiceFailedRegistrants.remove(h); } // Inherited documentation suffices. public void registerForMmiInitiate(Handler h, int what, Object obj) { checkCorrectThread(h); mMmiRegistrants.addUnique(h, what, obj); } // Inherited documentation suffices. public void unregisterForMmiInitiate(Handler h) { mMmiRegistrants.remove(h); } // Inherited documentation suffices. public void registerForMmiComplete(Handler h, int what, Object obj) { checkCorrectThread(h); mMmiCompleteRegistrants.addUnique(h, what, obj); } // Inherited documentation suffices. public void unregisterForMmiComplete(Handler h) { checkCorrectThread(h); mMmiCompleteRegistrants.remove(h); } /** * Method to retrieve the saved operator id from the Shared Preferences */ private String getSavedNetworkSelection() { // open the shared preferences and search with our key. SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext()); return sp.getString(NETWORK_SELECTION_KEY, ""); } /** * Method to restore the previously saved operator id, or reset to * automatic selection, all depending upon the value in the shared * preferences. */ public void restoreSavedNetworkSelection(Message response) { // retrieve the operator id String networkSelection = getSavedNetworkSelection(); // set to auto if the id is empty, otherwise select the network. if (TextUtils.isEmpty(networkSelection)) { mCM.setNetworkSelectionModeAutomatic(response); } else { mCM.setNetworkSelectionModeManual(networkSelection, response); } } // Inherited documentation suffices. public void setUnitTestMode(boolean f) { mUnitTestMode = f; } // Inherited documentation suffices. public boolean getUnitTestMode() { return mUnitTestMode; } /** * To be invoked when a voice call Connection disconnects. * * Subclasses of Phone probably want to replace this with a * version scoped to their packages */ protected void notifyDisconnectP(Connection cn) { AsyncResult ar = new AsyncResult(null, cn, null); mDisconnectRegistrants.notifyRegistrants(ar); } // Inherited documentation suffices. public void registerForServiceStateChanged( Handler h, int what, Object obj) { checkCorrectThread(h); mServiceStateRegistrants.add(h, what, obj); } // Inherited documentation suffices. public void unregisterForServiceStateChanged(Handler h) { mServiceStateRegistrants.remove(h); } /** * Subclasses of Phone probably want to replace this with a * version scoped to their packages */ protected void notifyServiceStateChangedP(ServiceState ss) { AsyncResult ar = new AsyncResult(null, ss, null); mServiceStateRegistrants.notifyRegistrants(ar); mNotifier.notifyServiceState(this); } // Inherited documentation suffices. public SimulatedRadioControl getSimulatedRadioControl() { return mSimulatedRadioControl; } /** * Verifies the current thread is the same as the thread originally * used in the initialization of this instance. Throws RuntimeException * if not. * * @exception RuntimeException if the current thread is not * the thread that originally obtained this PhoneBase instance. */ private void checkCorrectThread(Handler h) { if (h.getLooper() != mLooper) { throw new RuntimeException( "com.android.internal.telephony.Phone must be used from within one thread"); } } /** * Set the locale by matching the carrier string in * a string-array resource */ private void setLocaleByCarrier() { String carrier = SystemProperties.get("ro.carrier"); if (null == carrier || 0 == carrier.length()) { return; } CharSequence[] carrierLocales = mContext. getResources().getTextArray(R.array.carrier_locales); for (int i = 0; i < carrierLocales.length-1; i+=2) { String c = carrierLocales[i].toString(); String l = carrierLocales[i+1].toString(); if (carrier.equals(c)) { String language = l.substring(0, 2); String country = ""; if (l.length() >=5) { country = l.substring(3, 5); } setSystemLocale(language, country); return; } } } /** * Utility code to set the system locale if it's not set already * @param langauge Two character language code desired * @param country Two character country code desired * * {@hide} */ public void setSystemLocale(String language, String country) { String l = SystemProperties.get("persist.sys.language"); String c = SystemProperties.get("persist.sys.country"); if (null == language) { return; // no match possible } - language.toLowerCase(); + language = language.toLowerCase(); if (null == country) { country = ""; } country = country.toUpperCase(); if((null == l || 0 == l.length()) && (null == c || 0 == c.length())) { try { // try to find a good match String[] locales = mContext.getAssets().getLocales(); final int N = locales.length; String bestMatch = null; for(int i = 0; i < N; i++) { - if (locales[i]!=null && locales[i].length() >= 2 && + // only match full (lang + country) locales + if (locales[i]!=null && locales[i].length() >= 5 && locales[i].substring(0,2).equals(language)) { - if (locales[i].length() >= 5) { - if (locales[i].substring(3,5).equals(country)) { - bestMatch = locales[i]; - break; - } + if (locales[i].substring(3,5).equals(country)) { + bestMatch = locales[i]; + break; } else if (null == bestMatch) { bestMatch = locales[i]; } } } if (null != bestMatch) { IActivityManager am = ActivityManagerNative.getDefault(); Configuration config = am.getConfiguration(); - if (bestMatch.length() >= 5) { - config.locale = new Locale(bestMatch.substring(0,2), - bestMatch.substring(3,5)); - } else { - config.locale = new Locale(bestMatch.substring(0,2)); - } + config.locale = new Locale(bestMatch.substring(0,2), + bestMatch.substring(3,5)); config.userSetLocale = true; am.updateConfiguration(config); } } catch (Exception e) { // Intentionally left blank } } } /* * Retrieves the Handler of the Phone instance */ public abstract Handler getHandler(); /** * Retrieves the IccFileHandler of the Phone instance */ public abstract IccFileHandler getIccFileHandler(); /** * Query the status of the CDMA roaming preference */ public void queryCdmaRoamingPreference(Message response) { mCM.queryCdmaRoamingPreference(response); } /** * Set the status of the CDMA roaming preference */ public void setCdmaRoamingPreference(int cdmaRoamingType, Message response) { mCM.setCdmaRoamingPreference(cdmaRoamingType, response); } /** * Set the status of the CDMA subscription mode */ public void setCdmaSubscription(int cdmaSubscriptionType, Message response) { mCM.setCdmaSubscription(cdmaSubscriptionType, response); } /** * Set the preferred Network Type: Global, CDMA only or GSM/UMTS only */ public void setPreferredNetworkType(int networkType, Message response) { mCM.setPreferredNetworkType(networkType, response); } /** * Set the status of the preferred Network Type: Global, CDMA only or GSM/UMTS only */ public void getPreferredNetworkType(Message response) { mCM.getPreferredNetworkType(response); } public void setTTYModeEnabled(boolean enable, Message onComplete) { // This function should be overridden by the class CDMAPhone. Not implemented in GSMPhone. Log.e(LOG_TAG, "Error! This function should never be executed, inactive CDMAPhone."); } public void queryTTYModeEnabled(Message onComplete) { // This function should be overridden by the class CDMAPhone. Not implemented in GSMPhone. Log.e(LOG_TAG, "Error! This function should never be executed, inactive CDMAPhone."); } /** * This should only be called in GSM mode. * Only here for some backward compatibility * issues concerning the GSMPhone class. * @deprecated */ public List<PdpConnection> getCurrentPdpList() { return null; } public void enableEnhancedVoicePrivacy(boolean enable, Message onComplete) { // This function should be overridden by the class CDMAPhone. Not implemented in GSMPhone. Log.e(LOG_TAG, "Error! This function should never be executed, inactive CDMAPhone."); } public void getEnhancedVoicePrivacy(Message onComplete) { // This function should be overridden by the class CDMAPhone. Not implemented in GSMPhone. Log.e(LOG_TAG, "Error! This function should never be executed, inactive CDMAPhone."); } public void setBandMode(int bandMode, Message response) { mCM.setBandMode(bandMode, response); } public void queryAvailableBandMode(Message response) { mCM.queryAvailableBandMode(response); } public void invokeOemRilRequestRaw(byte[] data, Message response) { mCM.invokeOemRilRequestRaw(data, response); } public void invokeOemRilRequestStrings(String[] strings, Message response) { mCM.invokeOemRilRequestStrings(strings, response); } public void notifyDataActivity() { mNotifier.notifyDataActivity(this); } public void notifyDataConnection(String reason) { mNotifier.notifyDataConnection(this, reason); } public abstract String getPhoneName(); }
false
true
public void setSystemLocale(String language, String country) { String l = SystemProperties.get("persist.sys.language"); String c = SystemProperties.get("persist.sys.country"); if (null == language) { return; // no match possible } language.toLowerCase(); if (null == country) { country = ""; } country = country.toUpperCase(); if((null == l || 0 == l.length()) && (null == c || 0 == c.length())) { try { // try to find a good match String[] locales = mContext.getAssets().getLocales(); final int N = locales.length; String bestMatch = null; for(int i = 0; i < N; i++) { if (locales[i]!=null && locales[i].length() >= 2 && locales[i].substring(0,2).equals(language)) { if (locales[i].length() >= 5) { if (locales[i].substring(3,5).equals(country)) { bestMatch = locales[i]; break; } } else if (null == bestMatch) { bestMatch = locales[i]; } } } if (null != bestMatch) { IActivityManager am = ActivityManagerNative.getDefault(); Configuration config = am.getConfiguration(); if (bestMatch.length() >= 5) { config.locale = new Locale(bestMatch.substring(0,2), bestMatch.substring(3,5)); } else { config.locale = new Locale(bestMatch.substring(0,2)); } config.userSetLocale = true; am.updateConfiguration(config); } } catch (Exception e) { // Intentionally left blank } } }
public void setSystemLocale(String language, String country) { String l = SystemProperties.get("persist.sys.language"); String c = SystemProperties.get("persist.sys.country"); if (null == language) { return; // no match possible } language = language.toLowerCase(); if (null == country) { country = ""; } country = country.toUpperCase(); if((null == l || 0 == l.length()) && (null == c || 0 == c.length())) { try { // try to find a good match String[] locales = mContext.getAssets().getLocales(); final int N = locales.length; String bestMatch = null; for(int i = 0; i < N; i++) { // only match full (lang + country) locales if (locales[i]!=null && locales[i].length() >= 5 && locales[i].substring(0,2).equals(language)) { if (locales[i].substring(3,5).equals(country)) { bestMatch = locales[i]; break; } else if (null == bestMatch) { bestMatch = locales[i]; } } } if (null != bestMatch) { IActivityManager am = ActivityManagerNative.getDefault(); Configuration config = am.getConfiguration(); config.locale = new Locale(bestMatch.substring(0,2), bestMatch.substring(3,5)); config.userSetLocale = true; am.updateConfiguration(config); } } catch (Exception e) { // Intentionally left blank } } }
diff --git a/src/com/android/launcher2/AllAppsView.java b/src/com/android/launcher2/AllAppsView.java index 9e222319..0c45075c 100644 --- a/src/com/android/launcher2/AllAppsView.java +++ b/src/com/android/launcher2/AllAppsView.java @@ -1,1444 +1,1444 @@ /* * Copyright (C) 2008 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.launcher2; import android.content.ComponentName; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.Rect; import android.os.SystemClock; import android.renderscript.Allocation; import android.renderscript.Dimension; import android.renderscript.Element; import android.renderscript.ProgramFragment; import android.renderscript.ProgramStore; import android.renderscript.ProgramVertex; import android.renderscript.RSSurfaceView; import android.renderscript.RenderScript; import android.renderscript.Sampler; import android.renderscript.Script; import android.renderscript.ScriptC; import android.renderscript.SimpleMesh; import android.renderscript.Type; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.SurfaceHolder; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.accessibility.AccessibilityEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; public class AllAppsView extends RSSurfaceView implements View.OnClickListener, View.OnLongClickListener, DragSource { private static final String TAG = "Launcher.AllAppsView"; /** Bit for mLocks for when there are icons being loaded. */ private static final int LOCK_ICONS_PENDING = 1; private static final int TRACKING_NONE = 0; private static final int TRACKING_FLING = 1; private static final int TRACKING_HOME = 2; private static final int SELECTED_NONE = 0; private static final int SELECTED_FOCUSED = 1; private static final int SELECTED_PRESSED = 2; private static final int SELECTION_NONE = 0; private static final int SELECTION_ICONS = 1; private static final int SELECTION_HOME = 2; private Launcher mLauncher; private DragController mDragController; /** When this is 0, modifications are allowed, when it's not, they're not. * TODO: What about scrolling? */ private int mLocks = LOCK_ICONS_PENDING; private int mSlop; private int mMaxFlingVelocity; private Defines mDefines = new Defines(); private RenderScript mRS; private RolloRS mRollo; private ArrayList<ApplicationInfo> mAllAppsList; /** * True when we are using arrow keys or trackball to drive navigation */ private boolean mArrowNavigation = false; private boolean mStartedScrolling; /** * Used to keep track of the selection when AllAppsView loses window focus. * One of the SELECTION_ constants. */ private int mLastSelection; /** * Used to keep track of the selection when AllAppsView loses window focus */ private int mLastSelectedIcon; private VelocityTracker mVelocityTracker; private int mTouchTracking; private int mMotionDownRawX; private int mMotionDownRawY; private int mDownIconIndex = -1; private int mCurrentIconIndex = -1; private boolean mShouldGainFocus; private boolean mZoomDirty = false; private boolean mAnimateNextZoom; private float mZoom; private float mPosX; private float mVelocity; private AAMessage mMessageProc; static class Defines { public static final int ALLOC_PARAMS = 0; public static final int ALLOC_STATE = 1; public static final int ALLOC_ICON_IDS = 3; public static final int ALLOC_LABEL_IDS = 4; public static final int COLUMNS_PER_PAGE = 4; public static final int ROWS_PER_PAGE = 4; public static final int ICON_WIDTH_PX = 64; public static final int ICON_TEXTURE_WIDTH_PX = 128; public static final int ICON_HEIGHT_PX = 64; public static final int ICON_TEXTURE_HEIGHT_PX = 128; public int SCREEN_WIDTH_PX; public int SCREEN_HEIGHT_PX; public void recompute(int w, int h) { SCREEN_WIDTH_PX = 480; SCREEN_HEIGHT_PX = 800; } } public AllAppsView(Context context, AttributeSet attrs) { super(context, attrs); setFocusable(true); setSoundEffectsEnabled(false); getHolder().setFormat(PixelFormat.TRANSLUCENT); final ViewConfiguration config = ViewConfiguration.get(context); mSlop = config.getScaledTouchSlop(); mMaxFlingVelocity = config.getScaledMaximumFlingVelocity(); setOnClickListener(this); setOnLongClickListener(this); setZOrderOnTop(true); getHolder().setFormat(PixelFormat.TRANSLUCENT); mRS = createRenderScript(true); } @Override protected void onDetachedFromWindow() { destroyRenderScript(); } /** * If you have an attached click listener, View always plays the click sound!?!? * Deal with sound effects by hand. */ public void reallyPlaySoundEffect(int sound) { boolean old = isSoundEffectsEnabled(); setSoundEffectsEnabled(true); playSoundEffect(sound); setSoundEffectsEnabled(old); } public AllAppsView(Context context, AttributeSet attrs, int defStyle) { this(context, attrs); } public void setLauncher(Launcher launcher) { mLauncher = launcher; } @Override public void surfaceDestroyed(SurfaceHolder holder) { super.surfaceDestroyed(holder); mRollo.mHasSurface = false; // Without this, we leak mMessageCallback which leaks the context. mRS.mMessageCallback = null; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { //long startTime = SystemClock.uptimeMillis(); super.surfaceChanged(holder, format, w, h); if (mRollo == null) { mRollo = new RolloRS(); mRollo.mHasSurface = true; mRollo.init(getResources(), w, h); if (mAllAppsList != null) { mRollo.setApps(mAllAppsList); } if (mShouldGainFocus) { gainFocus(); mShouldGainFocus = false; } } else { mRollo.mHasSurface = true; } mRollo.dirtyCheck(); mRollo.resize(w, h); mRS.mMessageCallback = mMessageProc = new AAMessage(); Resources res = getContext().getResources(); int barHeight = (int)res.getDimension(R.dimen.button_bar_height); //long endTime = SystemClock.uptimeMillis(); //Log.d(TAG, "surfaceChanged took " + (endTime-startTime) + "ms"); } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); if (mArrowNavigation) { if (!hasWindowFocus) { // Clear selection when we lose window focus mLastSelectedIcon = mRollo.mState.selectedIconIndex; mRollo.setHomeSelected(SELECTED_NONE); mRollo.clearSelectedIcon(); mRollo.mState.save(); } else if (hasWindowFocus) { if (mRollo.mState.iconCount > 0) { if (mLastSelection == SELECTION_ICONS) { int selection = mLastSelectedIcon; final int firstIcon = Math.round(mPosX) * Defines.COLUMNS_PER_PAGE; if (selection < 0 || // No selection selection < firstIcon || // off the top of the screen selection >= mRollo.mState.iconCount || // past last icon selection >= firstIcon + // past last icon on screen (Defines.COLUMNS_PER_PAGE * Defines.ROWS_PER_PAGE)) { selection = firstIcon; } // Select the first icon when we gain window focus mRollo.selectIcon(selection, SELECTED_FOCUSED); mRollo.mState.save(); } else if (mLastSelection == SELECTION_HOME) { mRollo.setHomeSelected(SELECTED_FOCUSED); mRollo.mState.save(); } } } } } @Override protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); if (!isVisible()) { return; } if (gainFocus) { if (mRollo != null && mRollo.mHasSurface) { gainFocus(); } else { mShouldGainFocus = true; } } else { if (mRollo != null && mRollo.mHasSurface) { if (mArrowNavigation) { // Clear selection when we lose focus mRollo.clearSelectedIcon(); mRollo.setHomeSelected(SELECTED_NONE); mRollo.mState.save(); mArrowNavigation = false; } } else { mShouldGainFocus = false; } } } private void gainFocus() { if (!mArrowNavigation && mRollo.mState.iconCount > 0) { // Select the first icon when we gain keyboard focus mArrowNavigation = true; mRollo.selectIcon(Math.round(mPosX) * Defines.COLUMNS_PER_PAGE, SELECTED_FOCUSED); mRollo.mState.save(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { boolean handled = false; if (!isVisible()) { return false; } final int iconCount = mRollo.mState.iconCount; if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) { if (mArrowNavigation) { if (mLastSelection == SELECTION_HOME) { reallyPlaySoundEffect(SoundEffectConstants.CLICK); mLauncher.closeAllApps(true); } else { int whichApp = mRollo.mState.selectedIconIndex; if (whichApp >= 0) { ApplicationInfo app = mAllAppsList.get(whichApp); mLauncher.startActivitySafely(app.intent); handled = true; } } } } if (iconCount > 0) { mArrowNavigation = true; int currentSelection = mRollo.mState.selectedIconIndex; int currentTopRow = Math.round(mPosX); // The column of the current selection, in the range 0..COLUMNS_PER_PAGE-1 final int currentPageCol = currentSelection % Defines.COLUMNS_PER_PAGE; // The row of the current selection, in the range 0..ROWS_PER_PAGE-1 final int currentPageRow = (currentSelection - (currentTopRow*Defines.COLUMNS_PER_PAGE)) / Defines.ROWS_PER_PAGE; int newSelection = currentSelection; switch (keyCode) { case KeyEvent.KEYCODE_DPAD_UP: if (mLastSelection == SELECTION_HOME) { mRollo.setHomeSelected(SELECTED_NONE); int lastRowCount = iconCount % Defines.COLUMNS_PER_PAGE; if (lastRowCount == 0) { lastRowCount = Defines.COLUMNS_PER_PAGE; } newSelection = iconCount - lastRowCount + (Defines.COLUMNS_PER_PAGE / 2); if (newSelection >= iconCount) { newSelection = iconCount-1; } int target = (newSelection / Defines.COLUMNS_PER_PAGE) - (Defines.ROWS_PER_PAGE - 1); if (target < 0) { target = 0; } if (currentTopRow != target) { mRollo.moveTo(target); } } else { if (currentPageRow > 0) { newSelection = currentSelection - Defines.COLUMNS_PER_PAGE; } else if (currentTopRow > 0) { newSelection = currentSelection - Defines.COLUMNS_PER_PAGE; mRollo.moveTo(newSelection / Defines.COLUMNS_PER_PAGE); - } else { - newSelection = Defines.COLUMNS_PER_PAGE * (Defines.ROWS_PER_PAGE-1); + } else if (currentPageRow != 0) { + newSelection = currentTopRow * Defines.ROWS_PER_PAGE; } } handled = true; break; case KeyEvent.KEYCODE_DPAD_DOWN: { final int rowCount = iconCount / Defines.COLUMNS_PER_PAGE + (iconCount % Defines.COLUMNS_PER_PAGE == 0 ? 0 : 1); final int currentRow = currentSelection / Defines.COLUMNS_PER_PAGE; if (mLastSelection != SELECTION_HOME) { if (currentRow < rowCount-1) { mRollo.setHomeSelected(SELECTED_NONE); if (currentSelection < 0) { newSelection = 0; } else { newSelection = currentSelection + Defines.COLUMNS_PER_PAGE; } if (newSelection >= iconCount) { // Go from D to G in this arrangement: // A B C D // E F G newSelection = iconCount - 1; } if (currentPageRow >= Defines.ROWS_PER_PAGE - 1) { mRollo.moveTo((newSelection / Defines.COLUMNS_PER_PAGE) - Defines.ROWS_PER_PAGE + 1); } } else { newSelection = -1; mRollo.setHomeSelected(SELECTED_FOCUSED); } } handled = true; break; } case KeyEvent.KEYCODE_DPAD_LEFT: if (currentPageCol > 0) { newSelection = currentSelection - 1; } handled = true; break; case KeyEvent.KEYCODE_DPAD_RIGHT: if ((currentPageCol < Defines.COLUMNS_PER_PAGE - 1) && (currentSelection < iconCount - 1)) { newSelection = currentSelection + 1; } handled = true; break; } if (newSelection != currentSelection) { mRollo.selectIcon(newSelection, SELECTED_FOCUSED); mRollo.mState.save(); } } return handled; } @Override public boolean onTouchEvent(MotionEvent ev) { mArrowNavigation = false; if (!isVisible()) { return true; } if (mLocks != 0) { return true; } super.onTouchEvent(ev); int x = (int)ev.getX(); int y = (int)ev.getY(); int action = ev.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: if (y > mRollo.mTouchYBorders[mRollo.mTouchYBorders.length-1]) { mTouchTracking = TRACKING_HOME; mRollo.setHomeSelected(SELECTED_PRESSED); mRollo.mState.save(); mCurrentIconIndex = -1; } else { mTouchTracking = TRACKING_FLING; mMotionDownRawX = (int)ev.getRawX(); mMotionDownRawY = (int)ev.getRawY(); mRollo.mState.newPositionX = ev.getRawY() / getHeight(); mRollo.mState.newTouchDown = 1; if (!mRollo.checkClickOK()) { mRollo.clearSelectedIcon(); } else { mDownIconIndex = mCurrentIconIndex = mRollo.selectIcon(x, y, mPosX, SELECTED_PRESSED); if (mDownIconIndex < 0) { // if nothing was selected, no long press. cancelLongPress(); } } mRollo.mState.save(); mRollo.move(); mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(ev); mStartedScrolling = false; } break; case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_OUTSIDE: if (mTouchTracking == TRACKING_HOME) { mRollo.setHomeSelected(y > mRollo.mTouchYBorders[mRollo.mTouchYBorders.length-1] ? SELECTED_PRESSED : SELECTED_NONE); mRollo.mState.save(); } else if (mTouchTracking == TRACKING_FLING) { int rawX = (int)ev.getRawX(); int rawY = (int)ev.getRawY(); int slop; slop = Math.abs(rawY - mMotionDownRawY); if (!mStartedScrolling && slop < mSlop) { // don't update anything so when we do start scrolling // below, we get the right delta. mCurrentIconIndex = mRollo.chooseTappedIcon(x, y, mPosX); if (mDownIconIndex != mCurrentIconIndex) { // If a different icon is selected, don't allow it to be picked up. // This handles off-axis dragging. cancelLongPress(); mCurrentIconIndex = -1; } } else { if (!mStartedScrolling) { cancelLongPress(); mCurrentIconIndex = -1; } mRollo.mState.newPositionX = ev.getRawY() / getHeight(); mRollo.mState.newTouchDown = 1; mRollo.move(); mStartedScrolling = true; mRollo.clearSelectedIcon(); mVelocityTracker.addMovement(ev); mRollo.mState.save(); } } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: if (mTouchTracking == TRACKING_HOME) { if (action == MotionEvent.ACTION_UP) { if (y > mRollo.mTouchYBorders[mRollo.mTouchYBorders.length-1]) { reallyPlaySoundEffect(SoundEffectConstants.CLICK); mLauncher.closeAllApps(true); } mRollo.setHomeSelected(SELECTED_NONE); mRollo.mState.save(); } mCurrentIconIndex = -1; } else if (mTouchTracking == TRACKING_FLING) { mRollo.mState.newTouchDown = 0; mRollo.mState.newPositionX = ev.getRawY() / getHeight(); mVelocityTracker.computeCurrentVelocity(1000 /* px/sec */, mMaxFlingVelocity); mRollo.mState.flingVelocity = mVelocityTracker.getYVelocity() / getHeight(); mRollo.clearSelectedIcon(); mRollo.mState.save(); mRollo.fling(); if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } mTouchTracking = TRACKING_NONE; break; } return true; } public void onClick(View v) { if (mLocks != 0 || !isVisible()) { return; } if (mRollo.checkClickOK() && mCurrentIconIndex == mDownIconIndex && mCurrentIconIndex >= 0 && mCurrentIconIndex < mAllAppsList.size()) { reallyPlaySoundEffect(SoundEffectConstants.CLICK); ApplicationInfo app = mAllAppsList.get(mCurrentIconIndex); mLauncher.startActivitySafely(app.intent); } } public boolean onLongClick(View v) { if (mLocks != 0 || !isVisible()) { return true; } if (mRollo.checkClickOK() && mCurrentIconIndex == mDownIconIndex && mCurrentIconIndex >= 0 && mCurrentIconIndex < mAllAppsList.size()) { ApplicationInfo app = mAllAppsList.get(mCurrentIconIndex); // We don't really have an accurate location to use. This will do. int screenX = mMotionDownRawX - (mDefines.ICON_WIDTH_PX / 2); int screenY = mMotionDownRawY - mDefines.ICON_HEIGHT_PX; int left = (mDefines.ICON_TEXTURE_WIDTH_PX - mDefines.ICON_WIDTH_PX) / 2; int top = (mDefines.ICON_TEXTURE_HEIGHT_PX - mDefines.ICON_HEIGHT_PX) / 2; mDragController.startDrag(app.iconBitmap, screenX, screenY, left, top, mDefines.ICON_WIDTH_PX, mDefines.ICON_HEIGHT_PX, this, app, DragController.DRAG_ACTION_COPY); mLauncher.closeAllApps(true); } return true; } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SELECTED) { if (!isVisible()) { return false; } String text = null; int index; int count = mAllAppsList.size() + 1; // +1 is home int pos = -1; switch (mLastSelection) { case SELECTION_ICONS: index = mRollo.mState.selectedIconIndex; if (index >= 0) { ApplicationInfo info = mAllAppsList.get(index); if (info.title != null) { text = info.title.toString(); pos = index; } } break; case SELECTION_HOME: text = getContext().getString(R.string.all_apps_home_button_label); pos = count; break; } if (text != null) { event.setEnabled(true); event.getText().add(text); //event.setContentDescription(text); event.setItemCount(count); event.setCurrentItemIndex(pos); } } return false; } public void setDragController(DragController dragger) { mDragController = dragger; } public void onDropCompleted(View target, boolean success) { } /** * Zoom to the specifed level. * * @param zoom [0..1] 0 is hidden, 1 is open */ public void zoom(float zoom, boolean animate) { cancelLongPress(); if (mRollo == null || !mRollo.mHasSurface) { mZoomDirty = true; mZoom = zoom; mAnimateNextZoom = animate; return; } else { mRollo.setZoom(zoom, animate); } } public boolean isVisible() { return mZoom > 0.001f; } public boolean isOpaque() { return mZoom > 0.999f; } public void setApps(ArrayList<ApplicationInfo> list) { mAllAppsList = list; if (mRollo != null) { if (mRollo.mHasSurface) { mRollo.setApps(list); } else { mRollo.mAppsDirty = true; } } mLocks &= ~LOCK_ICONS_PENDING; } public void addApps(ArrayList<ApplicationInfo> list) { if (mAllAppsList == null) { // Not done loading yet. We'll find out about it later. return; } final int N = list.size(); if (mRollo != null && mRollo.mHasSurface) { mRollo.reallocAppsList(mRollo.mState.iconCount + N); } for (int i=0; i<N; i++) { final ApplicationInfo item = list.get(i); int index = Collections.binarySearch(mAllAppsList, item, LauncherModel.APP_NAME_COMPARATOR); if (index < 0) { index = -(index+1); } mAllAppsList.add(index, item); if (mRollo != null && mRollo.mHasSurface) { mRollo.addApp(index, item); mRollo.mState.iconCount++; } } if (mRollo != null && mRollo.mHasSurface) { mRollo.saveAppsList(); } } public void removeApps(ArrayList<ApplicationInfo> list) { if (mAllAppsList == null) { // Not done loading yet. We'll find out about it later. return; } final int N = list.size(); for (int i=0; i<N; i++) { final ApplicationInfo item = list.get(i); int index = findAppByComponent(mAllAppsList, item); if (index >= 0) { int ic = mRollo != null ? mRollo.mState.iconCount : 666; mAllAppsList.remove(index); if (mRollo != null && mRollo.mHasSurface) { mRollo.removeApp(index); } } else { Log.w(TAG, "couldn't find a match for item \"" + item + "\""); // Try to recover. This should keep us from crashing for now. } } if (mRollo != null && mRollo.mHasSurface) { mRollo.saveAppsList(); } } public void updateApps(String packageName, ArrayList<ApplicationInfo> list) { // Just remove and add, because they may need to be re-sorted. removeApps(list); addApps(list); } private static int findAppByComponent(ArrayList<ApplicationInfo> list, ApplicationInfo item) { ComponentName component = item.intent.getComponent(); final int N = list.size(); for (int i=0; i<N; i++) { ApplicationInfo x = list.get(i); if (x.intent.getComponent().equals(component)) { return i; } } return -1; } private static int countPages(int iconCount) { int iconsPerPage = Defines.COLUMNS_PER_PAGE * Defines.ROWS_PER_PAGE; int pages = iconCount / iconsPerPage; if (pages*iconsPerPage != iconCount) { pages++; } return pages; } class AAMessage extends RenderScript.RSMessage { public void run() { mPosX = ((float)mData[0]) / (1 << 16); mVelocity = ((float)mData[1]) / (1 << 16); mZoom = ((float)mData[2]) / (1 << 16); mZoomDirty = false; } } public class RolloRS { // Allocations ====== private int mWidth; private int mHeight; private Resources mRes; private Script mScript; private Script.Invokable mInvokeMove; private Script.Invokable mInvokeMoveTo; private Script.Invokable mInvokeFling; private Script.Invokable mInvokeResetWAR; private Script.Invokable mInvokeSetZoom; private ProgramStore mPSIcons; private ProgramStore mPSText; private ProgramFragment mPFColor; private ProgramFragment mPFTexMip; private ProgramFragment mPFTexNearest; private ProgramVertex mPV; private ProgramVertex mPVOrtho; private SimpleMesh mMesh; private SimpleMesh mMesh2; private ProgramVertex.MatrixAllocation mPVA; private Allocation mHomeButtonNormal; private Allocation mHomeButtonFocused; private Allocation mHomeButtonPressed; private Allocation[] mIcons; private int[] mIconIds; private Allocation mAllocIconIds; private Allocation[] mLabels; private int[] mLabelIds; private Allocation mAllocLabelIds; private Allocation mSelectedIcon; private int[] mTouchYBorders; private int[] mTouchXBorders; private Bitmap mSelectionBitmap; private Canvas mSelectionCanvas; boolean mHasSurface = false; private boolean mAppsDirty = false; Params mParams; State mState; class BaseAlloc { Allocation mAlloc; Type mType; void save() { mAlloc.data(this); } } private boolean checkClickOK() { return (Math.abs(mVelocity) < 0.4f) && (Math.abs(mPosX - Math.round(mPosX)) < 0.4f); } class Params extends BaseAlloc { Params() { mType = Type.createFromClass(mRS, Params.class, 1, "ParamsClass"); mAlloc = Allocation.createTyped(mRS, mType); save(); } public int bubbleWidth; public int bubbleHeight; public int bubbleBitmapWidth; public int bubbleBitmapHeight; public int homeButtonWidth; public int homeButtonHeight; public int homeButtonTextureWidth; public int homeButtonTextureHeight; } class State extends BaseAlloc { public float newPositionX; public int newTouchDown; public float flingVelocity; public int iconCount; public int selectedIconIndex = -1; public int selectedIconTexture; public float zoomTarget; public int homeButtonId; public float targetPos; State() { mType = Type.createFromClass(mRS, State.class, 1, "StateClass"); mAlloc = Allocation.createTyped(mRS, mType); save(); } } public RolloRS() { } public void init(Resources res, int width, int height) { mRes = res; mWidth = width; mHeight = height; mDefines.recompute(width, height); initProgramVertex(); initProgramFragment(); initProgramStore(); initMesh(); initGl(); initData(); initTouchState(); initRs(); } public void initMesh() { SimpleMesh.TriangleMeshBuilder tm = new SimpleMesh.TriangleMeshBuilder(mRS, 3, SimpleMesh.TriangleMeshBuilder.TEXTURE_0 | SimpleMesh.TriangleMeshBuilder.COLOR); float y = 0; float z = 0; for (int ct=0; ct < 200; ct++) { float angle = 0; float maxAngle = 3.14f * 0.16f; float l = 1.f; l = 1 - ((ct-5) * 0.10f); if (ct > 7) { angle = maxAngle * (ct - 7) * 0.2f; angle = Math.min(angle, maxAngle); } l = Math.max(0.4f, l); l = Math.min(1.0f, l); y += 0.1f * Math.cos(angle); z += 0.1f * Math.sin(angle); float t = 0.1f * ct; float ds = 0.08f; tm.setColor(l, l, l, 0.99f); tm.setTexture(ds, t); tm.addVertex(-0.5f, y, z); tm.setTexture(1 - ds, t); tm.addVertex(0.5f, y, z); } for (int ct=0; ct < (200 * 2 - 2); ct+= 2) { tm.addTriangle(ct, ct+1, ct+2); tm.addTriangle(ct+1, ct+3, ct+2); } mMesh2 = tm.create(); mMesh2.setName("SMMesh"); } void resize(int w, int h) { mPVA.setupProjectionNormalized(w, h); mWidth = w; mHeight = h; } private void initProgramVertex() { mPVA = new ProgramVertex.MatrixAllocation(mRS); resize(mWidth, mHeight); ProgramVertex.Builder pvb = new ProgramVertex.Builder(mRS, null, null); pvb.setTextureMatrixEnable(true); mPV = pvb.create(); mPV.setName("PV"); mPV.bindAllocation(mPVA); //pva = new ProgramVertex.MatrixAllocation(mRS); //pva.setupOrthoWindow(mWidth, mHeight); //pvb.setTextureMatrixEnable(true); //mPVOrtho = pvb.create(); //mPVOrtho.setName("PVOrtho"); //mPVOrtho.bindAllocation(pva); mRS.contextBindProgramVertex(mPV); } private void initProgramFragment() { Sampler.Builder sb = new Sampler.Builder(mRS); sb.setMin(Sampler.Value.LINEAR_MIP_LINEAR); sb.setMag(Sampler.Value.LINEAR); sb.setWrapS(Sampler.Value.CLAMP); sb.setWrapT(Sampler.Value.CLAMP); Sampler linear = sb.create(); sb.setMin(Sampler.Value.NEAREST); sb.setMag(Sampler.Value.NEAREST); Sampler nearest = sb.create(); ProgramFragment.Builder bf = new ProgramFragment.Builder(mRS, null, null); //mPFColor = bf.create(); //mPFColor.setName("PFColor"); bf.setTexEnable(true, 0); bf.setTexEnvMode(ProgramFragment.EnvMode.MODULATE, 0); mPFTexMip = bf.create(); mPFTexMip.setName("PFTexMip"); mPFTexMip.bindSampler(linear, 0); mPFTexNearest = bf.create(); mPFTexNearest.setName("PFTexNearest"); mPFTexNearest.bindSampler(nearest, 0); } private void initProgramStore() { ProgramStore.Builder bs = new ProgramStore.Builder(mRS, null, null); bs.setDepthFunc(ProgramStore.DepthFunc.ALWAYS); bs.setColorMask(true,true,true,false); bs.setDitherEnable(true); bs.setBlendFunc(ProgramStore.BlendSrcFunc.SRC_ALPHA, ProgramStore.BlendDstFunc.ONE_MINUS_SRC_ALPHA); mPSIcons = bs.create(); mPSIcons.setName("PSIcons"); //bs.setDitherEnable(false); //mPSText = bs.create(); //mPSText.setName("PSText"); } private void initGl() { mTouchXBorders = new int[Defines.COLUMNS_PER_PAGE+1]; mTouchYBorders = new int[Defines.ROWS_PER_PAGE+1]; } private void initData() { mParams = new Params(); mState = new State(); final Utilities.BubbleText bubble = new Utilities.BubbleText(getContext()); mParams.bubbleWidth = bubble.getBubbleWidth(); mParams.bubbleHeight = bubble.getMaxBubbleHeight(); mParams.bubbleBitmapWidth = bubble.getBitmapWidth(); mParams.bubbleBitmapHeight = bubble.getBitmapHeight(); mHomeButtonNormal = Allocation.createFromBitmapResource(mRS, mRes, R.drawable.home_button_normal, Element.RGBA_8888(mRS), false); mHomeButtonNormal.uploadToTexture(0); mHomeButtonFocused = Allocation.createFromBitmapResource(mRS, mRes, R.drawable.home_button_focused, Element.RGBA_8888(mRS), false); mHomeButtonFocused.uploadToTexture(0); mHomeButtonPressed = Allocation.createFromBitmapResource(mRS, mRes, R.drawable.home_button_pressed, Element.RGBA_8888(mRS), false); mHomeButtonPressed.uploadToTexture(0); mParams.homeButtonWidth = 76; mParams.homeButtonHeight = 68; mParams.homeButtonTextureWidth = 128; mParams.homeButtonTextureHeight = 128; mState.homeButtonId = mHomeButtonNormal.getID(); mParams.save(); mState.save(); mSelectionBitmap = Bitmap.createBitmap(Defines.ICON_TEXTURE_WIDTH_PX, Defines.ICON_TEXTURE_HEIGHT_PX, Bitmap.Config.ARGB_8888); mSelectionCanvas = new Canvas(mSelectionBitmap); setApps(null); } private void initScript(int id) { } private void initRs() { ScriptC.Builder sb = new ScriptC.Builder(mRS); sb.setScript(mRes, R.raw.rollo3); sb.setRoot(true); sb.addDefines(mDefines); sb.setType(mParams.mType, "params", Defines.ALLOC_PARAMS); sb.setType(mState.mType, "state", Defines.ALLOC_STATE); mInvokeMove = sb.addInvokable("move"); mInvokeFling = sb.addInvokable("fling"); mInvokeMoveTo = sb.addInvokable("moveTo"); mInvokeResetWAR = sb.addInvokable("resetHWWar"); mInvokeSetZoom = sb.addInvokable("setZoom"); mScript = sb.create(); mScript.setClearColor(0.0f, 0.0f, 0.0f, 0.0f); mScript.bindAllocation(mParams.mAlloc, Defines.ALLOC_PARAMS); mScript.bindAllocation(mState.mAlloc, Defines.ALLOC_STATE); mScript.bindAllocation(mAllocIconIds, Defines.ALLOC_ICON_IDS); mScript.bindAllocation(mAllocLabelIds, Defines.ALLOC_LABEL_IDS); mRS.contextBindRootScript(mScript); } private void uploadApps(ArrayList<ApplicationInfo> list) { for (int i=0; i < mState.iconCount; i++) { uploadAppIcon(i, list.get(i)); } } void dirtyCheck() { if (mHasSurface) { if (mAppsDirty) { uploadApps(mAllAppsList); saveAppsList(); mAppsDirty = false; } if (mZoomDirty) { setZoom(mZoom, mAnimateNextZoom); } } } private void setApps(ArrayList<ApplicationInfo> list) { final int count = list != null ? list.size() : 0; int allocCount = count; if (allocCount < 1) { allocCount = 1; } mIcons = new Allocation[count]; mIconIds = new int[allocCount]; mAllocIconIds = Allocation.createSized(mRS, Element.USER_I32(mRS), allocCount); mLabels = new Allocation[count]; mLabelIds = new int[allocCount]; mAllocLabelIds = Allocation.createSized(mRS, Element.USER_I32(mRS), allocCount); Element ie8888 = Element.RGBA_8888(mRS); Utilities.BubbleText bubble = new Utilities.BubbleText(getContext()); mState.iconCount = count; uploadApps(list); saveAppsList(); } private void setZoom(float zoom, boolean animate) { mRollo.clearSelectedIcon(); mRollo.setHomeSelected(SELECTED_NONE); if (zoom > 0.001f) { mRollo.mState.zoomTarget = zoom; } else { mRollo.mState.zoomTarget = 0; } mRollo.mState.save(); if (!animate) { mRollo.mInvokeSetZoom.execute(); } } private void frameBitmapAllocMips(Allocation alloc, int w, int h) { int black[] = new int[w > h ? w : h]; Allocation.Adapter2D a = alloc.createAdapter2D(); int mip = 0; while (w > 1 || h > 1) { a.subData(0, 0, 1, h, black); a.subData(w-1, 0, 1, h, black); a.subData(0, 0, w, 1, black); a.subData(0, h-1, w, 1, black); mip++; w = (w + 1) >> 1; h = (h + 1) >> 1; a.setConstraint(Dimension.LOD, mip); } a.subData(0, 0, 1, 1, black); } private void uploadAppIcon(int index, ApplicationInfo item) { mIcons[index] = Allocation.createFromBitmap(mRS, item.iconBitmap, Element.RGBA_8888(mRS), true); frameBitmapAllocMips(mIcons[index], item.iconBitmap.getWidth(), item.iconBitmap.getHeight()); mLabels[index] = Allocation.createFromBitmap(mRS, item.titleBitmap, Element.RGBA_8888(mRS), true); frameBitmapAllocMips(mLabels[index], item.titleBitmap.getWidth(), item.titleBitmap.getHeight()); mIcons[index].uploadToTexture(0); mLabels[index].uploadToTexture(0); mIconIds[index] = mIcons[index].getID(); mLabelIds[index] = mLabels[index].getID(); } /** * Puts the empty spaces at the end. Updates mState.iconCount. You must * fill in the values and call saveAppsList(). */ private void reallocAppsList(int count) { Allocation[] icons = new Allocation[count]; int[] iconIds = new int[count]; mAllocIconIds = Allocation.createSized(mRS, Element.USER_I32(mRS), count); Allocation[] labels = new Allocation[count]; int[] labelIds = new int[count]; mAllocLabelIds = Allocation.createSized(mRS, Element.USER_I32(mRS), count); final int oldCount = mRollo.mState.iconCount; System.arraycopy(mIcons, 0, icons, 0, oldCount); System.arraycopy(mIconIds, 0, iconIds, 0, oldCount); System.arraycopy(mLabels, 0, labels, 0, oldCount); System.arraycopy(mLabelIds, 0, labelIds, 0, oldCount); mIcons = icons; mIconIds = iconIds; mLabels = labels; mLabelIds = labelIds; } /** * Handle the allocations for the new app. Make sure you call saveAppsList when done. */ private void addApp(int index, ApplicationInfo item) { final int count = mState.iconCount - index; final int dest = index + 1; System.arraycopy(mIcons, index, mIcons, dest, count); System.arraycopy(mIconIds, index, mIconIds, dest, count); System.arraycopy(mLabels, index, mLabels, dest, count); System.arraycopy(mLabelIds, index, mLabelIds, dest, count); if (mHasSurface) { uploadAppIcon(index, item); } else { mAppsDirty = true; } } /** * Handle the allocations for the removed app. Make sure you call saveAppsList when done. */ private void removeApp(int index) { final int count = mState.iconCount - index - 1; final int src = index + 1; System.arraycopy(mIcons, src, mIcons, index, count); System.arraycopy(mIconIds, src, mIconIds, index, count); System.arraycopy(mLabels, src, mLabels, index, count); System.arraycopy(mLabelIds, src, mLabelIds, index, count); mRollo.mState.iconCount--; final int last = mState.iconCount - 1; mIcons[last] = null; mIconIds[last] = 0; mLabels[last] = null; mLabelIds[last] = 0; } /** * Send the apps list structures to RS. */ private void saveAppsList() { mRS.contextBindRootScript(null); mAllocIconIds.data(mIconIds); mAllocLabelIds.data(mLabelIds); if (mScript != null) { // this happens when we init it mScript.bindAllocation(mAllocIconIds, Defines.ALLOC_ICON_IDS); mScript.bindAllocation(mAllocLabelIds, Defines.ALLOC_LABEL_IDS); } mState.save(); // Note: mScript may be null if we haven't initialized it yet. // In that case, this is a no-op. if (mInvokeResetWAR != null) { mInvokeResetWAR.execute(); } mRS.contextBindRootScript(mScript); } void initTouchState() { int width = getWidth(); int height = getHeight(); int cellHeight = 145;//iconsSize / Defines.ROWS_PER_PAGE; int cellWidth = width / Defines.COLUMNS_PER_PAGE; int centerY = (height / 2); mTouchYBorders[0] = centerY - (cellHeight * 2); mTouchYBorders[1] = centerY - cellHeight; mTouchYBorders[2] = centerY; mTouchYBorders[3] = centerY + cellHeight; mTouchYBorders[4] = centerY + (cellHeight * 2); int centerX = (width / 2); mTouchXBorders[0] = 0; mTouchXBorders[1] = centerX - (width / 4); mTouchXBorders[2] = centerX; mTouchXBorders[3] = centerX + (width / 4); mTouchXBorders[4] = width; } void fling() { mInvokeFling.execute(); } void move() { mInvokeMove.execute(); } void moveTo(float row) { mState.targetPos = row; mState.save(); mInvokeMoveTo.execute(); } int chooseTappedIcon(int x, int y, float pos) { // Adjust for scroll position if not zero. y += (pos - ((int)pos)) * (mTouchYBorders[1] - mTouchYBorders[0]); int col = -1; int row = -1; for (int i=0; i<Defines.COLUMNS_PER_PAGE; i++) { if (x >= mTouchXBorders[i] && x < mTouchXBorders[i+1]) { col = i; break; } } for (int i=0; i<Defines.ROWS_PER_PAGE; i++) { if (y >= mTouchYBorders[i] && y < mTouchYBorders[i+1]) { row = i; break; } } if (row < 0 || col < 0) { return -1; } int index = (((int)pos) * Defines.COLUMNS_PER_PAGE) + (row * Defines.ROWS_PER_PAGE) + col; if (index >= mState.iconCount) { return -1; } else { return index; } } /** * You need to call save() on mState on your own after calling this. * * @return the index of the icon that was selected. */ int selectIcon(int x, int y, float pos, int pressed) { final int index = chooseTappedIcon(x, y, pos); selectIcon(index, pressed); return index; } /** * Select the icon at the given index. * * @param index The index. * @param pressed one of SELECTED_PRESSED or SELECTED_FOCUSED */ void selectIcon(int index, int pressed) { if (mAllAppsList == null || index < 0 || index >= mAllAppsList.size()) { mState.selectedIconIndex = -1; if (mLastSelection == SELECTION_ICONS) { mLastSelection = SELECTION_NONE; } } else { if (pressed == SELECTED_FOCUSED) { mLastSelection = SELECTION_ICONS; } int prev = mState.selectedIconIndex; mState.selectedIconIndex = index; ApplicationInfo info = mAllAppsList.get(index); Bitmap selectionBitmap = mSelectionBitmap; Utilities.drawSelectedAllAppsBitmap(mSelectionCanvas, selectionBitmap.getWidth(), selectionBitmap.getHeight(), pressed == SELECTED_PRESSED, info.iconBitmap); mSelectedIcon = Allocation.createFromBitmap(mRS, selectionBitmap, Element.RGBA_8888(mRS), false); mSelectedIcon.uploadToTexture(0); mState.selectedIconTexture = mSelectedIcon.getID(); if (prev != index) { if (info.title != null && info.title.length() > 0) { //setContentDescription(info.title); sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); } } } } /** * You need to call save() on mState on your own after calling this. */ void clearSelectedIcon() { mState.selectedIconIndex = -1; } void setHomeSelected(int mode) { final int prev = mLastSelection; switch (mode) { case SELECTED_NONE: mState.homeButtonId = mHomeButtonNormal.getID(); break; case SELECTED_FOCUSED: mLastSelection = SELECTION_HOME; mState.homeButtonId = mHomeButtonFocused.getID(); if (prev != SELECTION_HOME) { sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); } break; case SELECTED_PRESSED: mState.homeButtonId = mHomeButtonPressed.getID(); break; } } public void dumpState() { Log.d(TAG, "mRollo.mWidth=" + mWidth); Log.d(TAG, "mRollo.mHeight=" + mHeight); Log.d(TAG, "mRollo.mIcons=" + mIcons); if (mIcons != null) { Log.d(TAG, "mRollo.mIcons.length=" + mIcons.length); } if (mIconIds != null) { Log.d(TAG, "mRollo.mIconIds.length=" + mIconIds.length); } Log.d(TAG, "mRollo.mIconIds=" + Arrays.toString(mIconIds)); if (mLabelIds != null) { Log.d(TAG, "mRollo.mLabelIds.length=" + mLabelIds.length); } Log.d(TAG, "mRollo.mLabelIds=" + Arrays.toString(mLabelIds)); Log.d(TAG, "mRollo.mTouchXBorders=" + Arrays.toString(mTouchXBorders)); Log.d(TAG, "mRollo.mTouchYBorders=" + Arrays.toString(mTouchYBorders)); Log.d(TAG, "mRollo.mHasSurface=" + mHasSurface); Log.d(TAG, "mRollo.mAppsDirty=" + mAppsDirty); Log.d(TAG, "mRollo.mState.newPositionX=" + mState.newPositionX); Log.d(TAG, "mRollo.mState.newTouchDown=" + mState.newTouchDown); Log.d(TAG, "mRollo.mState.flingVelocity=" + mState.flingVelocity); Log.d(TAG, "mRollo.mState.iconCount=" + mState.iconCount); Log.d(TAG, "mRollo.mState.selectedIconIndex=" + mState.selectedIconIndex); Log.d(TAG, "mRollo.mState.selectedIconTexture=" + mState.selectedIconTexture); Log.d(TAG, "mRollo.mState.zoomTarget=" + mState.zoomTarget); Log.d(TAG, "mRollo.mState.homeButtonId=" + mState.homeButtonId); Log.d(TAG, "mRollo.mState.targetPos=" + mState.targetPos); Log.d(TAG, "mRollo.mParams.bubbleWidth=" + mParams.bubbleWidth); Log.d(TAG, "mRollo.mParams.bubbleHeight=" + mParams.bubbleHeight); Log.d(TAG, "mRollo.mParams.bubbleBitmapWidth=" + mParams.bubbleBitmapWidth); Log.d(TAG, "mRollo.mParams.bubbleBitmapHeight=" + mParams.bubbleBitmapHeight); Log.d(TAG, "mRollo.mParams.homeButtonWidth=" + mParams.homeButtonWidth); Log.d(TAG, "mRollo.mParams.homeButtonHeight=" + mParams.homeButtonHeight); Log.d(TAG, "mRollo.mParams.homeButtonTextureWidth=" + mParams.homeButtonTextureWidth); Log.d(TAG, "mRollo.mParams.homeButtonTextureHeight=" + mParams.homeButtonTextureHeight); } } public void dumpState() { Log.d(TAG, "mRS=" + mRS); Log.d(TAG, "mRollo=" + mRollo); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList", mAllAppsList); Log.d(TAG, "mArrowNavigation=" + mArrowNavigation); Log.d(TAG, "mStartedScrolling=" + mStartedScrolling); Log.d(TAG, "mLastSelection=" + mLastSelection); Log.d(TAG, "mLastSelectedIcon=" + mLastSelectedIcon); Log.d(TAG, "mVelocityTracker=" + mVelocityTracker); Log.d(TAG, "mTouchTracking=" + mTouchTracking); Log.d(TAG, "mShouldGainFocus=" + mShouldGainFocus); Log.d(TAG, "mZoomDirty=" + mZoomDirty); Log.d(TAG, "mAnimateNextZoom=" + mAnimateNextZoom); Log.d(TAG, "mZoom=" + mZoom); Log.d(TAG, "mPosX=" + mPosX); Log.d(TAG, "mVelocity=" + mVelocity); Log.d(TAG, "mMessageProc=" + mMessageProc); if (mRollo != null) { mRollo.dumpState(); } if (mRS != null) { mRS.contextDump(0); } } }
true
true
public boolean onKeyDown(int keyCode, KeyEvent event) { boolean handled = false; if (!isVisible()) { return false; } final int iconCount = mRollo.mState.iconCount; if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) { if (mArrowNavigation) { if (mLastSelection == SELECTION_HOME) { reallyPlaySoundEffect(SoundEffectConstants.CLICK); mLauncher.closeAllApps(true); } else { int whichApp = mRollo.mState.selectedIconIndex; if (whichApp >= 0) { ApplicationInfo app = mAllAppsList.get(whichApp); mLauncher.startActivitySafely(app.intent); handled = true; } } } } if (iconCount > 0) { mArrowNavigation = true; int currentSelection = mRollo.mState.selectedIconIndex; int currentTopRow = Math.round(mPosX); // The column of the current selection, in the range 0..COLUMNS_PER_PAGE-1 final int currentPageCol = currentSelection % Defines.COLUMNS_PER_PAGE; // The row of the current selection, in the range 0..ROWS_PER_PAGE-1 final int currentPageRow = (currentSelection - (currentTopRow*Defines.COLUMNS_PER_PAGE)) / Defines.ROWS_PER_PAGE; int newSelection = currentSelection; switch (keyCode) { case KeyEvent.KEYCODE_DPAD_UP: if (mLastSelection == SELECTION_HOME) { mRollo.setHomeSelected(SELECTED_NONE); int lastRowCount = iconCount % Defines.COLUMNS_PER_PAGE; if (lastRowCount == 0) { lastRowCount = Defines.COLUMNS_PER_PAGE; } newSelection = iconCount - lastRowCount + (Defines.COLUMNS_PER_PAGE / 2); if (newSelection >= iconCount) { newSelection = iconCount-1; } int target = (newSelection / Defines.COLUMNS_PER_PAGE) - (Defines.ROWS_PER_PAGE - 1); if (target < 0) { target = 0; } if (currentTopRow != target) { mRollo.moveTo(target); } } else { if (currentPageRow > 0) { newSelection = currentSelection - Defines.COLUMNS_PER_PAGE; } else if (currentTopRow > 0) { newSelection = currentSelection - Defines.COLUMNS_PER_PAGE; mRollo.moveTo(newSelection / Defines.COLUMNS_PER_PAGE); } else { newSelection = Defines.COLUMNS_PER_PAGE * (Defines.ROWS_PER_PAGE-1); } } handled = true; break; case KeyEvent.KEYCODE_DPAD_DOWN: { final int rowCount = iconCount / Defines.COLUMNS_PER_PAGE + (iconCount % Defines.COLUMNS_PER_PAGE == 0 ? 0 : 1); final int currentRow = currentSelection / Defines.COLUMNS_PER_PAGE; if (mLastSelection != SELECTION_HOME) { if (currentRow < rowCount-1) { mRollo.setHomeSelected(SELECTED_NONE); if (currentSelection < 0) { newSelection = 0; } else { newSelection = currentSelection + Defines.COLUMNS_PER_PAGE; } if (newSelection >= iconCount) { // Go from D to G in this arrangement: // A B C D // E F G newSelection = iconCount - 1; } if (currentPageRow >= Defines.ROWS_PER_PAGE - 1) { mRollo.moveTo((newSelection / Defines.COLUMNS_PER_PAGE) - Defines.ROWS_PER_PAGE + 1); } } else { newSelection = -1; mRollo.setHomeSelected(SELECTED_FOCUSED); } } handled = true; break; } case KeyEvent.KEYCODE_DPAD_LEFT: if (currentPageCol > 0) { newSelection = currentSelection - 1; } handled = true; break; case KeyEvent.KEYCODE_DPAD_RIGHT: if ((currentPageCol < Defines.COLUMNS_PER_PAGE - 1) && (currentSelection < iconCount - 1)) { newSelection = currentSelection + 1; } handled = true; break; } if (newSelection != currentSelection) { mRollo.selectIcon(newSelection, SELECTED_FOCUSED); mRollo.mState.save(); } } return handled; }
public boolean onKeyDown(int keyCode, KeyEvent event) { boolean handled = false; if (!isVisible()) { return false; } final int iconCount = mRollo.mState.iconCount; if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) { if (mArrowNavigation) { if (mLastSelection == SELECTION_HOME) { reallyPlaySoundEffect(SoundEffectConstants.CLICK); mLauncher.closeAllApps(true); } else { int whichApp = mRollo.mState.selectedIconIndex; if (whichApp >= 0) { ApplicationInfo app = mAllAppsList.get(whichApp); mLauncher.startActivitySafely(app.intent); handled = true; } } } } if (iconCount > 0) { mArrowNavigation = true; int currentSelection = mRollo.mState.selectedIconIndex; int currentTopRow = Math.round(mPosX); // The column of the current selection, in the range 0..COLUMNS_PER_PAGE-1 final int currentPageCol = currentSelection % Defines.COLUMNS_PER_PAGE; // The row of the current selection, in the range 0..ROWS_PER_PAGE-1 final int currentPageRow = (currentSelection - (currentTopRow*Defines.COLUMNS_PER_PAGE)) / Defines.ROWS_PER_PAGE; int newSelection = currentSelection; switch (keyCode) { case KeyEvent.KEYCODE_DPAD_UP: if (mLastSelection == SELECTION_HOME) { mRollo.setHomeSelected(SELECTED_NONE); int lastRowCount = iconCount % Defines.COLUMNS_PER_PAGE; if (lastRowCount == 0) { lastRowCount = Defines.COLUMNS_PER_PAGE; } newSelection = iconCount - lastRowCount + (Defines.COLUMNS_PER_PAGE / 2); if (newSelection >= iconCount) { newSelection = iconCount-1; } int target = (newSelection / Defines.COLUMNS_PER_PAGE) - (Defines.ROWS_PER_PAGE - 1); if (target < 0) { target = 0; } if (currentTopRow != target) { mRollo.moveTo(target); } } else { if (currentPageRow > 0) { newSelection = currentSelection - Defines.COLUMNS_PER_PAGE; } else if (currentTopRow > 0) { newSelection = currentSelection - Defines.COLUMNS_PER_PAGE; mRollo.moveTo(newSelection / Defines.COLUMNS_PER_PAGE); } else if (currentPageRow != 0) { newSelection = currentTopRow * Defines.ROWS_PER_PAGE; } } handled = true; break; case KeyEvent.KEYCODE_DPAD_DOWN: { final int rowCount = iconCount / Defines.COLUMNS_PER_PAGE + (iconCount % Defines.COLUMNS_PER_PAGE == 0 ? 0 : 1); final int currentRow = currentSelection / Defines.COLUMNS_PER_PAGE; if (mLastSelection != SELECTION_HOME) { if (currentRow < rowCount-1) { mRollo.setHomeSelected(SELECTED_NONE); if (currentSelection < 0) { newSelection = 0; } else { newSelection = currentSelection + Defines.COLUMNS_PER_PAGE; } if (newSelection >= iconCount) { // Go from D to G in this arrangement: // A B C D // E F G newSelection = iconCount - 1; } if (currentPageRow >= Defines.ROWS_PER_PAGE - 1) { mRollo.moveTo((newSelection / Defines.COLUMNS_PER_PAGE) - Defines.ROWS_PER_PAGE + 1); } } else { newSelection = -1; mRollo.setHomeSelected(SELECTED_FOCUSED); } } handled = true; break; } case KeyEvent.KEYCODE_DPAD_LEFT: if (currentPageCol > 0) { newSelection = currentSelection - 1; } handled = true; break; case KeyEvent.KEYCODE_DPAD_RIGHT: if ((currentPageCol < Defines.COLUMNS_PER_PAGE - 1) && (currentSelection < iconCount - 1)) { newSelection = currentSelection + 1; } handled = true; break; } if (newSelection != currentSelection) { mRollo.selectIcon(newSelection, SELECTED_FOCUSED); mRollo.mState.save(); } } return handled; }
diff --git a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/poll/SendVote.java b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/poll/SendVote.java index 3b682da68..c8ecc8b1f 100644 --- a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/poll/SendVote.java +++ b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/poll/SendVote.java @@ -1,168 +1,173 @@ package net.cyklotron.cms.modules.actions.poll; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import org.jcontainer.dna.Logger; import org.objectledge.context.Context; import org.objectledge.coral.security.Subject; import org.objectledge.coral.session.CoralSession; import org.objectledge.coral.store.Resource; import org.objectledge.i18n.I18nContext; import org.objectledge.parameters.Parameters; import org.objectledge.parameters.RequestParameters; import org.objectledge.pipeline.ProcessingException; import org.objectledge.templating.Template; import org.objectledge.templating.TemplatingContext; import org.objectledge.utils.StackTrace; import org.objectledge.web.HttpContext; import org.objectledge.web.captcha.CaptchaService; import org.objectledge.web.mvc.MVCContext; import net.cyklotron.cms.CmsData; import net.cyklotron.cms.CmsDataFactory; import net.cyklotron.cms.confirmation.EmailConfirmationService; import net.cyklotron.cms.documents.LinkRenderer; import net.cyklotron.cms.poll.AnswerResource; import net.cyklotron.cms.poll.PollService; import net.cyklotron.cms.poll.VoteResource; import net.cyklotron.cms.poll.VoteResourceImpl; import net.cyklotron.cms.structure.StructureService; import net.cyklotron.cms.util.OfflineLinkRenderingService; import net.cyklotron.cms.workflow.WorkflowService; /** * @author <a href="mailo:[email protected]">Pawel Potempski</a> * @version $Id: RespondPoll.java,v 1.7 2007-02-25 14:14:49 pablo Exp $ */ public class SendVote extends BasePollAction { private EmailConfirmationService emailConfirmationRequestService; private CaptchaService captchaService; private final OfflineLinkRenderingService linkRenderingService; public SendVote(Logger logger, StructureService structureService, CmsDataFactory cmsDataFactory, PollService pollService, WorkflowService workflowService, EmailConfirmationService emailConfirmationRequestService, CaptchaService captchaService, OfflineLinkRenderingService linkRenderingService) { super(logger, structureService, cmsDataFactory, pollService, workflowService); this.emailConfirmationRequestService = emailConfirmationRequestService; this.captchaService = captchaService; this.linkRenderingService = linkRenderingService; } /** * Performs the action. */ public void execute(Context context, Parameters parameters, MVCContext mvcContext, TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession) throws ProcessingException { HttpSession session = httpContext.getRequest().getSession(); CmsData cmsData = cmsDataFactory.getCmsData(context); Parameters screenConfig = cmsData.getEmbeddedScreenConfig(); if(session == null || session.isNew()) { templatingContext.put("result", "new_session"); return; } Subject subject = coralSession.getUserSubject(); int vid = parameters.getInt("vid", -1); if(vid == -1) { throw new ProcessingException("Vote id not found"); } + Long answerId = parameters.getLong("answer", -1); + if(answerId == -1) + { + templatingContext.put("result", "answer_not_found"); + return; + } String email = parameters.get("email", ""); if(!email.matches("([a-zA-Z0-9.-_]+@[a-zA-Z0-9.-_]+.[a-zA-Z]{1,4})?")) { templatingContext.put("result", "invalid_email"); return; } if(screenConfig.getBoolean("add_captcha", false) && !captchaService.checkCaptcha(httpContext, (RequestParameters)parameters)) { templatingContext.put("result", "invalid_captcha_verification"); return; } try { VoteResource voteResource = VoteResourceImpl.getVoteResource(coralSession, vid); Set<String> voteEmails = pollService.getBallotsEmails(coralSession, voteResource); if(pollService.hasVoted(httpContext, templatingContext, voteResource) || voteEmails.contains(email)) { templatingContext.put("already_voted", Boolean.TRUE); templatingContext.put("result", "already_responded"); return; } Resource[] answersResources = coralSession.getStore().getResource(voteResource); for(int i = 0; i < answersResources.length; i++) { AnswerResource answerResource = (AnswerResource)answersResources[i]; - Long answerId = parameters.getLong("answer_" + answerResource.getSequence(), -1); - if(answerId != -1) + if(answerId.equals(answerResource.getId())) { String confirmationRequest = emailConfirmationRequestService .createEmailConfirmationRequest(coralSession, email, answerId.toString()); I18nContext i18nContext = I18nContext.getI18nContext(context); Template template = pollService.getVoteConfiramationTicketTemplate( voteResource, i18nContext.getLocale()); LinkRenderer linkRenderer = linkRenderingService.getLinkRenderer(); Map<String, Object> entries = new HashMap<String, Object>(); entries.put("vote", voteResource); emailConfirmationRequestService.sendConfirmationRequest(confirmationRequest, voteResource.getSenderAddress(), email, entries, cmsData.getNode(), template, "PLAIN", linkRenderer, coralSession); setCookie(httpContext, vid, answerId); break; } } } catch(Exception e) { templatingContext.put("result", "exception"); templatingContext.put("trace", new StackTrace(e)); logger.error("Exception in poll,SendVote action", e); return; } templatingContext.put("result", "responded_successfully"); templatingContext.put("already_voted", Boolean.TRUE); } private void setCookie(HttpContext httpContext, Integer vid, Long answerId) { String cookieKey = "vote_" + vid; Cookie cookie = new Cookie(cookieKey, answerId.toString()); cookie.setMaxAge(30 * 24 * 3600); cookie.setPath("/"); httpContext.getResponse().addCookie(cookie); } public boolean checkAccessRights(Context context) throws ProcessingException { CmsData cmsData = cmsDataFactory.getCmsData(context); if(!cmsData.isApplicationEnabled("poll")) { logger.debug("Application 'poll' not enabled in site"); return false; } return true; } }
false
true
public void execute(Context context, Parameters parameters, MVCContext mvcContext, TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession) throws ProcessingException { HttpSession session = httpContext.getRequest().getSession(); CmsData cmsData = cmsDataFactory.getCmsData(context); Parameters screenConfig = cmsData.getEmbeddedScreenConfig(); if(session == null || session.isNew()) { templatingContext.put("result", "new_session"); return; } Subject subject = coralSession.getUserSubject(); int vid = parameters.getInt("vid", -1); if(vid == -1) { throw new ProcessingException("Vote id not found"); } String email = parameters.get("email", ""); if(!email.matches("([a-zA-Z0-9.-_]+@[a-zA-Z0-9.-_]+.[a-zA-Z]{1,4})?")) { templatingContext.put("result", "invalid_email"); return; } if(screenConfig.getBoolean("add_captcha", false) && !captchaService.checkCaptcha(httpContext, (RequestParameters)parameters)) { templatingContext.put("result", "invalid_captcha_verification"); return; } try { VoteResource voteResource = VoteResourceImpl.getVoteResource(coralSession, vid); Set<String> voteEmails = pollService.getBallotsEmails(coralSession, voteResource); if(pollService.hasVoted(httpContext, templatingContext, voteResource) || voteEmails.contains(email)) { templatingContext.put("already_voted", Boolean.TRUE); templatingContext.put("result", "already_responded"); return; } Resource[] answersResources = coralSession.getStore().getResource(voteResource); for(int i = 0; i < answersResources.length; i++) { AnswerResource answerResource = (AnswerResource)answersResources[i]; Long answerId = parameters.getLong("answer_" + answerResource.getSequence(), -1); if(answerId != -1) { String confirmationRequest = emailConfirmationRequestService .createEmailConfirmationRequest(coralSession, email, answerId.toString()); I18nContext i18nContext = I18nContext.getI18nContext(context); Template template = pollService.getVoteConfiramationTicketTemplate( voteResource, i18nContext.getLocale()); LinkRenderer linkRenderer = linkRenderingService.getLinkRenderer(); Map<String, Object> entries = new HashMap<String, Object>(); entries.put("vote", voteResource); emailConfirmationRequestService.sendConfirmationRequest(confirmationRequest, voteResource.getSenderAddress(), email, entries, cmsData.getNode(), template, "PLAIN", linkRenderer, coralSession); setCookie(httpContext, vid, answerId); break; } } } catch(Exception e) { templatingContext.put("result", "exception"); templatingContext.put("trace", new StackTrace(e)); logger.error("Exception in poll,SendVote action", e); return; } templatingContext.put("result", "responded_successfully"); templatingContext.put("already_voted", Boolean.TRUE); }
public void execute(Context context, Parameters parameters, MVCContext mvcContext, TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession) throws ProcessingException { HttpSession session = httpContext.getRequest().getSession(); CmsData cmsData = cmsDataFactory.getCmsData(context); Parameters screenConfig = cmsData.getEmbeddedScreenConfig(); if(session == null || session.isNew()) { templatingContext.put("result", "new_session"); return; } Subject subject = coralSession.getUserSubject(); int vid = parameters.getInt("vid", -1); if(vid == -1) { throw new ProcessingException("Vote id not found"); } Long answerId = parameters.getLong("answer", -1); if(answerId == -1) { templatingContext.put("result", "answer_not_found"); return; } String email = parameters.get("email", ""); if(!email.matches("([a-zA-Z0-9.-_]+@[a-zA-Z0-9.-_]+.[a-zA-Z]{1,4})?")) { templatingContext.put("result", "invalid_email"); return; } if(screenConfig.getBoolean("add_captcha", false) && !captchaService.checkCaptcha(httpContext, (RequestParameters)parameters)) { templatingContext.put("result", "invalid_captcha_verification"); return; } try { VoteResource voteResource = VoteResourceImpl.getVoteResource(coralSession, vid); Set<String> voteEmails = pollService.getBallotsEmails(coralSession, voteResource); if(pollService.hasVoted(httpContext, templatingContext, voteResource) || voteEmails.contains(email)) { templatingContext.put("already_voted", Boolean.TRUE); templatingContext.put("result", "already_responded"); return; } Resource[] answersResources = coralSession.getStore().getResource(voteResource); for(int i = 0; i < answersResources.length; i++) { AnswerResource answerResource = (AnswerResource)answersResources[i]; if(answerId.equals(answerResource.getId())) { String confirmationRequest = emailConfirmationRequestService .createEmailConfirmationRequest(coralSession, email, answerId.toString()); I18nContext i18nContext = I18nContext.getI18nContext(context); Template template = pollService.getVoteConfiramationTicketTemplate( voteResource, i18nContext.getLocale()); LinkRenderer linkRenderer = linkRenderingService.getLinkRenderer(); Map<String, Object> entries = new HashMap<String, Object>(); entries.put("vote", voteResource); emailConfirmationRequestService.sendConfirmationRequest(confirmationRequest, voteResource.getSenderAddress(), email, entries, cmsData.getNode(), template, "PLAIN", linkRenderer, coralSession); setCookie(httpContext, vid, answerId); break; } } } catch(Exception e) { templatingContext.put("result", "exception"); templatingContext.put("trace", new StackTrace(e)); logger.error("Exception in poll,SendVote action", e); return; } templatingContext.put("result", "responded_successfully"); templatingContext.put("already_voted", Boolean.TRUE); }
diff --git a/server/plugin/src/pt/webdetails/cdf/dd/render/cdw/CggChart.java b/server/plugin/src/pt/webdetails/cdf/dd/render/cdw/CggChart.java index bbdb4037..d3e25664 100644 --- a/server/plugin/src/pt/webdetails/cdf/dd/render/cdw/CggChart.java +++ b/server/plugin/src/pt/webdetails/cdf/dd/render/cdw/CggChart.java @@ -1,156 +1,156 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pt.webdetails.cdf.dd.render.cdw; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import net.sf.json.JSONArray; import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.Pointer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.platform.api.repository.ISolutionRepository; import org.pentaho.platform.engine.core.system.PentahoSessionHolder; import org.pentaho.platform.engine.core.system.PentahoSystem; import pt.webdetails.cdf.dd.render.components.BaseComponent; import pt.webdetails.cdf.dd.render.components.ComponentManager; /** * * @author pdpi */ public class CggChart { private static final Log logger = LogFactory.getLog(CggChart.class); private static final String CGG_EXTENSION = ".js"; JXPathContext document; Pointer chart; String path, chartName, chartTitle; Map<String, String> parameters; public CggChart(Pointer chart) { this.chart = chart; this.document = JXPathContext.newContext(chart.getRootNode()); this.path = ""; this.chartName = JXPathContext.newContext(chart.getNode()).getPointer("properties/.[name='name']/value").getValue().toString(); this.chartTitle = JXPathContext.newContext(chart.getNode()).getPointer("properties/.[name='title']/value").getValue().toString(); } public void renderToFile() { StringBuilder chartScript = new StringBuilder(); renderPreamble(chartScript); renderChart(chartScript); renderDatasource(chartScript); chartScript.append("renderCccFromComponent(render_" + this.chartName + ", data);\n"); chartScript.append( - "document.lastChild.setAttribute('width', " + this.chartName + ".chartDefinition.width);\n"+ - "document.lastChild.setAttribute('height', " + this.chartName + ".chartDefinition.height);"); + "document.lastChild.setAttribute('width', render_" + this.chartName + ".chartDefinition.width);\n"+ + "document.lastChild.setAttribute('height', render_" + this.chartName + ".chartDefinition.height);"); writeFile(chartScript); } private void renderDatasource(StringBuilder chartScript) { String datasourceName = JXPathContext.newContext(chart.getNode()).getPointer("properties/.[name='dataSource']/value").getNode().toString(); JXPathContext datasourceContext = JXPathContext.newContext(document.getPointer("/datasources/rows[properties[name='name' and value='" + datasourceName + "']]").getNode()); renderDatasourcePreamble(chartScript, datasourceContext); renderParameters(chartScript, JSONArray.fromObject(datasourceContext.getValue("properties/.[name='parameters']/value", String.class))); chartScript.append("var data = eval('new Object(' + String(datasource.execute()) + ');');\n"); } /** * Sets up the includes, place holders and any other niceties needed for the chart */ private void renderPreamble(StringBuilder chartScript) { chartScript.append("lib('protovis-bundle.js');\n\n"); chartScript.append("elem = document.createElement('g');\n" + "elem.setAttribute('id','canvas');\n" + "document.lastChild.appendChild(elem);\n\n"); } private void renderChart(StringBuilder chartScript) { ComponentManager engine = ComponentManager.getInstance(); JXPathContext context = document.getRelativeContext(chart); BaseComponent renderer = engine.getRenderer(context); renderer.setNode(context); chartScript.append(renderer.render(context)); } private void writeFile(StringBuilder chartScript) { try { ISolutionRepository solutionRepository = PentahoSystem.get(ISolutionRepository.class, PentahoSessionHolder.getSession()); solutionRepository.publish(PentahoSystem.getApplicationContext().getSolutionPath(""), path, this.chartName + CGG_EXTENSION, chartScript.toString().getBytes("UTF-8"), true); } catch (Exception e) { logger.error("failed to write script file for " + chartName + ": " + e.getCause().getMessage()); } } private void renderDatasourcePreamble(StringBuilder chartScript, JXPathContext context) { String dataAccessId = (String) context.getValue("properties/.[name='name']/value", String.class); chartScript.append("var datasource = datasourceFactory.createDatasource('cda');\n"); chartScript.append("datasource.setDefinitionFile(render_" + this.chartName + ".chartDefinition.path);\n"); chartScript.append("datasource.setDataAccessId('" + dataAccessId + "');\n\n"); } private void renderParameters(StringBuilder chartScript, JSONArray params) { parameters = new HashMap<String, String>(); Iterator<JSONArray> it = params.iterator(); while (it.hasNext()) { JSONArray param = it.next(); String paramName = param.get(0).toString(); String defaultValue = param.get(1).toString(); chartScript.append("var param" + paramName + " = params.get('" + paramName + "');\n"); chartScript.append("param" + paramName + " = (param" + paramName + " !== null && param" + paramName + " !== '')? param" + paramName + " : '"+ defaultValue+ "';\n"); chartScript.append("datasource.setParameter('" + paramName + "', param" + paramName + ");\n"); parameters.put(param.get(0).toString(), param.get(2).toString()); } } public void setPath(String path) { this.path = path; } public String getFilename() { return (path + "/" + this.chartName + CGG_EXTENSION).replaceAll("/+", "/"); } public Map<String, String> getParameters() { return parameters; } public String getName() { return (chartTitle != null && !chartTitle.isEmpty()) ? chartTitle : chartName; } public String getId() { return chartName; } }
true
true
public void renderToFile() { StringBuilder chartScript = new StringBuilder(); renderPreamble(chartScript); renderChart(chartScript); renderDatasource(chartScript); chartScript.append("renderCccFromComponent(render_" + this.chartName + ", data);\n"); chartScript.append( "document.lastChild.setAttribute('width', " + this.chartName + ".chartDefinition.width);\n"+ "document.lastChild.setAttribute('height', " + this.chartName + ".chartDefinition.height);"); writeFile(chartScript); }
public void renderToFile() { StringBuilder chartScript = new StringBuilder(); renderPreamble(chartScript); renderChart(chartScript); renderDatasource(chartScript); chartScript.append("renderCccFromComponent(render_" + this.chartName + ", data);\n"); chartScript.append( "document.lastChild.setAttribute('width', render_" + this.chartName + ".chartDefinition.width);\n"+ "document.lastChild.setAttribute('height', render_" + this.chartName + ".chartDefinition.height);"); writeFile(chartScript); }
diff --git a/core/src/processing/core/PImage.java b/core/src/processing/core/PImage.java index 7910717..91283e6 100644 --- a/core/src/processing/core/PImage.java +++ b/core/src/processing/core/PImage.java @@ -1,2722 +1,2722 @@ /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2004-10 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.core; import java.io.*; import java.util.HashMap; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Bitmap.Config; /** * Storage class for pixel data. This is the base class for most image and * pixel information, such as PGraphics and the video library classes. * <P> * Code for copying, resizing, scaling, and blending contributed * by <A HREF="http://www.toxi.co.uk">toxi</A>. * <P> */ public class PImage implements PConstants, Cloneable { /** * Format for this image, one of RGB, ARGB or ALPHA. * note that RGB images still require 0xff in the high byte * because of how they'll be manipulated by other functions */ public int format; public int[] pixels; public int width, height; /** * Path to parent object that will be used with save(). * This prevents users from needing savePath() to use PImage.save(). */ public PApplet parent; protected Bitmap bitmap; protected GLTexture texture; // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** for subclasses that need to store info about the image */ protected HashMap<Object,Object> cacheMap; /** modified portion of the image */ protected boolean modified; protected int mx1, my1, mx2, my2; // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // private fields private int fracU, ifU, fracV, ifV, u1, u2, v1, v2, sX, sY, iw, iw1, ih1; private int ul, ll, ur, lr, cUL, cLL, cUR, cLR; private int srcXOffset, srcYOffset; private int r, g, b, a; private int[] srcBuffer; // fixed point precision is limited to 15 bits!! static final int PRECISIONB = 15; static final int PRECISIONF = 1 << PRECISIONB; static final int PREC_MAXVAL = PRECISIONF-1; static final int PREC_ALPHA_SHIFT = 24-PRECISIONB; static final int PREC_RED_SHIFT = 16-PRECISIONB; // internal kernel stuff for the gaussian blur filter private int blurRadius; private int blurKernelSize; private int[] blurKernel; private int[][] blurMult; ////////////////////////////////////////////////////////////// /** * Create an empty image object, set its format to RGB. * The pixel array is not allocated. */ public PImage() { format = ARGB; // default to ARGB images for release 0116 // cache = null; } /** * Create a new RGB (alpha ignored) image of a specific size. * All pixels are set to zero, meaning black, but since the * alpha is zero, it will be transparent. */ public PImage(int width, int height) { init(width, height, RGB); } public PImage(int width, int height, int format) { init(width, height, format); } /** * Function to be used by subclasses of PImage to init later than * at the constructor, or re-init later when things changes. * Used by Capture and Movie classes (and perhaps others), * because the width/height will not be known when super() is called. * (Leave this public so that other libraries can do the same.) */ public void init(int width, int height, int format) { // ignore this.width = width; this.height = height; this.pixels = new int[width*height]; this.format = format; // this.cache = null; } /** * Check the alpha on an image, using a really primitive loop. */ protected void checkAlpha() { if (pixels == null) return; for (int i = 0; i < pixels.length; i++) { // since transparency is often at corners, hopefully this // will find a non-transparent pixel quickly and exit if ((pixels[i] & 0xff000000) != 0xff000000) { format = ARGB; break; } } } ////////////////////////////////////////////////////////////// /** * Construct a new PImage from an Android bitmap. The pixels[] array is not * initialized, nor is data copied to it, until loadPixels() is called. */ public PImage(Bitmap image) { this.bitmap = image; this.width = image.getWidth(); this.height = image.getHeight(); this.pixels = null; this.format = image.hasAlpha() ? ARGB : RGB; } /** * Returns a BufferedImage from this PImage. */ // public java.awt.Image getImage() { // loadPixels(); // int type = (format == RGB) ? // BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB; // BufferedImage image = new BufferedImage(width, height, type); // WritableRaster wr = image.getRaster(); // wr.setDataElements(0, 0, width, height, pixels); // return image; // } public Bitmap getBitmap() { return bitmap; } public void initTexture() { texture = new GLTexture(parent, width, height, new GLTexture.Parameters(format)); updateTexture(); } public void initTexture(int filter) { texture = new GLTexture(parent, width, height, new GLTexture.Parameters(format, filter)); updateTexture(); } public void initTexture(GLTexture.Parameters params) { texture = new GLTexture(parent, width, height, params); updateTexture(); } public void updateTexture() { loadPixels(); texture.set(this); } public void setTexture(GLTexture texture) { this.texture = texture; } public GLTexture getTexture() { return texture; } ////////////////////////////////////////////////////////////// /** * Store data of some kind for a renderer that requires extra metadata of * some kind. Usually this is a renderer-specific representation of the * image data, for instance a BufferedImage with tint() settings applied for * PGraphicsJava2D, or resized image data and OpenGL texture indices for * PGraphicsOpenGL. */ public void setCache(Object parent, Object storage) { if (cacheMap == null) cacheMap = new HashMap<Object, Object>(); cacheMap.put(parent, storage); } /** * Get cache storage data for the specified renderer. Because each renderer * will cache data in different formats, it's necessary to store cache data * keyed by the renderer object. Otherwise, attempting to draw the same * image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors. * @param parent The PGraphics object (or any object, really) associated * @return data stored for the specified parent */ public Object getCache(Object parent) { if (cacheMap == null) return null; return cacheMap.get(parent); } /** * Remove information associated with this renderer from the cache, if any. * @param parent The PGraphics object whose cache data should be removed */ public void removeCache(Object parent) { if (cacheMap != null) { cacheMap.remove(parent); } } ////////////////////////////////////////////////////////////// // MARKING IMAGE AS MODIFIED / FOR USE w/ GET/SET public boolean isModified() { // ignore return modified; } public void setModified() { // ignore modified = true; } public void setModified(boolean m) { // ignore modified = m; } /** * Call this when you want to mess with the pixels[] array. * <p/> * For subclasses where the pixels[] buffer isn't set by default, * this should copy all data into the pixels[] array */ public void loadPixels() { // ignore if (pixels == null || pixels.length != width*height) { pixels = new int[width*height]; } if (bitmap != null) { bitmap.getPixels(pixels, 0, width, 0, 0, width, height); } } /** * Call this when finished messing with the pixels[] array. * <p/> * Mark all pixels as needing update. */ public void updatePixels() { // ignore updatePixelsImpl(0, 0, width, height); } /** * Mark the pixels in this region as needing an update. * <P> * This is not currently used by any of the renderers, however the api * is structured this way in the hope of being able to use this to * speed things up in the future. */ public void updatePixels(int x, int y, int w, int h) { // ignore // if (imageMode == CORNER) { // x2, y2 are w/h // x2 += x1; // y2 += y1; // // } else if (imageMode == CENTER) { // x1 -= x2 / 2; // y1 -= y2 / 2; // x2 += x1; // y2 += y1; // } updatePixelsImpl(x, y, w, h); } protected void updatePixelsImpl(int x, int y, int w, int h) { int x2 = x + w; int y2 = y + h; if (!modified) { mx1 = x; mx2 = x2; my1 = y; my2 = y2; modified = true; } else { if (x < mx1) mx1 = x; if (x > mx2) mx2 = x; if (y < my1) my1 = y; if (y > my2) my2 = y; if (x2 < mx1) mx1 = x2; if (x2 > mx2) mx2 = x2; if (y2 < my1) my1 = y2; if (y2 > my2) my2 = y2; } } ////////////////////////////////////////////////////////////// // COPYING IMAGE DATA /** * Duplicate an image, returns new PImage object. * The pixels[] array for the new object will be unique * and recopied from the source image. This is implemented as an * override of Object.clone(). We recommend using get() instead, * because it prevents you from needing to catch the * CloneNotSupportedException, and from doing a cast from the result. */ public Object clone() throws CloneNotSupportedException { // ignore PImage c = (PImage) super.clone(); // super.clone() will only copy the reference to the pixels // array, so this will do a proper duplication of it instead. c.pixels = new int[width * height]; System.arraycopy(pixels, 0, c.pixels, 0, pixels.length); // return the goods return c; } /** * Resize this image to a new width and height. * Use 0 for wide or high to make that dimension scale proportionally. */ public void resize(int wide, int high) { // ignore // Make sure that the pixels[] array is valid loadPixels(); if (wide <= 0 && high <= 0) { width = 0; // Gimme a break, don't waste my time height = 0; pixels = new int[0]; bitmap = null; } else { if (wide == 0) { // Use height to determine relative size float diff = (float) high / (float) height; wide = (int) (width * diff); } else if (high == 0) { // Use the width to determine relative size float diff = (float) wide / (float) width; high = (int) (height * diff); } PImage temp = new PImage(wide, high, this.format); temp.copy(this, 0, 0, width, height, 0, 0, wide, high); this.width = wide; this.height = high; this.pixels = temp.pixels; this.bitmap = null; } // Mark the pixels array as altered updatePixels(); } ////////////////////////////////////////////////////////////// // GET/SET PIXELS /** * Returns an ARGB "color" type (a packed 32 bit int with the color. * If the coordinate is outside the image, zero is returned * (black, but completely transparent). * <P> * If the image is in RGB format (i.e. on a PVideo object), * the value will get its high bits set, just to avoid cases where * they haven't been set already. * <P> * If the image is in ALPHA format, this returns a white with its * alpha value set. * <P> * This function is included primarily for beginners. It is quite * slow because it has to check to see if the x, y that was provided * is inside the bounds, and then has to check to see what image * type it is. If you want things to be more efficient, access the * pixels[] array directly. */ public int get(int x, int y) { if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return 0; if (pixels == null) { return bitmap.getPixel(x, y); } else { // If the pixels array exists, it's fairly safe to assume that it's // the most up to date, and that it's faster for access. switch (format) { case RGB: return pixels[y*width + x] | 0xff000000; case ARGB: return pixels[y*width + x]; case ALPHA: return (pixels[y*width + x] << 24) | 0xffffff; } } return 0; } /** * Grab a subsection of a PImage, and copy it into a fresh PImage. * As of release 0149, no longer honors imageMode() for the coordinates. */ public PImage get(int x, int y, int w, int h) { if (x < 0) { w += x; // clip off the left edge x = 0; } if (y < 0) { h += y; // clip off some of the height y = 0; } if (x + w > width) w = width - x; if (y + h > height) h = height - y; return getImpl(x, y, w, h); } /** * Internal function to actually handle getting a block of pixels that * has already been properly cropped to a valid region. That is, x/y/w/h * are guaranteed to be inside the image space, so the implementation can * use the fastest possible pixel copying method. */ protected PImage getImpl(int x, int y, int w, int h) { PImage newbie = new PImage(w, h, format); newbie.parent = parent; if (pixels == null) { bitmap.getPixels(newbie.pixels, 0, w, x, y, w, h); } else { int index = y*width + x; int index2 = 0; for (int row = y; row < y+h; row++) { System.arraycopy(pixels, index, newbie.pixels, index2, w); index += width; index2 += w; } } return newbie; } /** * Returns a copy of this PImage. Equivalent to get(0, 0, width, height). */ public PImage get() { try { return (PImage) clone(); } catch (CloneNotSupportedException e) { return null; } } /** * Set a single pixel to the specified color. */ public void set(int x, int y, int c) { if (pixels == null) { bitmap.setPixel(x, y, c); } else { if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return; pixels[y*width + x] = c; updatePixelsImpl(x, y, x+1, y+1); // slow? } } /** * Efficient method of drawing an image's pixels directly to this surface. * No variations are employed, meaning that any scale, tint, or imageMode * settings will be ignored. */ public void set(int x, int y, PImage src) { if (src.format == ALPHA) { // set() doesn't really make sense for an ALPHA image, since it // directly replaces pixels and does no blending. throw new RuntimeException("set() not available for ALPHA images"); } int sx = 0; int sy = 0; int sw = src.width; int sh = src.height; // if (imageMode == CENTER) { // x -= src.width/2; // y -= src.height/2; // } if (x < 0) { // off left edge sx -= x; sw += x; x = 0; } if (y < 0) { // off top edge sy -= y; sh += y; y = 0; } if (x + sw > width) { // off right edge sw = width - x; } if (y + sh > height) { // off bottom edge sh = height - y; } // this could be nonexistent if ((sw <= 0) || (sh <= 0)) return; setImpl(x, y, sx, sy, sw, sh, src); } /** * Internal function to actually handle setting a block of pixels that * has already been properly cropped from the image to a valid region. */ protected void setImpl(int dx, int dy, int sx, int sy, int sw, int sh, PImage src) { if (src.pixels == null) { src.loadPixels(); } // if this.pixels[] is null, copying directly into this.bitmap if (pixels == null) { // if this.pixels[] is null, this.bitmap cannot be null // make sure the bitmap is writable if (!bitmap.isMutable()) { // create a mutable version of this bitmap bitmap = bitmap.copy(Config.ARGB_8888, true); } // copy from src.pixels to this.bitmap int offset = sy * src.width + sx; bitmap.setPixels(src.pixels, offset, src.width, dx, dy, sw, sh); } else { // pixels != null // copy into this.pixels[] and mark as modified int srcOffset = sy * src.width + sx; int dstOffset = dy * width + dx; for (int y = sy; y < sy + sh; y++) { System.arraycopy(src.pixels, srcOffset, pixels, dstOffset, sw); srcOffset += src.width; dstOffset += width; } updatePixelsImpl(dx, dy, sw, sh); } } ////////////////////////////////////////////////////////////// // ALPHA CHANNEL /** * Set alpha channel for an image. Black colors in the source * image will make the destination image completely transparent, * and white will make things fully opaque. Gray values will * be in-between steps. * <P> * Strictly speaking the "blue" value from the source image is * used as the alpha color. For a fully grayscale image, this * is correct, but for a color image it's not 100% accurate. * For a more accurate conversion, first use filter(GRAY) * which will make the image into a "correct" grayscake by * performing a proper luminance-based conversion. */ public void mask(int alpha[]) { loadPixels(); // don't execute if mask image is different size if (alpha.length != pixels.length) { throw new RuntimeException("The PImage used with mask() must be " + "the same size as the applet."); } for (int i = 0; i < pixels.length; i++) { pixels[i] = ((alpha[i] & 0xff) << 24) | (pixels[i] & 0xffffff); } format = ARGB; updatePixels(); } /** * Set alpha channel for an image using another image as the source. */ public void mask(PImage alpha) { if (alpha.pixels == null) { // if pixels haven't been loaded by the user, then only load them // temporarily to save memory when finished. alpha.loadPixels(); mask(alpha.pixels); alpha.pixels = null; } else { mask(alpha.pixels); } } ////////////////////////////////////////////////////////////// // IMAGE FILTERS /** * Method to apply a variety of basic filters to this image. * <P> * <UL> * <LI>filter(BLUR) provides a basic blur. * <LI>filter(GRAY) converts the image to grayscale based on luminance. * <LI>filter(INVERT) will invert the color components in the image. * <LI>filter(OPAQUE) set all the high bits in the image to opaque * <LI>filter(THRESHOLD) converts the image to black and white. * <LI>filter(DILATE) grow white/light areas * <LI>filter(ERODE) shrink white/light areas * </UL> * Luminance conversion code contributed by * <A HREF="http://www.toxi.co.uk">toxi</A> * <P/> * Gaussian blur code contributed by * <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A> */ public void filter(int kind) { loadPixels(); switch (kind) { case BLUR: // TODO write basic low-pass filter blur here // what does photoshop do on the edges with this guy? // better yet.. why bother? just use gaussian with radius 1 filter(BLUR, 1); break; case GRAY: if (format == ALPHA) { // for an alpha image, convert it to an opaque grayscale for (int i = 0; i < pixels.length; i++) { int col = 255 - pixels[i]; pixels[i] = 0xff000000 | (col << 16) | (col << 8) | col; } format = RGB; } else { // Converts RGB image data into grayscale using // weighted RGB components, and keeps alpha channel intact. // [toxi 040115] for (int i = 0; i < pixels.length; i++) { int col = pixels[i]; // luminance = 0.3*red + 0.59*green + 0.11*blue // 0.30 * 256 = 77 // 0.59 * 256 = 151 // 0.11 * 256 = 28 int lum = (77*(col>>16&0xff) + 151*(col>>8&0xff) + 28*(col&0xff))>>8; pixels[i] = (col & ALPHA_MASK) | lum<<16 | lum<<8 | lum; } } break; case INVERT: for (int i = 0; i < pixels.length; i++) { //pixels[i] = 0xff000000 | pixels[i] ^= 0xffffff; } break; case POSTERIZE: throw new RuntimeException("Use filter(POSTERIZE, int levels) " + "instead of filter(POSTERIZE)"); case RGB: for (int i = 0; i < pixels.length; i++) { pixels[i] |= 0xff000000; } format = RGB; break; case THRESHOLD: filter(THRESHOLD, 0.5f); break; // [toxi20050728] added new filters case ERODE: dilate(true); break; case DILATE: dilate(false); break; } updatePixels(); // mark as modified } /** * Method to apply a variety of basic filters to this image. * These filters all take a parameter. * <P> * <UL> * <LI>filter(BLUR, int radius) performs a gaussian blur of the * specified radius. * <LI>filter(POSTERIZE, int levels) will posterize the image to * between 2 and 255 levels. * <LI>filter(THRESHOLD, float center) allows you to set the * center point for the threshold. It takes a value from 0 to 1.0. * </UL> * Gaussian blur code contributed by * <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A> * and later updated by toxi for better speed. */ public void filter(int kind, float param) { loadPixels(); switch (kind) { case BLUR: if (format == ALPHA) blurAlpha(param); else if (format == ARGB) blurARGB(param); else blurRGB(param); break; case GRAY: throw new RuntimeException("Use filter(GRAY) instead of " + "filter(GRAY, param)"); case INVERT: throw new RuntimeException("Use filter(INVERT) instead of " + "filter(INVERT, param)"); case OPAQUE: throw new RuntimeException("Use filter(OPAQUE) instead of " + "filter(OPAQUE, param)"); case POSTERIZE: int levels = (int)param; if ((levels < 2) || (levels > 255)) { throw new RuntimeException("Levels must be between 2 and 255 for " + "filter(POSTERIZE, levels)"); } int levels1 = levels - 1; for (int i = 0; i < pixels.length; i++) { int rlevel = (pixels[i] >> 16) & 0xff; int glevel = (pixels[i] >> 8) & 0xff; int blevel = pixels[i] & 0xff; rlevel = (((rlevel * levels) >> 8) * 255) / levels1; glevel = (((glevel * levels) >> 8) * 255) / levels1; blevel = (((blevel * levels) >> 8) * 255) / levels1; pixels[i] = ((0xff000000 & pixels[i]) | (rlevel << 16) | (glevel << 8) | blevel); } break; case THRESHOLD: // greater than or equal to the threshold int thresh = (int) (param * 255); for (int i = 0; i < pixels.length; i++) { int max = Math.max((pixels[i] & RED_MASK) >> 16, Math.max((pixels[i] & GREEN_MASK) >> 8, (pixels[i] & BLUE_MASK))); pixels[i] = (pixels[i] & ALPHA_MASK) | ((max < thresh) ? 0x000000 : 0xffffff); } break; // [toxi20050728] added new filters case ERODE: throw new RuntimeException("Use filter(ERODE) instead of " + "filter(ERODE, param)"); case DILATE: throw new RuntimeException("Use filter(DILATE) instead of " + "filter(DILATE, param)"); } updatePixels(); // mark as modified } /** * Optimized code for building the blur kernel. * further optimized blur code (approx. 15% for radius=20) * bigger speed gains for larger radii (~30%) * added support for various image types (ALPHA, RGB, ARGB) * [toxi 050728] */ protected void buildBlurKernel(float r) { int radius = (int) (r * 3.5f); radius = (radius < 1) ? 1 : ((radius < 248) ? radius : 248); if (blurRadius != radius) { blurRadius = radius; blurKernelSize = 1 + blurRadius<<1; blurKernel = new int[blurKernelSize]; blurMult = new int[blurKernelSize][256]; int bk,bki; int[] bm,bmi; for (int i = 1, radiusi = radius - 1; i < radius; i++) { blurKernel[radius+i] = blurKernel[radiusi] = bki = radiusi * radiusi; bm=blurMult[radius+i]; bmi=blurMult[radiusi--]; for (int j = 0; j < 256; j++) bm[j] = bmi[j] = bki*j; } bk = blurKernel[radius] = radius * radius; bm = blurMult[radius]; for (int j = 0; j < 256; j++) bm[j] = bk*j; } } protected void blurAlpha(float r) { int sum, cb; int read, ri, ym, ymi, bk0; int b2[] = new int[pixels.length]; int yi = 0; buildBlurKernel(r); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { //cb = cg = cr = sum = 0; cb = sum = 0; read = x - blurRadius; if (read<0) { bk0=-read; read=0; } else { if (read >= width) break; bk0=0; } for (int i = bk0; i < blurKernelSize; i++) { if (read >= width) break; int c = pixels[read + yi]; int[] bm=blurMult[i]; cb += bm[c & BLUE_MASK]; sum += blurKernel[i]; read++; } ri = yi + x; b2[ri] = cb / sum; } yi += width; } yi = 0; ym=-blurRadius; ymi=ym*width; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { //cb = cg = cr = sum = 0; cb = sum = 0; if (ym<0) { bk0 = ri = -ym; read = x; } else { if (ym >= height) break; bk0 = 0; ri = ym; read = x + ymi; } for (int i = bk0; i < blurKernelSize; i++) { if (ri >= height) break; int[] bm=blurMult[i]; cb += bm[b2[read]]; sum += blurKernel[i]; ri++; read += width; } pixels[x+yi] = (cb/sum); } yi += width; ymi += width; ym++; } } protected void blurRGB(float r) { int sum, cr, cg, cb; //, k; int /*pixel,*/ read, ri, /*roff,*/ ym, ymi, /*riw,*/ bk0; int r2[] = new int[pixels.length]; int g2[] = new int[pixels.length]; int b2[] = new int[pixels.length]; int yi = 0; buildBlurKernel(r); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { cb = cg = cr = sum = 0; read = x - blurRadius; if (read<0) { bk0=-read; read=0; } else { if (read >= width) break; bk0=0; } for (int i = bk0; i < blurKernelSize; i++) { if (read >= width) break; int c = pixels[read + yi]; int[] bm=blurMult[i]; cr += bm[(c & RED_MASK) >> 16]; cg += bm[(c & GREEN_MASK) >> 8]; cb += bm[c & BLUE_MASK]; sum += blurKernel[i]; read++; } ri = yi + x; r2[ri] = cr / sum; g2[ri] = cg / sum; b2[ri] = cb / sum; } yi += width; } yi = 0; ym=-blurRadius; ymi=ym*width; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { cb = cg = cr = sum = 0; if (ym<0) { bk0 = ri = -ym; read = x; } else { if (ym >= height) break; bk0 = 0; ri = ym; read = x + ymi; } for (int i = bk0; i < blurKernelSize; i++) { if (ri >= height) break; int[] bm=blurMult[i]; cr += bm[r2[read]]; cg += bm[g2[read]]; cb += bm[b2[read]]; sum += blurKernel[i]; ri++; read += width; } pixels[x+yi] = 0xff000000 | (cr/sum)<<16 | (cg/sum)<<8 | (cb/sum); } yi += width; ymi += width; ym++; } } protected void blurARGB(float r) { int sum, cr, cg, cb, ca; int /*pixel,*/ read, ri, /*roff,*/ ym, ymi, /*riw,*/ bk0; int wh = pixels.length; int r2[] = new int[wh]; int g2[] = new int[wh]; int b2[] = new int[wh]; int a2[] = new int[wh]; int yi = 0; buildBlurKernel(r); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { cb = cg = cr = ca = sum = 0; read = x - blurRadius; if (read<0) { bk0=-read; read=0; } else { if (read >= width) break; bk0=0; } for (int i = bk0; i < blurKernelSize; i++) { if (read >= width) break; int c = pixels[read + yi]; int[] bm=blurMult[i]; ca += bm[(c & ALPHA_MASK) >>> 24]; cr += bm[(c & RED_MASK) >> 16]; cg += bm[(c & GREEN_MASK) >> 8]; cb += bm[c & BLUE_MASK]; sum += blurKernel[i]; read++; } ri = yi + x; a2[ri] = ca / sum; r2[ri] = cr / sum; g2[ri] = cg / sum; b2[ri] = cb / sum; } yi += width; } yi = 0; ym=-blurRadius; ymi=ym*width; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { cb = cg = cr = ca = sum = 0; if (ym<0) { bk0 = ri = -ym; read = x; } else { if (ym >= height) break; bk0 = 0; ri = ym; read = x + ymi; } for (int i = bk0; i < blurKernelSize; i++) { if (ri >= height) break; int[] bm=blurMult[i]; ca += bm[a2[read]]; cr += bm[r2[read]]; cg += bm[g2[read]]; cb += bm[b2[read]]; sum += blurKernel[i]; ri++; read += width; } pixels[x+yi] = (ca/sum)<<24 | (cr/sum)<<16 | (cg/sum)<<8 | (cb/sum); } yi += width; ymi += width; ym++; } } /** * Generic dilate/erode filter using luminance values * as decision factor. [toxi 050728] */ protected void dilate(boolean isInverted) { int currIdx=0; int maxIdx=pixels.length; int[] out=new int[maxIdx]; if (!isInverted) { // erosion (grow light areas) while (currIdx<maxIdx) { int currRowIdx=currIdx; int maxRowIdx=currIdx+width; while (currIdx<maxRowIdx) { int colOrig,colOut; colOrig=colOut=pixels[currIdx]; int idxLeft=currIdx-1; int idxRight=currIdx+1; int idxUp=currIdx-width; int idxDown=currIdx+width; if (idxLeft<currRowIdx) idxLeft=currIdx; if (idxRight>=maxRowIdx) idxRight=currIdx; if (idxUp<0) idxUp=0; if (idxDown>=maxIdx) idxDown=currIdx; int colUp=pixels[idxUp]; int colLeft=pixels[idxLeft]; int colDown=pixels[idxDown]; int colRight=pixels[idxRight]; // compute luminance int currLum = 77*(colOrig>>16&0xff) + 151*(colOrig>>8&0xff) + 28*(colOrig&0xff); int lumLeft = 77*(colLeft>>16&0xff) + 151*(colLeft>>8&0xff) + 28*(colLeft&0xff); int lumRight = 77*(colRight>>16&0xff) + 151*(colRight>>8&0xff) + 28*(colRight&0xff); int lumUp = 77*(colUp>>16&0xff) + 151*(colUp>>8&0xff) + 28*(colUp&0xff); int lumDown = 77*(colDown>>16&0xff) + 151*(colDown>>8&0xff) + 28*(colDown&0xff); if (lumLeft>currLum) { colOut=colLeft; currLum=lumLeft; } if (lumRight>currLum) { colOut=colRight; currLum=lumRight; } if (lumUp>currLum) { colOut=colUp; currLum=lumUp; } if (lumDown>currLum) { colOut=colDown; currLum=lumDown; } out[currIdx++]=colOut; } } } else { // dilate (grow dark areas) while (currIdx<maxIdx) { int currRowIdx=currIdx; int maxRowIdx=currIdx+width; while (currIdx<maxRowIdx) { int colOrig,colOut; colOrig=colOut=pixels[currIdx]; int idxLeft=currIdx-1; int idxRight=currIdx+1; int idxUp=currIdx-width; int idxDown=currIdx+width; if (idxLeft<currRowIdx) idxLeft=currIdx; if (idxRight>=maxRowIdx) idxRight=currIdx; if (idxUp<0) idxUp=0; if (idxDown>=maxIdx) idxDown=currIdx; int colUp=pixels[idxUp]; int colLeft=pixels[idxLeft]; int colDown=pixels[idxDown]; int colRight=pixels[idxRight]; // compute luminance int currLum = 77*(colOrig>>16&0xff) + 151*(colOrig>>8&0xff) + 28*(colOrig&0xff); int lumLeft = 77*(colLeft>>16&0xff) + 151*(colLeft>>8&0xff) + 28*(colLeft&0xff); int lumRight = 77*(colRight>>16&0xff) + 151*(colRight>>8&0xff) + 28*(colRight&0xff); int lumUp = 77*(colUp>>16&0xff) + 151*(colUp>>8&0xff) + 28*(colUp&0xff); int lumDown = 77*(colDown>>16&0xff) + 151*(colDown>>8&0xff) + 28*(colDown&0xff); if (lumLeft<currLum) { colOut=colLeft; currLum=lumLeft; } if (lumRight<currLum) { colOut=colRight; currLum=lumRight; } if (lumUp<currLum) { colOut=colUp; currLum=lumUp; } if (lumDown<currLum) { colOut=colDown; currLum=lumDown; } out[currIdx++]=colOut; } } } System.arraycopy(out,0,pixels,0,maxIdx); } ////////////////////////////////////////////////////////////// // COPY /** * Copy things from one area of this image * to another area in the same image. */ public void copy(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { blend(this, sx, sy, sw, sh, dx, dy, dw, dh, REPLACE); } /** * Copies area of one image into another PImage object. */ public void copy(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { blend(src, sx, sy, sw, sh, dx, dy, dw, dh, REPLACE); } ////////////////////////////////////////////////////////////// // BLEND /** * Blend two colors based on a particular mode. * <UL> * <LI>REPLACE - destination colour equals colour of source pixel: C = A. * Sometimes called "Normal" or "Copy" in other software. * * <LI>BLEND - linear interpolation of colours: * <TT>C = A*factor + B</TT> * * <LI>ADD - additive blending with white clip: * <TT>C = min(A*factor + B, 255)</TT>. * Clipped to 0..255, Photoshop calls this "Linear Burn", * and Director calls it "Add Pin". * * <LI>SUBTRACT - substractive blend with black clip: * <TT>C = max(B - A*factor, 0)</TT>. * Clipped to 0..255, Photoshop calls this "Linear Dodge", * and Director calls it "Subtract Pin". * * <LI>DARKEST - only the darkest colour succeeds: * <TT>C = min(A*factor, B)</TT>. * Illustrator calls this "Darken". * * <LI>LIGHTEST - only the lightest colour succeeds: * <TT>C = max(A*factor, B)</TT>. * Illustrator calls this "Lighten". * * <LI>DIFFERENCE - subtract colors from underlying image. * * <LI>EXCLUSION - similar to DIFFERENCE, but less extreme. * * <LI>MULTIPLY - Multiply the colors, result will always be darker. * * <LI>SCREEN - Opposite multiply, uses inverse values of the colors. * * <LI>OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, * and screens light values. * * <LI>HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower. * * <LI>SOFT_LIGHT - Mix of DARKEST and LIGHTEST. * Works like OVERLAY, but not as harsh. * * <LI>DODGE - Lightens light tones and increases contrast, ignores darks. * Called "Color Dodge" in Illustrator and Photoshop. * * <LI>BURN - Darker areas are applied, increasing contrast, ignores lights. * Called "Color Burn" in Illustrator and Photoshop. * </UL> * <P>A useful reference for blending modes and their algorithms can be * found in the <A HREF="http://www.w3.org/TR/SVG12/rendering.html">SVG</A> * specification.</P> * <P>It is important to note that Processing uses "fast" code, not * necessarily "correct" code. No biggie, most software does. A nitpicker * can find numerous "off by 1 division" problems in the blend code where * <TT>&gt;&gt;8</TT> or <TT>&gt;&gt;7</TT> is used when strictly speaking * <TT>/255.0</T> or <TT>/127.0</TT> should have been used.</P> * <P>For instance, exclusion (not intended for real-time use) reads * <TT>r1 + r2 - ((2 * r1 * r2) / 255)</TT> because <TT>255 == 1.0</TT> * not <TT>256 == 1.0</TT>. In other words, <TT>(255*255)>>8</TT> is not * the same as <TT>(255*255)/255</TT>. But for real-time use the shifts * are preferrable, and the difference is insignificant for applications * built with Processing.</P> */ static public int blendColor(int c1, int c2, int mode) { switch (mode) { case REPLACE: return c2; case BLEND: return blend_blend(c1, c2); case ADD: return blend_add_pin(c1, c2); case SUBTRACT: return blend_sub_pin(c1, c2); case LIGHTEST: return blend_lightest(c1, c2); case DARKEST: return blend_darkest(c1, c2); case DIFFERENCE: return blend_difference(c1, c2); case EXCLUSION: return blend_exclusion(c1, c2); case MULTIPLY: return blend_multiply(c1, c2); case SCREEN: return blend_screen(c1, c2); case HARD_LIGHT: return blend_hard_light(c1, c2); case SOFT_LIGHT: return blend_soft_light(c1, c2); case OVERLAY: return blend_overlay(c1, c2); case DODGE: return blend_dodge(c1, c2); case BURN: return blend_burn(c1, c2); } return 0; } /** * Blends one area of this image to another area. * @see processing.core.PImage#blendColor(int,int,int) */ public void blend(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { blend(this, sx, sy, sw, sh, dx, dy, dw, dh, mode); } /** * Copies area of one image into another PImage object. * @see processing.core.PImage#blendColor(int,int,int) */ public void blend(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { /* if (imageMode == CORNER) { // if CORNERS, do nothing sx2 += sx1; sy2 += sy1; dx2 += dx1; dy2 += dy1; } else if (imageMode == CENTER) { sx1 -= sx2 / 2f; sy1 -= sy2 / 2f; sx2 += sx1; sy2 += sy1; dx1 -= dx2 / 2f; dy1 -= dy2 / 2f; dx2 += dx1; dy2 += dy1; } */ int sx2 = sx + sw; int sy2 = sy + sh; int dx2 = dx + dw; int dy2 = dy + dh; loadPixels(); if (src == this) { if (intersect(sx, sy, sx2, sy2, dx, dy, dx2, dy2)) { blit_resize(get(sx, sy, sx2 - sx, sy2 - sy), 0, 0, sx2 - sx - 1, sy2 - sy - 1, pixels, width, height, dx, dy, dx2, dy2, mode); } else { // same as below, except skip the loadPixels() because it'd be redundant blit_resize(src, sx, sy, sx2, sy2, pixels, width, height, dx, dy, dx2, dy2, mode); } } else { src.loadPixels(); blit_resize(src, sx, sy, sx2, sy2, pixels, width, height, dx, dy, dx2, dy2, mode); //src.updatePixels(); } updatePixels(); } /** * Check to see if two rectangles intersect one another */ private boolean intersect(int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2) { int sw = sx2 - sx1 + 1; int sh = sy2 - sy1 + 1; int dw = dx2 - dx1 + 1; int dh = dy2 - dy1 + 1; if (dx1 < sx1) { dw += dx1 - sx1; if (dw > sw) { dw = sw; } } else { int w = sw + sx1 - dx1; if (dw > w) { dw = w; } } if (dy1 < sy1) { dh += dy1 - sy1; if (dh > sh) { dh = sh; } } else { int h = sh + sy1 - dy1; if (dh > h) { dh = h; } } return !(dw <= 0 || dh <= 0); } ////////////////////////////////////////////////////////////// /** * Internal blitter/resizer/copier from toxi. * Uses bilinear filtering if smooth() has been enabled * 'mode' determines the blending mode used in the process. */ private void blit_resize(PImage img, int srcX1, int srcY1, int srcX2, int srcY2, int[] destPixels, int screenW, int screenH, int destX1, int destY1, int destX2, int destY2, int mode) { if (srcX1 < 0) srcX1 = 0; if (srcY1 < 0) srcY1 = 0; - if (srcX2 >= img.width) srcX2 = img.width - 1; - if (srcY2 >= img.height) srcY2 = img.height - 1; + if (srcX2 > img.width) srcX2 = img.width; + if (srcY2 > img.height) srcY2 = img.height; int srcW = srcX2 - srcX1; int srcH = srcY2 - srcY1; int destW = destX2 - destX1; int destH = destY2 - destY1; boolean smooth = true; // may as well go with the smoothing these days if (!smooth) { srcW++; srcH++; } if (destW <= 0 || destH <= 0 || srcW <= 0 || srcH <= 0 || destX1 >= screenW || destY1 >= screenH || srcX1 >= img.width || srcY1 >= img.height) { return; } int dx = (int) (srcW / (float) destW * PRECISIONF); int dy = (int) (srcH / (float) destH * PRECISIONF); srcXOffset = (int) (destX1 < 0 ? -destX1 * dx : srcX1 * PRECISIONF); srcYOffset = (int) (destY1 < 0 ? -destY1 * dy : srcY1 * PRECISIONF); if (destX1 < 0) { destW += destX1; destX1 = 0; } if (destY1 < 0) { destH += destY1; destY1 = 0; } destW = low(destW, screenW - destX1); destH = low(destH, screenH - destY1); int destOffset = destY1 * screenW + destX1; srcBuffer = img.pixels; if (smooth) { // use bilinear filtering iw = img.width; iw1 = img.width - 1; ih1 = img.height - 1; switch (mode) { case BLEND: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { // davbol - renamed old blend_multiply to blend_blend destPixels[destOffset + x] = blend_blend(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case ADD: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_add_pin(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SUBTRACT: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_sub_pin(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case LIGHTEST: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_lightest(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DARKEST: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_darkest(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case REPLACE: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = filter_bilinear(); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DIFFERENCE: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_difference(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case EXCLUSION: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_exclusion(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case MULTIPLY: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_multiply(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SCREEN: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_screen(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case OVERLAY: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_overlay(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case HARD_LIGHT: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_hard_light(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SOFT_LIGHT: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_soft_light(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; // davbol - proposed 2007-01-09 case DODGE: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_dodge(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case BURN: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_burn(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; } } else { // nearest neighbour scaling (++fast!) switch (mode) { case BLEND: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { // davbol - renamed old blend_multiply to blend_blend destPixels[destOffset + x] = blend_blend(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case ADD: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_add_pin(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SUBTRACT: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_sub_pin(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case LIGHTEST: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_lightest(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DARKEST: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_darkest(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case REPLACE: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = srcBuffer[sY + (sX >> PRECISIONB)]; sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DIFFERENCE: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_difference(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case EXCLUSION: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_exclusion(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case MULTIPLY: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_multiply(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SCREEN: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_screen(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case OVERLAY: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_overlay(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case HARD_LIGHT: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_hard_light(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SOFT_LIGHT: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_soft_light(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; // davbol - proposed 2007-01-09 case DODGE: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_dodge(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case BURN: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_burn(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; } } } private void filter_new_scanline() { sX = srcXOffset; fracV = srcYOffset & PREC_MAXVAL; ifV = PREC_MAXVAL - fracV; v1 = (srcYOffset >> PRECISIONB) * iw; v2 = low((srcYOffset >> PRECISIONB) + 1, ih1) * iw; } private int filter_bilinear() { fracU = sX & PREC_MAXVAL; ifU = PREC_MAXVAL - fracU; ul = (ifU * ifV) >> PRECISIONB; ll = (ifU * fracV) >> PRECISIONB; ur = (fracU * ifV) >> PRECISIONB; lr = (fracU * fracV) >> PRECISIONB; u1 = (sX >> PRECISIONB); u2 = low(u1 + 1, iw1); // get color values of the 4 neighbouring texels cUL = srcBuffer[v1 + u1]; cUR = srcBuffer[v1 + u2]; cLL = srcBuffer[v2 + u1]; cLR = srcBuffer[v2 + u2]; r = ((ul*((cUL&RED_MASK)>>16) + ll*((cLL&RED_MASK)>>16) + ur*((cUR&RED_MASK)>>16) + lr*((cLR&RED_MASK)>>16)) << PREC_RED_SHIFT) & RED_MASK; g = ((ul*(cUL&GREEN_MASK) + ll*(cLL&GREEN_MASK) + ur*(cUR&GREEN_MASK) + lr*(cLR&GREEN_MASK)) >>> PRECISIONB) & GREEN_MASK; b = (ul*(cUL&BLUE_MASK) + ll*(cLL&BLUE_MASK) + ur*(cUR&BLUE_MASK) + lr*(cLR&BLUE_MASK)) >>> PRECISIONB; a = ((ul*((cUL&ALPHA_MASK)>>>24) + ll*((cLL&ALPHA_MASK)>>>24) + ur*((cUR&ALPHA_MASK)>>>24) + lr*((cLR&ALPHA_MASK)>>>24)) << PREC_ALPHA_SHIFT) & ALPHA_MASK; return a | r | g | b; } ////////////////////////////////////////////////////////////// // internal blending methods private static int low(int a, int b) { return (a < b) ? a : b; } private static int high(int a, int b) { return (a > b) ? a : b; } // davbol - added peg helper, equiv to constrain(n,0,255) private static int peg(int n) { return (n < 0) ? 0 : ((n > 255) ? 255 : n); } private static int mix(int a, int b, int f) { return a + (((b - a) * f) >> 8); } ///////////////////////////////////////////////////////////// // BLEND MODE IMPLEMENTIONS private static int blend_blend(int a, int b) { int f = (b & ALPHA_MASK) >>> 24; return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | mix(a & RED_MASK, b & RED_MASK, f) & RED_MASK | mix(a & GREEN_MASK, b & GREEN_MASK, f) & GREEN_MASK | mix(a & BLUE_MASK, b & BLUE_MASK, f)); } /** * additive blend with clipping */ private static int blend_add_pin(int a, int b) { int f = (b & ALPHA_MASK) >>> 24; return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | low(((a & RED_MASK) + ((b & RED_MASK) >> 8) * f), RED_MASK) & RED_MASK | low(((a & GREEN_MASK) + ((b & GREEN_MASK) >> 8) * f), GREEN_MASK) & GREEN_MASK | low((a & BLUE_MASK) + (((b & BLUE_MASK) * f) >> 8), BLUE_MASK)); } /** * subtractive blend with clipping */ private static int blend_sub_pin(int a, int b) { int f = (b & ALPHA_MASK) >>> 24; return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | high(((a & RED_MASK) - ((b & RED_MASK) >> 8) * f), GREEN_MASK) & RED_MASK | high(((a & GREEN_MASK) - ((b & GREEN_MASK) >> 8) * f), BLUE_MASK) & GREEN_MASK | high((a & BLUE_MASK) - (((b & BLUE_MASK) * f) >> 8), 0)); } /** * only returns the blended lightest colour */ private static int blend_lightest(int a, int b) { int f = (b & ALPHA_MASK) >>> 24; return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | high(a & RED_MASK, ((b & RED_MASK) >> 8) * f) & RED_MASK | high(a & GREEN_MASK, ((b & GREEN_MASK) >> 8) * f) & GREEN_MASK | high(a & BLUE_MASK, ((b & BLUE_MASK) * f) >> 8)); } /** * only returns the blended darkest colour */ private static int blend_darkest(int a, int b) { int f = (b & ALPHA_MASK) >>> 24; return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | mix(a & RED_MASK, low(a & RED_MASK, ((b & RED_MASK) >> 8) * f), f) & RED_MASK | mix(a & GREEN_MASK, low(a & GREEN_MASK, ((b & GREEN_MASK) >> 8) * f), f) & GREEN_MASK | mix(a & BLUE_MASK, low(a & BLUE_MASK, ((b & BLUE_MASK) * f) >> 8), f)); } /** * returns the absolute value of the difference of the input colors * C = |A - B| */ private static int blend_difference(int a, int b) { // setup (this portion will always be the same) int f = (b & ALPHA_MASK) >>> 24; int ar = (a & RED_MASK) >> 16; int ag = (a & GREEN_MASK) >> 8; int ab = (a & BLUE_MASK); int br = (b & RED_MASK) >> 16; int bg = (b & GREEN_MASK) >> 8; int bb = (b & BLUE_MASK); // formula: int cr = (ar > br) ? (ar-br) : (br-ar); int cg = (ag > bg) ? (ag-bg) : (bg-ag); int cb = (ab > bb) ? (ab-bb) : (bb-ab); // alpha blend (this portion will always be the same) return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (peg(ar + (((cr - ar) * f) >> 8)) << 16) | (peg(ag + (((cg - ag) * f) >> 8)) << 8) | (peg(ab + (((cb - ab) * f) >> 8)) ) ); } /** * Cousin of difference, algorithm used here is based on a Lingo version * found here: http://www.mediamacros.com/item/item-1006687616/ * (Not yet verified to be correct). */ private static int blend_exclusion(int a, int b) { // setup (this portion will always be the same) int f = (b & ALPHA_MASK) >>> 24; int ar = (a & RED_MASK) >> 16; int ag = (a & GREEN_MASK) >> 8; int ab = (a & BLUE_MASK); int br = (b & RED_MASK) >> 16; int bg = (b & GREEN_MASK) >> 8; int bb = (b & BLUE_MASK); // formula: int cr = ar + br - ((ar * br) >> 7); int cg = ag + bg - ((ag * bg) >> 7); int cb = ab + bb - ((ab * bb) >> 7); // alpha blend (this portion will always be the same) return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (peg(ar + (((cr - ar) * f) >> 8)) << 16) | (peg(ag + (((cg - ag) * f) >> 8)) << 8) | (peg(ab + (((cb - ab) * f) >> 8)) ) ); } /** * returns the product of the input colors * C = A * B */ private static int blend_multiply(int a, int b) { // setup (this portion will always be the same) int f = (b & ALPHA_MASK) >>> 24; int ar = (a & RED_MASK) >> 16; int ag = (a & GREEN_MASK) >> 8; int ab = (a & BLUE_MASK); int br = (b & RED_MASK) >> 16; int bg = (b & GREEN_MASK) >> 8; int bb = (b & BLUE_MASK); // formula: int cr = (ar * br) >> 8; int cg = (ag * bg) >> 8; int cb = (ab * bb) >> 8; // alpha blend (this portion will always be the same) return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (peg(ar + (((cr - ar) * f) >> 8)) << 16) | (peg(ag + (((cg - ag) * f) >> 8)) << 8) | (peg(ab + (((cb - ab) * f) >> 8)) ) ); } /** * returns the inverse of the product of the inverses of the input colors * (the inverse of multiply). C = 1 - (1-A) * (1-B) */ private static int blend_screen(int a, int b) { // setup (this portion will always be the same) int f = (b & ALPHA_MASK) >>> 24; int ar = (a & RED_MASK) >> 16; int ag = (a & GREEN_MASK) >> 8; int ab = (a & BLUE_MASK); int br = (b & RED_MASK) >> 16; int bg = (b & GREEN_MASK) >> 8; int bb = (b & BLUE_MASK); // formula: int cr = 255 - (((255 - ar) * (255 - br)) >> 8); int cg = 255 - (((255 - ag) * (255 - bg)) >> 8); int cb = 255 - (((255 - ab) * (255 - bb)) >> 8); // alpha blend (this portion will always be the same) return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (peg(ar + (((cr - ar) * f) >> 8)) << 16) | (peg(ag + (((cg - ag) * f) >> 8)) << 8) | (peg(ab + (((cb - ab) * f) >> 8)) ) ); } /** * returns either multiply or screen for darker or lighter values of A * (the inverse of hard light) * C = * A < 0.5 : 2 * A * B * A >=0.5 : 1 - (2 * (255-A) * (255-B)) */ private static int blend_overlay(int a, int b) { // setup (this portion will always be the same) int f = (b & ALPHA_MASK) >>> 24; int ar = (a & RED_MASK) >> 16; int ag = (a & GREEN_MASK) >> 8; int ab = (a & BLUE_MASK); int br = (b & RED_MASK) >> 16; int bg = (b & GREEN_MASK) >> 8; int bb = (b & BLUE_MASK); // formula: int cr = (ar < 128) ? ((ar*br)>>7) : (255-(((255-ar)*(255-br))>>7)); int cg = (ag < 128) ? ((ag*bg)>>7) : (255-(((255-ag)*(255-bg))>>7)); int cb = (ab < 128) ? ((ab*bb)>>7) : (255-(((255-ab)*(255-bb))>>7)); // alpha blend (this portion will always be the same) return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (peg(ar + (((cr - ar) * f) >> 8)) << 16) | (peg(ag + (((cg - ag) * f) >> 8)) << 8) | (peg(ab + (((cb - ab) * f) >> 8)) ) ); } /** * returns either multiply or screen for darker or lighter values of B * (the inverse of overlay) * C = * B < 0.5 : 2 * A * B * B >=0.5 : 1 - (2 * (255-A) * (255-B)) */ private static int blend_hard_light(int a, int b) { // setup (this portion will always be the same) int f = (b & ALPHA_MASK) >>> 24; int ar = (a & RED_MASK) >> 16; int ag = (a & GREEN_MASK) >> 8; int ab = (a & BLUE_MASK); int br = (b & RED_MASK) >> 16; int bg = (b & GREEN_MASK) >> 8; int bb = (b & BLUE_MASK); // formula: int cr = (br < 128) ? ((ar*br)>>7) : (255-(((255-ar)*(255-br))>>7)); int cg = (bg < 128) ? ((ag*bg)>>7) : (255-(((255-ag)*(255-bg))>>7)); int cb = (bb < 128) ? ((ab*bb)>>7) : (255-(((255-ab)*(255-bb))>>7)); // alpha blend (this portion will always be the same) return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (peg(ar + (((cr - ar) * f) >> 8)) << 16) | (peg(ag + (((cg - ag) * f) >> 8)) << 8) | (peg(ab + (((cb - ab) * f) >> 8)) ) ); } /** * returns the inverse multiply plus screen, which simplifies to * C = 2AB + A^2 - 2A^2B */ private static int blend_soft_light(int a, int b) { // setup (this portion will always be the same) int f = (b & ALPHA_MASK) >>> 24; int ar = (a & RED_MASK) >> 16; int ag = (a & GREEN_MASK) >> 8; int ab = (a & BLUE_MASK); int br = (b & RED_MASK) >> 16; int bg = (b & GREEN_MASK) >> 8; int bb = (b & BLUE_MASK); // formula: int cr = ((ar*br)>>7) + ((ar*ar)>>8) - ((ar*ar*br)>>15); int cg = ((ag*bg)>>7) + ((ag*ag)>>8) - ((ag*ag*bg)>>15); int cb = ((ab*bb)>>7) + ((ab*ab)>>8) - ((ab*ab*bb)>>15); // alpha blend (this portion will always be the same) return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (peg(ar + (((cr - ar) * f) >> 8)) << 16) | (peg(ag + (((cg - ag) * f) >> 8)) << 8) | (peg(ab + (((cb - ab) * f) >> 8)) ) ); } /** * Returns the first (underlay) color divided by the inverse of * the second (overlay) color. C = A / (255-B) */ private static int blend_dodge(int a, int b) { // setup (this portion will always be the same) int f = (b & ALPHA_MASK) >>> 24; int ar = (a & RED_MASK) >> 16; int ag = (a & GREEN_MASK) >> 8; int ab = (a & BLUE_MASK); int br = (b & RED_MASK) >> 16; int bg = (b & GREEN_MASK) >> 8; int bb = (b & BLUE_MASK); // formula: int cr = (br==255) ? 255 : peg((ar << 8) / (255 - br)); // division requires pre-peg()-ing int cg = (bg==255) ? 255 : peg((ag << 8) / (255 - bg)); // " int cb = (bb==255) ? 255 : peg((ab << 8) / (255 - bb)); // " // alpha blend (this portion will always be the same) return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (peg(ar + (((cr - ar) * f) >> 8)) << 16) | (peg(ag + (((cg - ag) * f) >> 8)) << 8) | (peg(ab + (((cb - ab) * f) >> 8)) ) ); } /** * returns the inverse of the inverse of the first (underlay) color * divided by the second (overlay) color. C = 255 - (255-A) / B */ private static int blend_burn(int a, int b) { // setup (this portion will always be the same) int f = (b & ALPHA_MASK) >>> 24; int ar = (a & RED_MASK) >> 16; int ag = (a & GREEN_MASK) >> 8; int ab = (a & BLUE_MASK); int br = (b & RED_MASK) >> 16; int bg = (b & GREEN_MASK) >> 8; int bb = (b & BLUE_MASK); // formula: int cr = (br==0) ? 0 : 255 - peg(((255 - ar) << 8) / br); // division requires pre-peg()-ing int cg = (bg==0) ? 0 : 255 - peg(((255 - ag) << 8) / bg); // " int cb = (bb==0) ? 0 : 255 - peg(((255 - ab) << 8) / bb); // " // alpha blend (this portion will always be the same) return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | (peg(ar + (((cr - ar) * f) >> 8)) << 16) | (peg(ag + (((cg - ag) * f) >> 8)) << 8) | (peg(ab + (((cb - ab) * f) >> 8)) ) ); } ////////////////////////////////////////////////////////////// // FILE I/O static byte TIFF_HEADER[] = { 77, 77, 0, 42, 0, 0, 0, 8, 0, 9, 0, -2, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 0, 3, 0, 0, 0, 3, 0, 0, 0, 122, 1, 6, 0, 3, 0, 0, 0, 1, 0, 2, 0, 0, 1, 17, 0, 4, 0, 0, 0, 1, 0, 0, 3, 0, 1, 21, 0, 3, 0, 0, 0, 1, 0, 3, 0, 0, 1, 22, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 1, 23, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 8, 0, 8 }; static final String TIFF_ERROR = "Error: Processing can only read its own TIFF files."; static protected PImage loadTIFF(byte tiff[]) { if ((tiff[42] != tiff[102]) || // width/height in both places (tiff[43] != tiff[103])) { System.err.println(TIFF_ERROR); return null; } int width = ((tiff[30] & 0xff) << 8) | (tiff[31] & 0xff); int height = ((tiff[42] & 0xff) << 8) | (tiff[43] & 0xff); int count = ((tiff[114] & 0xff) << 24) | ((tiff[115] & 0xff) << 16) | ((tiff[116] & 0xff) << 8) | (tiff[117] & 0xff); if (count != width * height * 3) { System.err.println(TIFF_ERROR + " (" + width + ", " + height +")"); return null; } // check the rest of the header for (int i = 0; i < TIFF_HEADER.length; i++) { if ((i == 30) || (i == 31) || (i == 42) || (i == 43) || (i == 102) || (i == 103) || (i == 114) || (i == 115) || (i == 116) || (i == 117)) continue; if (tiff[i] != TIFF_HEADER[i]) { System.err.println(TIFF_ERROR + " (" + i + ")"); return null; } } PImage outgoing = new PImage(width, height, RGB); int index = 768; count /= 3; for (int i = 0; i < count; i++) { outgoing.pixels[i] = 0xFF000000 | (tiff[index++] & 0xff) << 16 | (tiff[index++] & 0xff) << 8 | (tiff[index++] & 0xff); } return outgoing; } protected boolean saveTIFF(OutputStream output) { // shutting off the warning, people can figure this out themselves /* if (format != RGB) { System.err.println("Warning: only RGB information is saved with " + ".tif files. Use .tga or .png for ARGB images and others."); } */ try { byte tiff[] = new byte[768]; System.arraycopy(TIFF_HEADER, 0, tiff, 0, TIFF_HEADER.length); tiff[30] = (byte) ((width >> 8) & 0xff); tiff[31] = (byte) ((width) & 0xff); tiff[42] = tiff[102] = (byte) ((height >> 8) & 0xff); tiff[43] = tiff[103] = (byte) ((height) & 0xff); int count = width*height*3; tiff[114] = (byte) ((count >> 24) & 0xff); tiff[115] = (byte) ((count >> 16) & 0xff); tiff[116] = (byte) ((count >> 8) & 0xff); tiff[117] = (byte) ((count) & 0xff); // spew the header to the disk output.write(tiff); for (int i = 0; i < pixels.length; i++) { output.write((pixels[i] >> 16) & 0xff); output.write((pixels[i] >> 8) & 0xff); output.write(pixels[i] & 0xff); } output.flush(); return true; } catch (IOException e) { e.printStackTrace(); } return false; } /** * Creates a Targa32 formatted byte sequence of specified * pixel buffer using RLE compression. * </p> * Also figured out how to avoid parsing the image upside-down * (there's a header flag to set the image origin to top-left) * </p> * Starting with revision 0092, the format setting is taken into account: * <UL> * <LI><TT>ALPHA</TT> images written as 8bit grayscale (uses lowest byte) * <LI><TT>RGB</TT> &rarr; 24 bits * <LI><TT>ARGB</TT> &rarr; 32 bits * </UL> * All versions are RLE compressed. * </p> * Contributed by toxi 8-10 May 2005, based on this RLE * <A HREF="http://www.wotsit.org/download.asp?f=tga">specification</A> */ protected boolean saveTGA(OutputStream output) { byte header[] = new byte[18]; if (format == ALPHA) { // save ALPHA images as 8bit grayscale header[2] = 0x0B; header[16] = 0x08; header[17] = 0x28; } else if (format == RGB) { header[2] = 0x0A; header[16] = 24; header[17] = 0x20; } else if (format == ARGB) { header[2] = 0x0A; header[16] = 32; header[17] = 0x28; } else { throw new RuntimeException("Image format not recognized inside save()"); } // set image dimensions lo-hi byte order header[12] = (byte) (width & 0xff); header[13] = (byte) (width >> 8); header[14] = (byte) (height & 0xff); header[15] = (byte) (height >> 8); try { output.write(header); int maxLen = height * width; int index = 0; int col; //, prevCol; int[] currChunk = new int[128]; // 8bit image exporter is in separate loop // to avoid excessive conditionals... if (format == ALPHA) { while (index < maxLen) { boolean isRLE = false; int rle = 1; currChunk[0] = col = pixels[index] & 0xff; while (index + rle < maxLen) { if (col != (pixels[index + rle]&0xff) || rle == 128) { isRLE = (rle > 1); break; } rle++; } if (isRLE) { output.write(0x80 | (rle - 1)); output.write(col); } else { rle = 1; while (index + rle < maxLen) { int cscan = pixels[index + rle] & 0xff; if ((col != cscan && rle < 128) || rle < 3) { currChunk[rle] = col = cscan; } else { if (col == cscan) rle -= 2; break; } rle++; } output.write(rle - 1); for (int i = 0; i < rle; i++) output.write(currChunk[i]); } index += rle; } } else { // export 24/32 bit TARGA while (index < maxLen) { boolean isRLE = false; currChunk[0] = col = pixels[index]; int rle = 1; // try to find repeating bytes (min. len = 2 pixels) // maximum chunk size is 128 pixels while (index + rle < maxLen) { if (col != pixels[index + rle] || rle == 128) { isRLE = (rle > 1); // set flag for RLE chunk break; } rle++; } if (isRLE) { output.write(128 | (rle - 1)); output.write(col & 0xff); output.write(col >> 8 & 0xff); output.write(col >> 16 & 0xff); if (format == ARGB) output.write(col >>> 24 & 0xff); } else { // not RLE rle = 1; while (index + rle < maxLen) { if ((col != pixels[index + rle] && rle < 128) || rle < 3) { currChunk[rle] = col = pixels[index + rle]; } else { // check if the exit condition was the start of // a repeating colour if (col == pixels[index + rle]) rle -= 2; break; } rle++; } // write uncompressed chunk output.write(rle - 1); if (format == ARGB) { for (int i = 0; i < rle; i++) { col = currChunk[i]; output.write(col & 0xff); output.write(col >> 8 & 0xff); output.write(col >> 16 & 0xff); output.write(col >>> 24 & 0xff); } } else { for (int i = 0; i < rle; i++) { col = currChunk[i]; output.write(col & 0xff); output.write(col >> 8 & 0xff); output.write(col >> 16 & 0xff); } } } index += rle; } } output.flush(); return true; } catch (IOException e) { e.printStackTrace(); return false; } } /** * Use ImageIO functions from Java 1.4 and later to handle image save. * Various formats are supported, typically jpeg, png, bmp, and wbmp. * To get a list of the supported formats for writing, use: <BR> * <TT>println(javax.imageio.ImageIO.getReaderFormatNames())</TT> */ // protected void saveImageIO(String path) throws IOException { // try { // BufferedImage bimage = // new BufferedImage(width, height, (format == ARGB) ? // BufferedImage.TYPE_INT_ARGB : // BufferedImage.TYPE_INT_RGB); // // bimage.setRGB(0, 0, width, height, pixels, 0, width); // // File file = new File(path); // String extension = path.substring(path.lastIndexOf('.') + 1); // // ImageIO.write(bimage, extension, file); // // } catch (Exception e) { // e.printStackTrace(); // throw new IOException("image save failed."); // } // } protected String[] saveImageFormats; /** * Save this image to disk. * <p> * As of revision 0100, this function requires an absolute path, * in order to avoid confusion. To save inside the sketch folder, * use the function savePath() from PApplet, or use saveFrame() instead. * As of revision 0116, savePath() is not needed if this object has been * created (as recommended) via createImage() or createGraphics() or * one of its neighbors. * <p> * As of revision 0115, when using Java 1.4 and later, you can write * to several formats besides tga and tiff. If Java 1.4 is installed * and the extension used is supported (usually png, jpg, jpeg, bmp, * and tiff), then those methods will be used to write the image. * To get a list of the supported formats for writing, use: <BR> * <TT>println(javax.imageio.ImageIO.getReaderFormatNames())</TT> * <p> * To use the original built-in image writers, use .tga or .tif as the * extension, or don't include an extension. When no extension is used, * the extension .tif will be added to the file name. * <p> * The ImageIO API claims to support wbmp files, however they probably * require a black and white image. Basic testing produced a zero-length * file with no error. */ public void save(String path) { // ignore boolean success = false; // File file = new File(path); // if (!file.isAbsolute()) { // if (parent != null) { // //file = new File(parent.savePath(filename)); // path = parent.savePath(path); // } else { // String msg = "PImage.save() requires an absolute path. " + // "Use createImage(), or pass savePath() to save()."; // PGraphics.showException(msg); // } // } // Make sure the pixel data is ready to go loadPixels(); try { OutputStream output = new BufferedOutputStream(parent.createOutput(path), 16 * 1024); String lower = path.toLowerCase(); String extension = lower.substring(lower.lastIndexOf('.') + 1); if (extension.equals("jpg") || extension.equals("jpeg")) { // TODO probably not necessary to create another bitmap Bitmap outgoing = Bitmap.createBitmap(pixels, width, height, Config.ARGB_8888); success = outgoing.compress(CompressFormat.JPEG, 100, output); } else if (extension.equals("png")) { Bitmap outgoing = Bitmap.createBitmap(pixels, width, height, Config.ARGB_8888); success = outgoing.compress(CompressFormat.PNG, 100, output); } else if (extension.equals("tga")) { success = saveTGA(output); //, pixels, width, height, format); } else { if (!extension.equals("tif") && !extension.equals("tiff")) { // if no .tif extension, add it.. path += ".tif"; } success = saveTIFF(output); } output.flush(); output.close(); } catch (IOException e) { e.printStackTrace(); } if (!success) { System.err.println("Could not write the image to " + path); } //return success; } }
true
true
private void blit_resize(PImage img, int srcX1, int srcY1, int srcX2, int srcY2, int[] destPixels, int screenW, int screenH, int destX1, int destY1, int destX2, int destY2, int mode) { if (srcX1 < 0) srcX1 = 0; if (srcY1 < 0) srcY1 = 0; if (srcX2 >= img.width) srcX2 = img.width - 1; if (srcY2 >= img.height) srcY2 = img.height - 1; int srcW = srcX2 - srcX1; int srcH = srcY2 - srcY1; int destW = destX2 - destX1; int destH = destY2 - destY1; boolean smooth = true; // may as well go with the smoothing these days if (!smooth) { srcW++; srcH++; } if (destW <= 0 || destH <= 0 || srcW <= 0 || srcH <= 0 || destX1 >= screenW || destY1 >= screenH || srcX1 >= img.width || srcY1 >= img.height) { return; } int dx = (int) (srcW / (float) destW * PRECISIONF); int dy = (int) (srcH / (float) destH * PRECISIONF); srcXOffset = (int) (destX1 < 0 ? -destX1 * dx : srcX1 * PRECISIONF); srcYOffset = (int) (destY1 < 0 ? -destY1 * dy : srcY1 * PRECISIONF); if (destX1 < 0) { destW += destX1; destX1 = 0; } if (destY1 < 0) { destH += destY1; destY1 = 0; } destW = low(destW, screenW - destX1); destH = low(destH, screenH - destY1); int destOffset = destY1 * screenW + destX1; srcBuffer = img.pixels; if (smooth) { // use bilinear filtering iw = img.width; iw1 = img.width - 1; ih1 = img.height - 1; switch (mode) { case BLEND: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { // davbol - renamed old blend_multiply to blend_blend destPixels[destOffset + x] = blend_blend(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case ADD: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_add_pin(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SUBTRACT: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_sub_pin(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case LIGHTEST: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_lightest(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DARKEST: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_darkest(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case REPLACE: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = filter_bilinear(); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DIFFERENCE: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_difference(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case EXCLUSION: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_exclusion(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case MULTIPLY: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_multiply(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SCREEN: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_screen(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case OVERLAY: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_overlay(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case HARD_LIGHT: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_hard_light(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SOFT_LIGHT: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_soft_light(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; // davbol - proposed 2007-01-09 case DODGE: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_dodge(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case BURN: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_burn(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; } } else { // nearest neighbour scaling (++fast!) switch (mode) { case BLEND: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { // davbol - renamed old blend_multiply to blend_blend destPixels[destOffset + x] = blend_blend(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case ADD: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_add_pin(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SUBTRACT: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_sub_pin(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case LIGHTEST: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_lightest(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DARKEST: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_darkest(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case REPLACE: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = srcBuffer[sY + (sX >> PRECISIONB)]; sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DIFFERENCE: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_difference(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case EXCLUSION: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_exclusion(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case MULTIPLY: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_multiply(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SCREEN: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_screen(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case OVERLAY: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_overlay(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case HARD_LIGHT: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_hard_light(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SOFT_LIGHT: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_soft_light(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; // davbol - proposed 2007-01-09 case DODGE: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_dodge(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case BURN: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_burn(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; } } }
private void blit_resize(PImage img, int srcX1, int srcY1, int srcX2, int srcY2, int[] destPixels, int screenW, int screenH, int destX1, int destY1, int destX2, int destY2, int mode) { if (srcX1 < 0) srcX1 = 0; if (srcY1 < 0) srcY1 = 0; if (srcX2 > img.width) srcX2 = img.width; if (srcY2 > img.height) srcY2 = img.height; int srcW = srcX2 - srcX1; int srcH = srcY2 - srcY1; int destW = destX2 - destX1; int destH = destY2 - destY1; boolean smooth = true; // may as well go with the smoothing these days if (!smooth) { srcW++; srcH++; } if (destW <= 0 || destH <= 0 || srcW <= 0 || srcH <= 0 || destX1 >= screenW || destY1 >= screenH || srcX1 >= img.width || srcY1 >= img.height) { return; } int dx = (int) (srcW / (float) destW * PRECISIONF); int dy = (int) (srcH / (float) destH * PRECISIONF); srcXOffset = (int) (destX1 < 0 ? -destX1 * dx : srcX1 * PRECISIONF); srcYOffset = (int) (destY1 < 0 ? -destY1 * dy : srcY1 * PRECISIONF); if (destX1 < 0) { destW += destX1; destX1 = 0; } if (destY1 < 0) { destH += destY1; destY1 = 0; } destW = low(destW, screenW - destX1); destH = low(destH, screenH - destY1); int destOffset = destY1 * screenW + destX1; srcBuffer = img.pixels; if (smooth) { // use bilinear filtering iw = img.width; iw1 = img.width - 1; ih1 = img.height - 1; switch (mode) { case BLEND: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { // davbol - renamed old blend_multiply to blend_blend destPixels[destOffset + x] = blend_blend(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case ADD: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_add_pin(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SUBTRACT: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_sub_pin(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case LIGHTEST: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_lightest(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DARKEST: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_darkest(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case REPLACE: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = filter_bilinear(); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DIFFERENCE: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_difference(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case EXCLUSION: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_exclusion(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case MULTIPLY: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_multiply(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SCREEN: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_screen(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case OVERLAY: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_overlay(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case HARD_LIGHT: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_hard_light(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SOFT_LIGHT: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_soft_light(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; // davbol - proposed 2007-01-09 case DODGE: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_dodge(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case BURN: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_burn(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; } } else { // nearest neighbour scaling (++fast!) switch (mode) { case BLEND: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { // davbol - renamed old blend_multiply to blend_blend destPixels[destOffset + x] = blend_blend(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case ADD: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_add_pin(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SUBTRACT: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_sub_pin(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case LIGHTEST: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_lightest(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DARKEST: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_darkest(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case REPLACE: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = srcBuffer[sY + (sX >> PRECISIONB)]; sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DIFFERENCE: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_difference(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case EXCLUSION: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_exclusion(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case MULTIPLY: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_multiply(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SCREEN: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_screen(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case OVERLAY: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_overlay(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case HARD_LIGHT: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_hard_light(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SOFT_LIGHT: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_soft_light(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; // davbol - proposed 2007-01-09 case DODGE: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_dodge(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case BURN: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_burn(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; } } }
diff --git a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddPersonToRoleTwoStageGenerator.java b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddPersonToRoleTwoStageGenerator.java index 2f9d9b8..73acb23 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddPersonToRoleTwoStageGenerator.java +++ b/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/AddPersonToRoleTwoStageGenerator.java @@ -1,921 +1,921 @@ /* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.vivoweb.webapp.util.ModelUtils; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.XSD; import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.jena.QueryUtils; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeIntervalValidationVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.RoleToActivityPredicatePreprocessor; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.AntiXssValidation; import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode; import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils; /** * Generates the edit configuration for adding a Role to a Person. Stage one is selecting the type of the non-person thing associated with the Role with the intention of reducing the number of Individuals that the user has to select from. Stage two is selecting the non-person Individual to associate with the Role. This is intended to create a set of statements like: ?person core:hasResearchActivityRole ?newRole. ?newRole rdf:type core:ResearchActivityRole ; roleToActivityPredicate ?someActivity . ?someActivity rdf:type core:ResearchActivity . ?someActivity rdfs:label "activity title" . Important: This form cannot be directly used as a custom form. It has parameters that must be set. See addClinicalRoleToPerson.jsp for an example. roleToActivityPredicate and activityToRolePredicate are both dependent on the type of the activity itself. For a new statement, the predicate type is not known. For an existing statement, the predicate is known but may change based on the type of the activity newly selected. bdc34: TODO: figure out what needs to be customized per role form, document it here in comments TODO: rewrite class as an abstract class with simple, documented, required methods to override AddRoleToPersonTwoStageGenerator is abstract, each subclass will need to configure: From the old JSP version: showRoleLabelField boolean roleType URI roleToActivityPredicate URI activityToRolePredicate URI roleActivityType_optionsType roleActivityType_objectClassURI roleActivityType_literalOptions For the new generator version: template * */ public abstract class AddPersonToRoleTwoStageGenerator extends BaseEditConfigurationGenerator implements EditConfigurationGenerator { private Log log = LogFactory.getLog(AddPersonToRoleTwoStageGenerator.class); /* ***** Methods that are REQUIRED to be implemented in subclasses ***** */ /** Freemarker template to use */ abstract String getTemplate(); /** URI of type for the role context node */ abstract String getRoleType(); /** In the case of literal options, subclass generator will set the options to be returned */ abstract HashMap<String, String> getRoleActivityTypeLiteralOptions(); /** * Each subclass generator will return its own type of option here: * whether literal hardcoded, based on class group, or subclasses of a specific class * The latter two will apparently lend some kind of uri to objectClassUri ? */ abstract RoleActivityOptionTypes getRoleActivityTypeOptionsType(); /** The URI of a Class to use with options if required. An option type like * CHILD_VCLASSES would reqire a role activity object class URI. */ abstract String getRoleActivityTypeObjectClassUri(VitroRequest vreq); /** If true an input should be shown on the form for a * label for the role context node * TODO: move this to the FTL and have label optional. */ abstract boolean isShowRoleLabelField(); /** URI of predicate between role context node and activity */ //Bdc34: not used anywhere? that's odd // abstract String getActivityToRolePredicate(); @Override public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) { EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); initProcessParameters(vreq, session, editConfiguration); editConfiguration.setVarNameForSubject("grant"); editConfiguration.setVarNameForPredicate("rolePredicate"); editConfiguration.setVarNameForObject("role"); // Required N3 editConfiguration.setN3Required(list( N3_PREFIX + "\n" + - "?grant ?inverseRolePredicate ?role .\n" + + "?grant ?rolePredicate ?role .\n" + "?role a ?roleType .\n" )); // Optional N3 //Note here we are placing the role to activity relationships as optional, since //it's possible to delete this relationship from the activity //On submission, if we kept these statements in n3required, the retractions would //not have all variables substituted, leading to an error //Note also we are including the relationship as a separate string in the array, to allow it to be //independently evaluated and passed back with substitutions even if the other strings are not //substituted correctly. editConfiguration.setN3Optional( list( "?role " + getRoleToActivityPlaceholder() + " ?roleActivity .\n"+ "?roleActivity " + getActivityToRolePlaceholder() + " ?role .", - "?person ?rolePredicate ?role .", + "?role ?inverseRolePredicate ?grant .", getN3ForActivityLabel(), getN3ForActivityType(), getN3RoleLabelAssertion(), getN3ForStart(), getN3ForEnd() )); editConfiguration.setNewResources( newResources(vreq) ); //In scope setUrisAndLiteralsInScope(editConfiguration, vreq); //on Form setUrisAndLiteralsOnForm(editConfiguration, vreq); //Sparql queries setSparqlQueries(editConfiguration, vreq); //set fields setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq)); //Form title and submit label now moved to edit configuration template //TODO: check if edit configuration template correct place to set those or whether //additional methods here should be used and reference instead, e.g. edit configuration template could call //default obj property form.populateTemplate or some such method //Select from existing also set within template itself editConfiguration.setTemplate(getTemplate()); //Add validator //editConfiguration.addValidator(new DateTimeIntervalValidationVTwo("startField","endField") ); //editConfiguration.addValidator(new AntiXssValidation()); //Add preprocessors addPreprocessors(editConfiguration, vreq.getWebappDaoFactory()); //Adding additional data, specifically edit mode addFormSpecificData(editConfiguration, vreq); //prepare prepare(vreq, editConfiguration); return editConfiguration; } private void initProcessParameters(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) { editConfiguration.setFormUrl(EditConfigurationUtils.getFormUrlWithoutContext(vreq)); editConfiguration.setEntityToReturnTo(EditConfigurationUtils.getSubjectUri(vreq)); } /* N3 Required and Optional Generators as well as supporting methods */ private String getN3ForActivityLabel() { return "?roleActivity <" + RDFS.label.getURI() + "> ?activityLabel ."; } private String getN3ForActivityType() { return "?roleActivity a ?roleActivityType ."; } private String getN3RoleLabelAssertion() { return "?role <" + RDFS.label.getURI() + "> ?roleLabel ."; } //Method b/c used in two locations, n3 optional and n3 assertions private List<String> getN3ForStart() { List<String> n3ForStart = new ArrayList<String>(); n3ForStart.add("?role <" + RoleToIntervalURI + "> ?intervalNode ." + "?intervalNode <" + RDF.type.getURI() + "> <" + IntervalTypeURI + "> ." + "?intervalNode <" + IntervalToStartURI + "> ?startNode ." + "?startNode <" + RDF.type.getURI() + "> <" + DateTimeValueTypeURI + "> ." + "?startNode <" + DateTimeValueURI + "> ?startField-value ." + "?startNode <" + DateTimePrecisionURI + "> ?startField-precision ."); return n3ForStart; } private List<String> getN3ForEnd() { List<String> n3ForEnd = new ArrayList<String>(); n3ForEnd.add("?role <" + RoleToIntervalURI + "> ?intervalNode . " + "?intervalNode <" + RDF.type.getURI() + "> <" + IntervalTypeURI + "> ." + "?intervalNode <" + IntervalToEndURI + "> ?endNode ." + "?endNode <" + RDF.type.getURI() + "> <" + DateTimeValueTypeURI + "> ." + "?endNode <" + DateTimeValueURI + "> ?endField-value ." + "?endNode <" + DateTimePrecisionURI+ "> ?endField-precision ."); return n3ForEnd; } /** Get new resources */ private Map<String, String> newResources(VitroRequest vreq) { String DEFAULT_NS_TOKEN=null; //null forces the default NS HashMap<String, String> newResources = new HashMap<String, String>(); newResources.put("role", DEFAULT_NS_TOKEN); newResources.put("roleActivity", DEFAULT_NS_TOKEN); newResources.put("intervalNode", DEFAULT_NS_TOKEN); newResources.put("startNode", DEFAULT_NS_TOKEN); newResources.put("endNode", DEFAULT_NS_TOKEN); return newResources; } /** Set URIS and Literals In Scope and on form and supporting methods */ private void setUrisAndLiteralsInScope(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { HashMap<String, List<String>> urisInScope = new HashMap<String, List<String>>(); //Setting inverse role predicate urisInScope.put("inverseRolePredicate", getInversePredicate(vreq)); urisInScope.put("roleType", list( getRoleType() ) ); //Uris in scope include subject, predicate, and object var editConfiguration.setUrisInScope(urisInScope); //literals in scope empty initially, usually populated by code in prepare for update //with existing values for variables } private List<String> getInversePredicate(VitroRequest vreq) { List<String> inversePredicateArray = new ArrayList<String>(); ObjectProperty op = EditConfigurationUtils.getObjectProperty(vreq); if(op != null && op.getURIInverse() != null) { inversePredicateArray.add(op.getURIInverse()); } return inversePredicateArray; } private void setUrisAndLiteralsOnForm(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { List<String> urisOnForm = new ArrayList<String>(); //add role activity and roleActivityType to uris on form urisOnForm.add("roleActivity"); urisOnForm.add("roleActivityType"); //Also adding the predicates //TODO: Check how to override this in case of default parameter? Just write hidden input to form? urisOnForm.add("roleToActivityPredicate"); urisOnForm.add("activityToRolePredicate"); editConfiguration.setUrisOnform(urisOnForm); //activity label and role label are literals on form List<String> literalsOnForm = new ArrayList<String>(); literalsOnForm.add("activityLabel"); literalsOnForm.add("roleLabel"); editConfiguration.setLiteralsOnForm(literalsOnForm); } /** Set SPARQL Queries and supporting methods. */ private void setSparqlQueries(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { //Queries for activity label, role label, start Field value, end Field value HashMap<String, String> map = new HashMap<String, String>(); map.put("activityLabel", getActivityLabelQuery(vreq)); map.put("roleLabel", getRoleLabelQuery(vreq)); map.put("startField-value", getExistingStartDateQuery(vreq)); map.put("endField-value", getExistingEndDateQuery(vreq)); editConfiguration.setSparqlForExistingLiterals(map); //Queries for role activity, activity type query, interval node, // start node, end node, start field precision, endfield precision map = new HashMap<String, String>(); map.put("roleActivity", getRoleActivityQuery(vreq)); map.put("roleActivityType", getActivityTypeQuery(vreq)); map.put("intervalNode", getIntervalNodeQuery(vreq)); map.put("startNode", getStartNodeQuery(vreq)); map.put("endNode", getEndNodeQuery(vreq)); map.put("startField-precision", getStartPrecisionQuery(vreq)); map.put("endField-precision", getEndPrecisionQuery(vreq)); //Also need sparql queries for roleToActivityPredicate and activityToRolePredicate map.put("roleToActivityPredicate", getRoleToActivityPredicateQuery(vreq)); map.put("activityToRolePredicate", getActivityToRolePredicateQuery(vreq)); editConfiguration.setSparqlForExistingUris(map); } private String getActivityToRolePredicateQuery(VitroRequest vreq) { String query = "SELECT ?existingActivityToRolePredicate \n " + "WHERE { \n" + "?roleActivity ?existingActivityToRolePredicate ?role .\n"; //Get possible predicates List<String> addToQuery = new ArrayList<String>(); List<String> predicates = getPossibleActivityToRolePredicates(); for(String p:predicates) { addToQuery.add("(?existingActivityToRolePredicate=<" + p + ">)"); } query += "FILTER (" + StringUtils.join(addToQuery, " || ") + ")\n"; query += "}"; return query; } private String getRoleToActivityPredicateQuery(VitroRequest vreq) { String query = "SELECT ?existingRoleToActivityPredicate \n " + "WHERE { \n" + "?role ?existingRoleToActivityPredicate ?roleActivity .\n"; //Get possible predicates query += getFilterRoleToActivityPredicate("existingRoleToActivityPredicate"); query += "\n}"; return query; } private String getEndPrecisionQuery(VitroRequest vreq) { String query = "SELECT ?existingEndPrecision WHERE {\n" + "?role <" + RoleToIntervalURI + "> ?intervalNode .\n" + "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" + "?intervalNode <" + IntervalToEndURI + "> ?endNode .\n" + "?endNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> . \n" + "?endNode <" + DateTimePrecisionURI + "> ?existingEndPrecision . }"; return query; } private String getStartPrecisionQuery(VitroRequest vreq) { String query = "SELECT ?existingStartPrecision WHERE {\n" + "?role <" + RoleToIntervalURI + "> ?intervalNode .\n" + "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" + "?intervalNode <" + IntervalToStartURI + "> ?startNode .\n" + "?startNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> . \n" + "?startNode <" + DateTimePrecisionURI + "> ?existingStartPrecision . }"; return query; } private String getEndNodeQuery(VitroRequest vreq) { String query = "SELECT ?existingEndNode WHERE {\n"+ "?role <" + RoleToIntervalURI + "> ?intervalNode .\n"+ "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n"+ "?intervalNode <" + IntervalToEndURI + "> ?existingEndNode . \n"+ "?existingEndNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .}\n"; return query; } private String getStartNodeQuery(VitroRequest vreq) { String query = "SELECT ?existingStartNode WHERE {\n"+ "?role <" + RoleToIntervalURI + "> ?intervalNode .\n"+ "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n"+ "?intervalNode <" + IntervalToStartURI + "> ?existingStartNode . \n"+ "?existingStartNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .}"; return query; } private String getIntervalNodeQuery(VitroRequest vreq) { String query = "SELECT ?existingIntervalNode WHERE { \n" + "?role <" + RoleToIntervalURI + "> ?existingIntervalNode . \n" + " ?existingIntervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> . }\n"; return query; } /* * The activity type query results must be limited to the values in the activity type select element. * Sometimes the query returns a superclass such as owl:Thing instead. * Make use of vitro:mostSpecificType so that, for example, an individual is both a * core:InvitedTalk and a core:Presentation, core:InvitedTalk is selected. * vitro:mostSpecificType alone may not suffice, since it does not guarantee that the value returned * is in the select list. * We could still have problems if the value from the select list is not a vitro:mostSpecificType, * but that is unlikely. */ //This method had some code already setup in the jsp file private String getActivityTypeQuery(VitroRequest vreq) { String activityTypeQuery = null; //roleActivityType_optionsType: This gets you whether this is a literal // RoleActivityOptionTypes optionsType = getRoleActivityTypeOptionsType(); // Note that this value is overloaded to specify either object class uri or classgroup uri String objectClassUri = getRoleActivityTypeObjectClassUri(vreq); if (StringUtils.isNotBlank(objectClassUri)) { log.debug("objectClassUri = " + objectClassUri); if (RoleActivityOptionTypes.VCLASSGROUP.equals(optionsType)) { activityTypeQuery = getClassgroupActivityTypeQuery(vreq); activityTypeQuery = QueryUtils.subUriForQueryVar(activityTypeQuery, "classgroup", objectClassUri); } else if (RoleActivityOptionTypes.CHILD_VCLASSES.equals(optionsType)) { activityTypeQuery = getSubclassActivityTypeQuery(vreq); activityTypeQuery = QueryUtils.subUriForQueryVar(activityTypeQuery, "objectClassUri", objectClassUri); } else { activityTypeQuery = getDefaultActivityTypeQuery(vreq); } // Select options are hardcoded } else if (RoleActivityOptionTypes.HARDCODED_LITERALS.equals(optionsType)) { //literal options HashMap<String, String> typeLiteralOptions = getRoleActivityTypeLiteralOptions(); if (typeLiteralOptions.size() > 0) { try { List<String> typeUris = new ArrayList<String>(); Set<String> optionUris = typeLiteralOptions.keySet(); for(String uri: optionUris) { if(!uri.isEmpty()) { typeUris.add("(?existingActivityType = <" + uri + ">)"); } } String typeFilters = "FILTER (" + StringUtils.join(typeUris, "||") + ")"; String defaultActivityTypeQuery = getDefaultActivityTypeQuery(vreq); activityTypeQuery = defaultActivityTypeQuery.replaceAll("}$", "") + typeFilters + "}"; } catch (Exception e) { activityTypeQuery = getDefaultActivityTypeQuery(vreq); } } else { activityTypeQuery = getDefaultActivityTypeQuery(vreq); } } else { activityTypeQuery = getDefaultActivityTypeQuery(vreq); } //The replacement of activity type query's predicate was only relevant when we actually //know which predicate is definitely being used here //Here we have multiple values possible for predicate so the original //Replacement should only happen when we have an actual predicate String replaceRoleToActivityPredicate = getRoleToActivityPredicate(vreq); activityTypeQuery = QueryUtils.replaceQueryVar(activityTypeQuery, "predicate", getRoleToActivityPlaceholderName()); log.debug("Activity type query: " + activityTypeQuery); return activityTypeQuery; } private String getDefaultActivityTypeQuery(VitroRequest vreq) { String query = "PREFIX core: <" + VIVO_NS + ">\n" + "PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" + "SELECT ?existingActivityType WHERE { \n" + " ?role ?predicate ?existingActivity . \n" + " ?existingActivity vitro:mostSpecificType ?existingActivityType . \n"; query += getFilterRoleToActivityPredicate("predicate"); query+= "}"; return query; } private String getSubclassActivityTypeQuery(VitroRequest vreq) { String query = "PREFIX core: <" + VIVO_NS + ">\n" + "PREFIX rdfs: <" + VitroVocabulary.RDFS + ">\n" + "PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" + "SELECT ?existingActivityType WHERE {\n" + " ?role ?predicate ?existingActivity . \n" + " ?existingActivity vitro:mostSpecificType ?existingActivityType . \n" + " ?existingActivityType rdfs:subClassOf ?objectClassUri . \n"; query += getFilterRoleToActivityPredicate("predicate"); query+= "}"; return query; } private String getClassgroupActivityTypeQuery(VitroRequest vreq) { String query = "PREFIX core: <" + VIVO_NS + ">\n" + "PREFIX vitro: <" + VitroVocabulary.vitroURI + "> \n" + "SELECT ?existingActivityType WHERE { \n" + " ?role ?predicate ?existingActivity . \n" + " ?existingActivity vitro:mostSpecificType ?existingActivityType . \n" + " ?existingActivityType vitro:inClassGroup ?classgroup . \n"; query += getFilterRoleToActivityPredicate("predicate"); query+= "}"; return query; } private String getRoleActivityQuery(VitroRequest vreq) { //If role to activity predicate is the default query, then we need to replace with a union //of both realizedIn and the other String query = "PREFIX core: <" + VIVO_NS + ">"; //Portion below for multiple possible predicates List<String> predicates = getPossibleRoleToActivityPredicates(); List<String> addToQuery = new ArrayList<String>(); query += "SELECT ?existingActivity WHERE { \n" + " ?role ?predicate ?existingActivity . \n "; query += getFilterRoleToActivityPredicate("predicate"); query += "}"; return query; } private String getExistingEndDateQuery(VitroRequest vreq) { String query = " SELECT ?existingEndDate WHERE {\n" + "?role <" + RoleToIntervalURI + "> ?intervalNode .\n" + "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" + "?intervalNode <" + IntervalToEndURI + "> ?endNode .\n" + "?endNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .\n" + "?endNode <" + DateTimeValueURI + "> ?existingEndDate . }"; return query; } private String getExistingStartDateQuery(VitroRequest vreq) { String query = "SELECT ?existingDateStart WHERE {\n" + "?role <" + RoleToIntervalURI + "> ?intervalNode .\n" + "?intervalNode <" + VitroVocabulary.RDF_TYPE + "> <" + IntervalTypeURI + "> .\n" + "?intervalNode <" + IntervalToStartURI+ "> ?startNode .\n" + "?startNode <" + VitroVocabulary.RDF_TYPE + "> <" + DateTimeValueTypeURI + "> .\n" + "?startNode <" + DateTimeValueURI + "> ?existingDateStart . }"; return query; } private String getRoleLabelQuery(VitroRequest vreq) { String query = "SELECT ?existingRoleLabel WHERE { \n" + "?role <" + VitroVocabulary.LABEL + "> ?existingRoleLabel . }"; return query; } private String getActivityLabelQuery(VitroRequest vreq) { String query = "PREFIX core: <" + VIVO_NS + ">" + "PREFIX rdfs: <" + RDFS.getURI() + "> \n"; query += "SELECT ?existingTitle WHERE { \n" + "?role ?predicate ?existingActivity . \n" + "?existingActivity rdfs:label ?existingTitle . \n"; query += getFilterRoleToActivityPredicate("predicate"); query += "}"; return query; } /** * * Set Fields and supporting methods */ private void setFields(EditConfigurationVTwo editConfiguration, VitroRequest vreq, String predicateUri) { Map<String, FieldVTwo> fields = new HashMap<String, FieldVTwo>(); //Multiple fields getActivityLabelField(editConfiguration, vreq, fields); getRoleActivityTypeField(editConfiguration, vreq, fields); getRoleActivityField(editConfiguration, vreq, fields); getRoleLabelField(editConfiguration, vreq, fields); getStartField(editConfiguration, vreq, fields); getEndField(editConfiguration, vreq, fields); //These fields are for the predicates that will be set later //TODO: Do these only if not using a parameter for the predicate? getRoleToActivityPredicateField(editConfiguration, vreq, fields); getActivityToRolePredicateField(editConfiguration, vreq, fields); editConfiguration.setFields(fields); } //This is a literal technically? private void getActivityToRolePredicateField( EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "activityToRolePredicate"; //get range data type uri and range language String stringDatatypeUri = XSD.xstring.toString(); FieldVTwo field = new FieldVTwo(); field.setName(fieldName); //queryForExisting is not being used anywhere in Field //Not really interested in validators here List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } private void getRoleToActivityPredicateField( EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "roleToActivityPredicate"; //get range data type uri and range language String stringDatatypeUri = XSD.xstring.toString(); FieldVTwo field = new FieldVTwo(); field.setName(fieldName); //queryForExisting is not being used anywhere in Field //Not really interested in validators here List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } //Label of "right side" of role, i.e. label for role roleIn Activity private void getActivityLabelField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "activityLabel"; //get range data type uri and range language String stringDatatypeUri = XSD.xstring.toString(); FieldVTwo field = new FieldVTwo(); field.setName(fieldName); //queryForExisting is not being used anywhere in Field List<String> validators = new ArrayList<String>(); //If add mode or repair, etc. need to add label required validator if(isAddMode(vreq) || isRepairMode(vreq)) { validators.add("nonempty"); } validators.add("datatype:" + stringDatatypeUri); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(stringDatatypeUri); field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } //type of "right side" of role, i.e. type of activity from role roleIn activity private void getRoleActivityTypeField( EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "roleActivityType"; //get range data type uri and range language FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); if(isAddMode(vreq) || isRepairMode(vreq)) { validators.add("nonempty"); } field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field //TODO: Check if this is correct field.setOptionsType(getRoleActivityTypeOptionsType().toString()); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(getRoleActivityTypeObjectClassUri(vreq)); field.setRangeDatatypeUri(null); HashMap<String, String> literalOptionsMap = getRoleActivityTypeLiteralOptions(); List<List<String>> fieldLiteralOptions = new ArrayList<List<String>>(); Set<String> optionUris = literalOptionsMap.keySet(); for(String optionUri: optionUris) { List<String> uriLabelArray = new ArrayList<String>(); uriLabelArray.add(optionUri); uriLabelArray.add(literalOptionsMap.get(optionUri)); fieldLiteralOptions.add(uriLabelArray); } field.setLiteralOptions(fieldLiteralOptions); fields.put(field.getName(), field); } //Assuming URI for activity for role? private void getRoleActivityField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "roleActivity"; //get range data type uri and range language FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); //empty field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } private void getRoleLabelField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "roleLabel"; String stringDatatypeUri = XSD.xstring.toString(); FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); validators.add("datatype:" + stringDatatypeUri); if(isShowRoleLabelField()) { validators.add("nonempty"); } field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(stringDatatypeUri); //empty field.setLiteralOptions(new ArrayList<List<String>>()); fields.put(field.getName(), field); } private void getStartField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "startField"; FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); //empty field.setLiteralOptions(new ArrayList<List<String>>()); //This logic was originally after edit configuration object created from json in original jsp field.setEditElement( new DateTimeWithPrecisionVTwo(field, VitroVocabulary.Precision.YEAR.uri(), VitroVocabulary.Precision.NONE.uri())); fields.put(field.getName(), field); } private void getEndField(EditConfigurationVTwo editConfiguration, VitroRequest vreq, Map<String, FieldVTwo> fields) { String fieldName = "endField"; FieldVTwo field = new FieldVTwo(); field.setName(fieldName); List<String> validators = new ArrayList<String>(); field.setValidators(validators); //subjectUri and subjectClassUri are not being used in Field field.setOptionsType("UNDEFINED"); //why isn't predicate uri set for data properties? field.setPredicateUri(null); field.setObjectClassUri(null); field.setRangeDatatypeUri(null); //empty field.setLiteralOptions(new ArrayList<List<String>>()); //Set edit element field.setEditElement( new DateTimeWithPrecisionVTwo(field, VitroVocabulary.Precision.YEAR.uri(), VitroVocabulary.Precision.NONE.uri())); fields.put(field.getName(), field); } private void addPreprocessors(EditConfigurationVTwo editConfiguration, WebappDaoFactory wadf) { //Add preprocessor that will replace the role to activity predicate and inverse //with correct properties based on the activity type editConfiguration.addEditSubmissionPreprocessor( new RoleToActivityPredicatePreprocessor(editConfiguration, wadf)); } //This has a default value, but note that even that will not be used //in the update with realized in or contributes to //Overridden when need be in subclassed generator //Also note that for now we're going to actually going to return a //placeholder value by default public String getRoleToActivityPredicate(VitroRequest vreq) { //TODO: <uri> and ?placeholder are incompatible return getRoleToActivityPlaceholder(); } //Ensure when overwritten that this includes the <> b/c otherwise the query won't work //Some values will have a default value public List<String> getPossibleRoleToActivityPredicates() { return ModelUtils.getPossiblePropertiesForRole(); } public List<String> getPossibleActivityToRolePredicates() { return ModelUtils.getPossibleInversePropertiesForRole(); } /* Methods that check edit mode */ public EditMode getEditMode(VitroRequest vreq) { List<String> roleToGrantPredicates = getPossibleRoleToActivityPredicates(); return EditModeUtils.getEditMode(vreq, roleToGrantPredicates); } private boolean isAddMode(VitroRequest vreq) { return EditModeUtils.isAddMode(getEditMode(vreq)); } private boolean isEditMode(VitroRequest vreq) { return EditModeUtils.isEditMode(getEditMode(vreq)); } private boolean isRepairMode(VitroRequest vreq) { return EditModeUtils.isRepairMode(getEditMode(vreq)); } /* URIS for various predicates */ private final String VIVO_NS="http://vivoweb.org/ontology/core#"; private final String RoleToIntervalURI = VIVO_NS + "dateTimeInterval"; private final String IntervalTypeURI = VIVO_NS + "DateTimeInterval"; private final String IntervalToStartURI = VIVO_NS + "start"; private final String IntervalToEndURI = VIVO_NS + "end"; private final String StartYearPredURI = VIVO_NS + "startYear"; private final String EndYearPredURI = VIVO_NS + "endYear"; private final String DateTimeValueTypeURI=VIVO_NS + "DateTimeValue"; private final String DateTimePrecisionURI=VIVO_NS + "dateTimePrecision"; private final String DateTimeValueURI = VIVO_NS + "dateTime"; //Form specific data public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) { HashMap<String, Object> formSpecificData = new HashMap<String, Object>(); formSpecificData.put("editMode", getEditMode(vreq).name().toLowerCase()); //Fields that will need select lists generated //Store field names List<String> objectSelect = new ArrayList<String>(); objectSelect.add("roleActivityType"); //TODO: Check if this is the proper way to do this? formSpecificData.put("objectSelect", objectSelect); //Also put in show role label field formSpecificData.put("showRoleLabelField", isShowRoleLabelField()); //Put in the fact that we require field editConfiguration.setFormSpecificData(formSpecificData); } public String getFilterRoleToActivityPredicate(String predicateVar) { String addFilter = "FILTER ("; List<String> predicates = getPossibleRoleToActivityPredicates(); List<String> filterPortions = new ArrayList<String>(); for(String p: predicates) { filterPortions.add("(?" + predicateVar + "=<" + p + ">)"); } addFilter += StringUtils.join(filterPortions, " || "); addFilter += ")"; return addFilter; } private String getRoleToActivityPlaceholder() { return "?" + getRoleToActivityPlaceholderName(); } private String getRoleToActivityPlaceholderName() { return "roleToActivityPredicate"; } private String getActivityToRolePlaceholder() { return "?activityToRolePredicate"; } //Types of options to populate drop-down for types for the "right side" of the role public static enum RoleActivityOptionTypes { VCLASSGROUP, CHILD_VCLASSES, HARDCODED_LITERALS }; private final String N3_PREFIX = "@prefix core: <http://vivoweb.org/ontology/core#> ."; }
false
true
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) { EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); initProcessParameters(vreq, session, editConfiguration); editConfiguration.setVarNameForSubject("grant"); editConfiguration.setVarNameForPredicate("rolePredicate"); editConfiguration.setVarNameForObject("role"); // Required N3 editConfiguration.setN3Required(list( N3_PREFIX + "\n" + "?grant ?inverseRolePredicate ?role .\n" + "?role a ?roleType .\n" )); // Optional N3 //Note here we are placing the role to activity relationships as optional, since //it's possible to delete this relationship from the activity //On submission, if we kept these statements in n3required, the retractions would //not have all variables substituted, leading to an error //Note also we are including the relationship as a separate string in the array, to allow it to be //independently evaluated and passed back with substitutions even if the other strings are not //substituted correctly. editConfiguration.setN3Optional( list( "?role " + getRoleToActivityPlaceholder() + " ?roleActivity .\n"+ "?roleActivity " + getActivityToRolePlaceholder() + " ?role .", "?person ?rolePredicate ?role .", getN3ForActivityLabel(), getN3ForActivityType(), getN3RoleLabelAssertion(), getN3ForStart(), getN3ForEnd() )); editConfiguration.setNewResources( newResources(vreq) ); //In scope setUrisAndLiteralsInScope(editConfiguration, vreq); //on Form setUrisAndLiteralsOnForm(editConfiguration, vreq); //Sparql queries setSparqlQueries(editConfiguration, vreq); //set fields setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq)); //Form title and submit label now moved to edit configuration template //TODO: check if edit configuration template correct place to set those or whether //additional methods here should be used and reference instead, e.g. edit configuration template could call //default obj property form.populateTemplate or some such method //Select from existing also set within template itself editConfiguration.setTemplate(getTemplate()); //Add validator //editConfiguration.addValidator(new DateTimeIntervalValidationVTwo("startField","endField") ); //editConfiguration.addValidator(new AntiXssValidation()); //Add preprocessors addPreprocessors(editConfiguration, vreq.getWebappDaoFactory()); //Adding additional data, specifically edit mode addFormSpecificData(editConfiguration, vreq); //prepare prepare(vreq, editConfiguration); return editConfiguration; }
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) { EditConfigurationVTwo editConfiguration = new EditConfigurationVTwo(); initProcessParameters(vreq, session, editConfiguration); editConfiguration.setVarNameForSubject("grant"); editConfiguration.setVarNameForPredicate("rolePredicate"); editConfiguration.setVarNameForObject("role"); // Required N3 editConfiguration.setN3Required(list( N3_PREFIX + "\n" + "?grant ?rolePredicate ?role .\n" + "?role a ?roleType .\n" )); // Optional N3 //Note here we are placing the role to activity relationships as optional, since //it's possible to delete this relationship from the activity //On submission, if we kept these statements in n3required, the retractions would //not have all variables substituted, leading to an error //Note also we are including the relationship as a separate string in the array, to allow it to be //independently evaluated and passed back with substitutions even if the other strings are not //substituted correctly. editConfiguration.setN3Optional( list( "?role " + getRoleToActivityPlaceholder() + " ?roleActivity .\n"+ "?roleActivity " + getActivityToRolePlaceholder() + " ?role .", "?role ?inverseRolePredicate ?grant .", getN3ForActivityLabel(), getN3ForActivityType(), getN3RoleLabelAssertion(), getN3ForStart(), getN3ForEnd() )); editConfiguration.setNewResources( newResources(vreq) ); //In scope setUrisAndLiteralsInScope(editConfiguration, vreq); //on Form setUrisAndLiteralsOnForm(editConfiguration, vreq); //Sparql queries setSparqlQueries(editConfiguration, vreq); //set fields setFields(editConfiguration, vreq, EditConfigurationUtils.getPredicateUri(vreq)); //Form title and submit label now moved to edit configuration template //TODO: check if edit configuration template correct place to set those or whether //additional methods here should be used and reference instead, e.g. edit configuration template could call //default obj property form.populateTemplate or some such method //Select from existing also set within template itself editConfiguration.setTemplate(getTemplate()); //Add validator //editConfiguration.addValidator(new DateTimeIntervalValidationVTwo("startField","endField") ); //editConfiguration.addValidator(new AntiXssValidation()); //Add preprocessors addPreprocessors(editConfiguration, vreq.getWebappDaoFactory()); //Adding additional data, specifically edit mode addFormSpecificData(editConfiguration, vreq); //prepare prepare(vreq, editConfiguration); return editConfiguration; }
diff --git a/src/com/valdaris/shoppinglist/dao/impl/ShoppingListDaoImpl.java b/src/com/valdaris/shoppinglist/dao/impl/ShoppingListDaoImpl.java index 3c194a5..b954a61 100755 --- a/src/com/valdaris/shoppinglist/dao/impl/ShoppingListDaoImpl.java +++ b/src/com/valdaris/shoppinglist/dao/impl/ShoppingListDaoImpl.java @@ -1,94 +1,100 @@ /** * This file is part of Flash Cart. * * Copyright (C) 2013 Javier Estévez * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.valdaris.shoppinglist.dao.impl; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import android.annotation.SuppressLint; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.valdaris.shoppinglist.dao.DatabaseHelper; import com.valdaris.shoppinglist.dao.IDataHandler; import com.valdaris.shoppinglist.model.ListItem; import com.valdaris.shoppinglist.model.ShoppingList; public class ShoppingListDaoImpl implements IDataHandler { private static final String TAG = ShoppingListDaoImpl.class.getCanonicalName(); @SuppressLint("SimpleDateFormat") private static final SimpleDateFormat FORMATTER = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); @Override public List<ShoppingList> getLists() { ArrayList<ShoppingList> lists = new ArrayList<ShoppingList>(); SQLiteDatabase db = new DatabaseHelper().getReadableDatabase(); String sort = ShoppingList.DATA_CREATION_FIELD_NAME; Cursor cursor = db.query(ShoppingList.TABLE_NAME, null, null, null, null, null, sort); while (cursor.moveToNext()) { ShoppingList list = new ShoppingList(); list.setId(cursor.getInt(cursor .getColumnIndex(ShoppingList.ID_FIELD_NAME))); try { - list.setCreationDate(FORMATTER.parse(cursor.getString(cursor - .getColumnIndex(ShoppingList.DATA_CREATION_FIELD_NAME)))); - list.setBuyDate(FORMATTER.parse(cursor.getString(cursor - .getColumnIndex(ShoppingList.DATA_BUY_FIELD_NAME)))); + String date = cursor.getString(cursor + .getColumnIndex(ShoppingList.DATA_CREATION_FIELD_NAME)); + if (date != null) { + list.setCreationDate(FORMATTER.parse(date)); + } + date = cursor.getString(cursor + .getColumnIndex(ShoppingList.DATA_BUY_FIELD_NAME)); + if (date != null) { + list.setBuyDate(FORMATTER.parse(date)); + } } catch (ParseException e) { Log.e(TAG, "Error formatting date", e); } list.setStatus(cursor.getString(cursor.getColumnIndex(ShoppingList.STATUS_FIELD_NAME))); list.setName(cursor.getString(cursor.getColumnIndex(ShoppingList.LIST_NAME))); lists.add(list); } cursor.close(); db.close(); return lists; } @Override public void create(ShoppingList list) { // TODO Auto-generated method stub } @Override public List<ListItem> getListProducts(ShoppingList list) { // TODO Auto-generated method stub return null; } @Override public void setListProducts(ShoppingList list, List<ListItem> products) { // TODO Auto-generated method stub } }
true
true
public List<ShoppingList> getLists() { ArrayList<ShoppingList> lists = new ArrayList<ShoppingList>(); SQLiteDatabase db = new DatabaseHelper().getReadableDatabase(); String sort = ShoppingList.DATA_CREATION_FIELD_NAME; Cursor cursor = db.query(ShoppingList.TABLE_NAME, null, null, null, null, null, sort); while (cursor.moveToNext()) { ShoppingList list = new ShoppingList(); list.setId(cursor.getInt(cursor .getColumnIndex(ShoppingList.ID_FIELD_NAME))); try { list.setCreationDate(FORMATTER.parse(cursor.getString(cursor .getColumnIndex(ShoppingList.DATA_CREATION_FIELD_NAME)))); list.setBuyDate(FORMATTER.parse(cursor.getString(cursor .getColumnIndex(ShoppingList.DATA_BUY_FIELD_NAME)))); } catch (ParseException e) { Log.e(TAG, "Error formatting date", e); } list.setStatus(cursor.getString(cursor.getColumnIndex(ShoppingList.STATUS_FIELD_NAME))); list.setName(cursor.getString(cursor.getColumnIndex(ShoppingList.LIST_NAME))); lists.add(list); } cursor.close(); db.close(); return lists; }
public List<ShoppingList> getLists() { ArrayList<ShoppingList> lists = new ArrayList<ShoppingList>(); SQLiteDatabase db = new DatabaseHelper().getReadableDatabase(); String sort = ShoppingList.DATA_CREATION_FIELD_NAME; Cursor cursor = db.query(ShoppingList.TABLE_NAME, null, null, null, null, null, sort); while (cursor.moveToNext()) { ShoppingList list = new ShoppingList(); list.setId(cursor.getInt(cursor .getColumnIndex(ShoppingList.ID_FIELD_NAME))); try { String date = cursor.getString(cursor .getColumnIndex(ShoppingList.DATA_CREATION_FIELD_NAME)); if (date != null) { list.setCreationDate(FORMATTER.parse(date)); } date = cursor.getString(cursor .getColumnIndex(ShoppingList.DATA_BUY_FIELD_NAME)); if (date != null) { list.setBuyDate(FORMATTER.parse(date)); } } catch (ParseException e) { Log.e(TAG, "Error formatting date", e); } list.setStatus(cursor.getString(cursor.getColumnIndex(ShoppingList.STATUS_FIELD_NAME))); list.setName(cursor.getString(cursor.getColumnIndex(ShoppingList.LIST_NAME))); lists.add(list); } cursor.close(); db.close(); return lists; }
diff --git a/src/forage/GetTypes.java b/src/forage/GetTypes.java index 4be0e65..2162954 100644 --- a/src/forage/GetTypes.java +++ b/src/forage/GetTypes.java @@ -1,120 +1,122 @@ package forage; import java.io.File; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Document; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.oauth.OAuthRequestException; import com.google.appengine.api.oauth.OAuthService; import com.google.appengine.api.oauth.OAuthServiceFactory; import com.google.appengine.api.users.User; /** * This servlet serves Get requests from client apps for newly added locations. Returns XML * @author M Hudson * */ public class GetTypes extends HttpServlet{ private static final long serialVersionUID = 2550724501785758817L; public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { //OAUTH check User user = null; try { OAuthService oauth = OAuthServiceFactory.getOAuthService(); //checks for user with current authorisation user = oauth.getCurrentUser(); resp.getWriter().println("Authenticated: " + user.getEmail()); + return; } catch (Exception e) { resp.getWriter().println("Not authenticated: "); return; } + /* //create key to run ancestor query on food types String food = "food"; DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Key foodKey = KeyFactory.createKey("Food", food); // Run an ancestor query to get food types Query typeQuery = new Query("FoodType", foodKey); List<Entity> types = datastore.prepare(typeQuery).asList( FetchOptions.Builder.withLimit(15)); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("food"); doc.appendChild(rootElement); for(Entity t: types){ Element type = doc.createElement("type"); rootElement.appendChild(type); Element name = doc.createElement("name"); String typeName = (String) t.getProperty("type"); name.appendChild(doc.createTextNode(typeName)); type.appendChild(name); } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); //StreamResult result = new StreamResult(new File("C:\\file.xml")); // Output xml as http response resp.setContentType("text/xml;charset=UTF-8"); StreamResult result = new StreamResult(resp.getOutputStream()); transformer.transform(source, result); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); - } + }*/ } }
false
true
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { //OAUTH check User user = null; try { OAuthService oauth = OAuthServiceFactory.getOAuthService(); //checks for user with current authorisation user = oauth.getCurrentUser(); resp.getWriter().println("Authenticated: " + user.getEmail()); } catch (Exception e) { resp.getWriter().println("Not authenticated: "); return; } //create key to run ancestor query on food types String food = "food"; DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Key foodKey = KeyFactory.createKey("Food", food); // Run an ancestor query to get food types Query typeQuery = new Query("FoodType", foodKey); List<Entity> types = datastore.prepare(typeQuery).asList( FetchOptions.Builder.withLimit(15)); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("food"); doc.appendChild(rootElement); for(Entity t: types){ Element type = doc.createElement("type"); rootElement.appendChild(type); Element name = doc.createElement("name"); String typeName = (String) t.getProperty("type"); name.appendChild(doc.createTextNode(typeName)); type.appendChild(name); } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); //StreamResult result = new StreamResult(new File("C:\\file.xml")); // Output xml as http response resp.setContentType("text/xml;charset=UTF-8"); StreamResult result = new StreamResult(resp.getOutputStream()); transformer.transform(source, result); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { //OAUTH check User user = null; try { OAuthService oauth = OAuthServiceFactory.getOAuthService(); //checks for user with current authorisation user = oauth.getCurrentUser(); resp.getWriter().println("Authenticated: " + user.getEmail()); return; } catch (Exception e) { resp.getWriter().println("Not authenticated: "); return; } /* //create key to run ancestor query on food types String food = "food"; DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Key foodKey = KeyFactory.createKey("Food", food); // Run an ancestor query to get food types Query typeQuery = new Query("FoodType", foodKey); List<Entity> types = datastore.prepare(typeQuery).asList( FetchOptions.Builder.withLimit(15)); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("food"); doc.appendChild(rootElement); for(Entity t: types){ Element type = doc.createElement("type"); rootElement.appendChild(type); Element name = doc.createElement("name"); String typeName = (String) t.getProperty("type"); name.appendChild(doc.createTextNode(typeName)); type.appendChild(name); } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); //StreamResult result = new StreamResult(new File("C:\\file.xml")); // Output xml as http response resp.setContentType("text/xml;charset=UTF-8"); StreamResult result = new StreamResult(resp.getOutputStream()); transformer.transform(source, result); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); }*/ }
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/revwalk/ObjectWalk.java b/org.eclipse.jgit/src/org/eclipse/jgit/revwalk/ObjectWalk.java index b1796b2..6904585 100644 --- a/org.eclipse.jgit/src/org/eclipse/jgit/revwalk/ObjectWalk.java +++ b/org.eclipse.jgit/src/org/eclipse/jgit/revwalk/ObjectWalk.java @@ -1,432 +1,432 @@ /* * Copyright (C) 2008, Shawn O. Pearce <[email protected]> * and other copyright owners as documented in the project's IP log. * * This program and the accompanying materials are made available * under the terms of the Eclipse Distribution License v1.0 which * accompanies this distribution, is reproduced below, and is * available at http://www.eclipse.org/org/documents/edl-v10.php * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name of the Eclipse Foundation, Inc. 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.eclipse.jgit.revwalk; import java.io.IOException; import org.eclipse.jgit.errors.CorruptObjectException; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.treewalk.CanonicalTreeParser; /** * Specialized subclass of RevWalk to include trees, blobs and tags. * <p> * Unlike RevWalk this subclass is able to remember starting roots that include * annotated tags, or arbitrary trees or blobs. Once commit generation is * complete and all commits have been popped by the application, individual * annotated tag, tree and blob objects can be popped through the additional * method {@link #nextObject()}. * <p> * Tree and blob objects reachable from interesting commits are automatically * scheduled for inclusion in the results of {@link #nextObject()}, returning * each object exactly once. Objects are sorted and returned according to the * the commits that reference them and the order they appear within a tree. * Ordering can be affected by changing the {@link RevSort} used to order the * commits that are returned first. */ public class ObjectWalk extends RevWalk { /** * Indicates a non-RevCommit is in {@link #pendingObjects}. * <p> * We can safely reuse {@link RevWalk#REWRITE} here for the same value as it * is only set on RevCommit and {@link #pendingObjects} never has RevCommit * instances inserted into it. */ private static final int IN_PENDING = RevWalk.REWRITE; private CanonicalTreeParser treeWalk; private BlockObjQueue pendingObjects; private RevTree currentTree; private boolean fromTreeWalk; private RevTree nextSubtree; /** * Create a new revision and object walker for a given repository. * * @param repo * the repository the walker will obtain data from. */ public ObjectWalk(final Repository repo) { super(repo); pendingObjects = new BlockObjQueue(); treeWalk = new CanonicalTreeParser(); } /** * Mark an object or commit to start graph traversal from. * <p> * Callers are encouraged to use {@link RevWalk#parseAny(AnyObjectId)} * instead of {@link RevWalk#lookupAny(AnyObjectId, int)}, as this method * requires the object to be parsed before it can be added as a root for the * traversal. * <p> * The method will automatically parse an unparsed object, but error * handling may be more difficult for the application to explain why a * RevObject is not actually valid. The object pool of this walker would * also be 'poisoned' by the invalid RevObject. * <p> * This method will automatically call {@link RevWalk#markStart(RevCommit)} * if passed RevCommit instance, or a RevTag that directly (or indirectly) * references a RevCommit. * * @param o * the object to start traversing from. The object passed must be * from this same revision walker. * @throws MissingObjectException * the object supplied is not available from the object * database. This usually indicates the supplied object is * invalid, but the reference was constructed during an earlier * invocation to {@link RevWalk#lookupAny(AnyObjectId, int)}. * @throws IncorrectObjectTypeException * the object was not parsed yet and it was discovered during * parsing that it is not actually the type of the instance * passed in. This usually indicates the caller used the wrong * type in a {@link RevWalk#lookupAny(AnyObjectId, int)} call. * @throws IOException * a pack file or loose object could not be read. */ public void markStart(RevObject o) throws MissingObjectException, IncorrectObjectTypeException, IOException { while (o instanceof RevTag) { addObject(o); o = ((RevTag) o).getObject(); parseHeaders(o); } if (o instanceof RevCommit) super.markStart((RevCommit) o); else addObject(o); } /** * Mark an object to not produce in the output. * <p> * Uninteresting objects denote not just themselves but also their entire * reachable chain, back until the merge base of an uninteresting commit and * an otherwise interesting commit. * <p> * Callers are encouraged to use {@link RevWalk#parseAny(AnyObjectId)} * instead of {@link RevWalk#lookupAny(AnyObjectId, int)}, as this method * requires the object to be parsed before it can be added as a root for the * traversal. * <p> * The method will automatically parse an unparsed object, but error * handling may be more difficult for the application to explain why a * RevObject is not actually valid. The object pool of this walker would * also be 'poisoned' by the invalid RevObject. * <p> * This method will automatically call {@link RevWalk#markStart(RevCommit)} * if passed RevCommit instance, or a RevTag that directly (or indirectly) * references a RevCommit. * * @param o * the object to start traversing from. The object passed must be * @throws MissingObjectException * the object supplied is not available from the object * database. This usually indicates the supplied object is * invalid, but the reference was constructed during an earlier * invocation to {@link RevWalk#lookupAny(AnyObjectId, int)}. * @throws IncorrectObjectTypeException * the object was not parsed yet and it was discovered during * parsing that it is not actually the type of the instance * passed in. This usually indicates the caller used the wrong * type in a {@link RevWalk#lookupAny(AnyObjectId, int)} call. * @throws IOException * a pack file or loose object could not be read. */ public void markUninteresting(RevObject o) throws MissingObjectException, IncorrectObjectTypeException, IOException { while (o instanceof RevTag) { o.flags |= UNINTERESTING; if (hasRevSort(RevSort.BOUNDARY)) addObject(o); o = ((RevTag) o).getObject(); parseHeaders(o); } if (o instanceof RevCommit) super.markUninteresting((RevCommit) o); else if (o instanceof RevTree) markTreeUninteresting((RevTree) o); else o.flags |= UNINTERESTING; if (o.getType() != Constants.OBJ_COMMIT && hasRevSort(RevSort.BOUNDARY)) { addObject(o); } } @Override public RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { for (;;) { final RevCommit r = super.next(); if (r == null) return null; if ((r.flags & UNINTERESTING) != 0) { markTreeUninteresting(r.getTree()); if (hasRevSort(RevSort.BOUNDARY)) { pendingObjects.add(r.getTree()); return r; } continue; } pendingObjects.add(r.getTree()); return r; } } /** * Pop the next most recent object. * * @return next most recent object; null if traversal is over. * @throws MissingObjectException * one or or more of the next objects are not available from the * object database, but were thought to be candidates for * traversal. This usually indicates a broken link. * @throws IncorrectObjectTypeException * one or or more of the objects in a tree do not match the type * indicated. * @throws IOException * a pack file or loose object could not be read. */ public RevObject nextObject() throws MissingObjectException, IncorrectObjectTypeException, IOException { fromTreeWalk = false; if (nextSubtree != null) { treeWalk = treeWalk.createSubtreeIterator0(db, nextSubtree, curs); nextSubtree = null; } while (!treeWalk.eof()) { final FileMode mode = treeWalk.getEntryFileMode(); final int sType = mode.getObjectType(); switch (sType) { case Constants.OBJ_BLOB: { treeWalk.getEntryObjectId(idBuffer); final RevBlob o = lookupBlob(idBuffer); if ((o.flags & SEEN) != 0) break; o.flags |= SEEN; if (shouldSkipObject(o)) break; fromTreeWalk = true; return o; } case Constants.OBJ_TREE: { treeWalk.getEntryObjectId(idBuffer); final RevTree o = lookupTree(idBuffer); if ((o.flags & SEEN) != 0) break; o.flags |= SEEN; if (shouldSkipObject(o)) break; nextSubtree = o; fromTreeWalk = true; return o; } default: if (FileMode.GITLINK.equals(mode)) break; treeWalk.getEntryObjectId(idBuffer); throw new CorruptObjectException("Invalid mode " + mode - + " for " + idBuffer.name() + " " - + treeWalk.getEntryPathString() + " in " + currentTree - + "."); + + " for " + idBuffer.name() + " '" + + treeWalk.getEntryPathString() + "' in " + + currentTree.name() + "."); } treeWalk = treeWalk.next(); } for (;;) { final RevObject o = pendingObjects.next(); if (o == null) return null; if ((o.flags & SEEN) != 0) continue; o.flags |= SEEN; if (shouldSkipObject(o)) continue; if (o instanceof RevTree) { currentTree = (RevTree) o; treeWalk = treeWalk.resetRoot(db, currentTree, curs); } return o; } } private final boolean shouldSkipObject(final RevObject o) { return (o.flags & UNINTERESTING) != 0 && !hasRevSort(RevSort.BOUNDARY); } /** * Verify all interesting objects are available, and reachable. * <p> * Callers should populate starting points and ending points with * {@link #markStart(RevObject)} and {@link #markUninteresting(RevObject)} * and then use this method to verify all objects between those two points * exist in the repository and are readable. * <p> * This method returns successfully if everything is connected; it throws an * exception if there is a connectivity problem. The exception message * provides some detail about the connectivity failure. * * @throws MissingObjectException * one or or more of the next objects are not available from the * object database, but were thought to be candidates for * traversal. This usually indicates a broken link. * @throws IncorrectObjectTypeException * one or or more of the objects in a tree do not match the type * indicated. * @throws IOException * a pack file or loose object could not be read. */ public void checkConnectivity() throws MissingObjectException, IncorrectObjectTypeException, IOException { for (;;) { final RevCommit c = next(); if (c == null) break; } for (;;) { final RevObject o = nextObject(); if (o == null) break; if (o instanceof RevBlob && !db.hasObject(o)) throw new MissingObjectException(o, Constants.TYPE_BLOB); } } /** * Get the current object's complete path. * <p> * This method is not very efficient and is primarily meant for debugging * and final output generation. Applications should try to avoid calling it, * and if invoked do so only once per interesting entry, where the name is * absolutely required for correct function. * * @return complete path of the current entry, from the root of the * repository. If the current entry is in a subtree there will be at * least one '/' in the returned string. Null if the current entry * has no path, such as for annotated tags or root level trees. */ public String getPathString() { return fromTreeWalk ? treeWalk.getEntryPathString() : null; } @Override public void dispose() { super.dispose(); pendingObjects = new BlockObjQueue(); nextSubtree = null; currentTree = null; } @Override protected void reset(final int retainFlags) { super.reset(retainFlags); pendingObjects = new BlockObjQueue(); nextSubtree = null; } private void addObject(final RevObject o) { if ((o.flags & IN_PENDING) == 0) { o.flags |= IN_PENDING; pendingObjects.add(o); } } private void markTreeUninteresting(final RevTree tree) throws MissingObjectException, IncorrectObjectTypeException, IOException { if ((tree.flags & UNINTERESTING) != 0) return; tree.flags |= UNINTERESTING; treeWalk = treeWalk.resetRoot(db, tree, curs); while (!treeWalk.eof()) { final FileMode mode = treeWalk.getEntryFileMode(); final int sType = mode.getObjectType(); switch (sType) { case Constants.OBJ_BLOB: { treeWalk.getEntryObjectId(idBuffer); lookupBlob(idBuffer).flags |= UNINTERESTING; break; } case Constants.OBJ_TREE: { treeWalk.getEntryObjectId(idBuffer); final RevTree t = lookupTree(idBuffer); if ((t.flags & UNINTERESTING) == 0) { t.flags |= UNINTERESTING; treeWalk = treeWalk.createSubtreeIterator0(db, t, curs); continue; } break; } default: if (FileMode.GITLINK.equals(mode)) break; treeWalk.getEntryObjectId(idBuffer); throw new CorruptObjectException("Invalid mode " + mode + " for " + idBuffer.name() + " " + treeWalk.getEntryPathString() + " in " + tree + "."); } treeWalk = treeWalk.next(); } } }
true
true
public RevObject nextObject() throws MissingObjectException, IncorrectObjectTypeException, IOException { fromTreeWalk = false; if (nextSubtree != null) { treeWalk = treeWalk.createSubtreeIterator0(db, nextSubtree, curs); nextSubtree = null; } while (!treeWalk.eof()) { final FileMode mode = treeWalk.getEntryFileMode(); final int sType = mode.getObjectType(); switch (sType) { case Constants.OBJ_BLOB: { treeWalk.getEntryObjectId(idBuffer); final RevBlob o = lookupBlob(idBuffer); if ((o.flags & SEEN) != 0) break; o.flags |= SEEN; if (shouldSkipObject(o)) break; fromTreeWalk = true; return o; } case Constants.OBJ_TREE: { treeWalk.getEntryObjectId(idBuffer); final RevTree o = lookupTree(idBuffer); if ((o.flags & SEEN) != 0) break; o.flags |= SEEN; if (shouldSkipObject(o)) break; nextSubtree = o; fromTreeWalk = true; return o; } default: if (FileMode.GITLINK.equals(mode)) break; treeWalk.getEntryObjectId(idBuffer); throw new CorruptObjectException("Invalid mode " + mode + " for " + idBuffer.name() + " " + treeWalk.getEntryPathString() + " in " + currentTree + "."); } treeWalk = treeWalk.next(); } for (;;) { final RevObject o = pendingObjects.next(); if (o == null) return null; if ((o.flags & SEEN) != 0) continue; o.flags |= SEEN; if (shouldSkipObject(o)) continue; if (o instanceof RevTree) { currentTree = (RevTree) o; treeWalk = treeWalk.resetRoot(db, currentTree, curs); } return o; } }
public RevObject nextObject() throws MissingObjectException, IncorrectObjectTypeException, IOException { fromTreeWalk = false; if (nextSubtree != null) { treeWalk = treeWalk.createSubtreeIterator0(db, nextSubtree, curs); nextSubtree = null; } while (!treeWalk.eof()) { final FileMode mode = treeWalk.getEntryFileMode(); final int sType = mode.getObjectType(); switch (sType) { case Constants.OBJ_BLOB: { treeWalk.getEntryObjectId(idBuffer); final RevBlob o = lookupBlob(idBuffer); if ((o.flags & SEEN) != 0) break; o.flags |= SEEN; if (shouldSkipObject(o)) break; fromTreeWalk = true; return o; } case Constants.OBJ_TREE: { treeWalk.getEntryObjectId(idBuffer); final RevTree o = lookupTree(idBuffer); if ((o.flags & SEEN) != 0) break; o.flags |= SEEN; if (shouldSkipObject(o)) break; nextSubtree = o; fromTreeWalk = true; return o; } default: if (FileMode.GITLINK.equals(mode)) break; treeWalk.getEntryObjectId(idBuffer); throw new CorruptObjectException("Invalid mode " + mode + " for " + idBuffer.name() + " '" + treeWalk.getEntryPathString() + "' in " + currentTree.name() + "."); } treeWalk = treeWalk.next(); } for (;;) { final RevObject o = pendingObjects.next(); if (o == null) return null; if ((o.flags & SEEN) != 0) continue; o.flags |= SEEN; if (shouldSkipObject(o)) continue; if (o instanceof RevTree) { currentTree = (RevTree) o; treeWalk = treeWalk.resetRoot(db, currentTree, curs); } return o; } }
diff --git a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/TaskListInterestFilter.java b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/TaskListInterestFilter.java index ed5faf08f..c94cea817 100644 --- a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/TaskListInterestFilter.java +++ b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/TaskListInterestFilter.java @@ -1,220 +1,219 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.internal.context.ui; import java.util.Calendar; import java.util.Set; import org.eclipse.mylyn.internal.tasks.core.LocalRepositoryConnector; import org.eclipse.mylyn.internal.tasks.core.ScheduledTaskContainer; import org.eclipse.mylyn.internal.tasks.core.TaskActivityManager; import org.eclipse.mylyn.internal.tasks.core.TaskArchive; import org.eclipse.mylyn.internal.tasks.ui.AbstractTaskListFilter; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.core.AbstractTaskContainer; import org.eclipse.mylyn.tasks.core.AbstractTask.RepositoryTaskSyncState; import org.eclipse.mylyn.tasks.ui.TasksUiPlugin; /** * Goal is to have this reuse as much of the super as possible. * * @author Mik Kersten * @author Rob Elves */ public class TaskListInterestFilter extends AbstractTaskListFilter { @Override public boolean select(Object parent, Object child) { - System.err.println(">>>"); try { if (child instanceof ScheduledTaskContainer) { ScheduledTaskContainer dateRangeTaskContainer = (ScheduledTaskContainer) child; return isDateRangeInteresting(dateRangeTaskContainer); } if (child instanceof AbstractTask) { AbstractTask task = null; if (child instanceof AbstractTask) { task = (AbstractTask) child; } if (task != null) { if (isUninteresting(parent, task)) { return false; } else if (isInteresting(parent, task)) { if (parent instanceof TaskArchive) { return (revealInArchive(task) && shouldAlwaysShow(child, task, TasksUiPlugin.getDefault() .groupSubtasks(task))); } return true; } } } else if (child instanceof TaskArchive) { // Display Archive if contains otherwise non-visible tasks that should always show boolean hasTasksToReveal = false; for (AbstractTask task : ((TaskArchive) child).getChildren()) { if (revealInArchive(task) && shouldAlwaysShow(child, task, TasksUiPlugin.getDefault().groupSubtasks(task))) { hasTasksToReveal = true; break; } } return hasTasksToReveal; } else if (child instanceof AbstractTaskContainer) { Set<AbstractTask> children = ((AbstractTaskContainer) child).getChildren(); // Always display empty containers if (children.size() == 0) { return false; } for (AbstractTask task : children) { if (shouldAlwaysShow(child, task, TasksUiPlugin.getDefault().groupSubtasks(task))) { return true; } } } } catch (Throwable t) { StatusHandler.fail(t, "interest filter failed", false); } return false; } private boolean revealInArchive(AbstractTask task) { if (TasksUiPlugin.getTaskListManager().getTaskList().getContainerForHandle(task.getHandleIdentifier()) == null && TasksUiPlugin.getTaskListManager() .getTaskList() .getQueriesForHandle(task.getHandleIdentifier()) .isEmpty()) { return true; } return false; } private boolean isDateRangeInteresting(ScheduledTaskContainer container) { return TasksUiPlugin.getTaskActivityManager().isWeekDay(container); // return (TasksUiPlugin.getTaskListManager().isWeekDay(container) && (container.isPresent() || container.isFuture())); } protected boolean isUninteresting(Object parent, AbstractTask task) { return !task.isActive() && !hasInterestingSubTasks(parent, task, true) && ((task.isCompleted() && !TaskActivityManager.getInstance().isCompletedToday(task) && !hasChanges( parent, task)) || (TaskActivityManager.getInstance().isScheduledAfterThisWeek(task)) && !hasChanges(parent, task)); } // TODO: make meta-context more explicit protected boolean isInteresting(Object parent, AbstractTask task) { return shouldAlwaysShow(parent, task, TasksUiPlugin.getDefault().groupSubtasks(task)); } public boolean shouldAlwaysShow(Object parent, AbstractTask task, boolean checkSubTasks) { return task.isActive() || hasChanges(parent, task) || (TaskActivityManager.getInstance().isCompletedToday(task)) || shouldShowInFocusedWorkweekDateContainer(parent, task) || (isInterestingForThisWeek(parent, task) && !task.isCompleted()) || (TaskActivityManager.getInstance().isOverdue(task)) || hasInterestingSubTasks(parent, task, checkSubTasks) || LocalRepositoryConnector.DEFAULT_SUMMARY.equals(task.getSummary()); // || isCurrentlySelectedInEditor(task); } private boolean hasInterestingSubTasks(Object parent, AbstractTask task, boolean checkSubTasks) { if (!checkSubTasks) { return false; } if (!TasksUiPlugin.getDefault().groupSubtasks(task)) { return false; } if (task.getChildren() != null && task.getChildren().size() > 0) { for (AbstractTask subTask : task.getChildren()) { if (shouldAlwaysShow(parent, subTask, false)) { return true; } } } return false; } private static boolean shouldShowInFocusedWorkweekDateContainer(Object parent, AbstractTask task) { if (parent instanceof ScheduledTaskContainer) { if (!TasksUiPlugin.getTaskActivityManager().isWeekDay((ScheduledTaskContainer) parent)) { return false; } if (TaskActivityManager.getInstance().isOverdue(task) || task.isPastReminder()) return true; ScheduledTaskContainer container = (ScheduledTaskContainer) parent; Calendar previousCal = TasksUiPlugin.getTaskActivityManager().getActivityPrevious().getEnd(); Calendar nextCal = TasksUiPlugin.getTaskActivityManager().getActivityNextWeek().getStart(); if (container.getEnd().compareTo(previousCal) > 0 && container.getStart().compareTo(nextCal) < 0) { // within workweek return true; } } return false; } public static boolean isInterestingForThisWeek(Object parent, AbstractTask task) { if (parent instanceof ScheduledTaskContainer) { return shouldShowInFocusedWorkweekDateContainer(parent, task); } else { return TasksUiPlugin.getTaskActivityManager().isScheduledForThisWeek(task) || TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task) || task.isPastReminder() || TasksUiPlugin.getTaskActivityManager().isDueThisWeek(task); } } public static boolean hasChanges(Object parent, AbstractTask task) { if (parent instanceof ScheduledTaskContainer) { if (!shouldShowInFocusedWorkweekDateContainer(parent, task)) { return false; } } boolean result = false; if (task != null) { if (task.getLastReadTimeStamp() == null) { return true; } else if (task.getSynchronizationState() == RepositoryTaskSyncState.OUTGOING) { return true; } else if (task.getSynchronizationState() == RepositoryTaskSyncState.INCOMING && !(parent instanceof ScheduledTaskContainer)) { return true; } else if (task.getSynchronizationState() == RepositoryTaskSyncState.CONFLICT) { return true; } return hasChangesHelper(parent, task); } return result; } private static boolean hasChangesHelper(Object parent, AbstractTaskContainer container) { boolean result = false; for (AbstractTask task : container.getChildren()) { if (task != null) { if (task.getLastReadTimeStamp() == null) { result = true; } else if (task.getSynchronizationState() == RepositoryTaskSyncState.OUTGOING) { result = true; } else if (task.getSynchronizationState() == RepositoryTaskSyncState.INCOMING && !(parent instanceof ScheduledTaskContainer)) { result = true; } else if (task.getSynchronizationState() == RepositoryTaskSyncState.CONFLICT) { result = true; } else if (task.getChildren() != null && task.getChildren().size() > 0) { result = hasChangesHelper(parent, task); } } } return result; } }
true
true
public boolean select(Object parent, Object child) { System.err.println(">>>"); try { if (child instanceof ScheduledTaskContainer) { ScheduledTaskContainer dateRangeTaskContainer = (ScheduledTaskContainer) child; return isDateRangeInteresting(dateRangeTaskContainer); } if (child instanceof AbstractTask) { AbstractTask task = null; if (child instanceof AbstractTask) { task = (AbstractTask) child; } if (task != null) { if (isUninteresting(parent, task)) { return false; } else if (isInteresting(parent, task)) { if (parent instanceof TaskArchive) { return (revealInArchive(task) && shouldAlwaysShow(child, task, TasksUiPlugin.getDefault() .groupSubtasks(task))); } return true; } } } else if (child instanceof TaskArchive) { // Display Archive if contains otherwise non-visible tasks that should always show boolean hasTasksToReveal = false; for (AbstractTask task : ((TaskArchive) child).getChildren()) { if (revealInArchive(task) && shouldAlwaysShow(child, task, TasksUiPlugin.getDefault().groupSubtasks(task))) { hasTasksToReveal = true; break; } } return hasTasksToReveal; } else if (child instanceof AbstractTaskContainer) { Set<AbstractTask> children = ((AbstractTaskContainer) child).getChildren(); // Always display empty containers if (children.size() == 0) { return false; } for (AbstractTask task : children) { if (shouldAlwaysShow(child, task, TasksUiPlugin.getDefault().groupSubtasks(task))) { return true; } } } } catch (Throwable t) { StatusHandler.fail(t, "interest filter failed", false); } return false; }
public boolean select(Object parent, Object child) { try { if (child instanceof ScheduledTaskContainer) { ScheduledTaskContainer dateRangeTaskContainer = (ScheduledTaskContainer) child; return isDateRangeInteresting(dateRangeTaskContainer); } if (child instanceof AbstractTask) { AbstractTask task = null; if (child instanceof AbstractTask) { task = (AbstractTask) child; } if (task != null) { if (isUninteresting(parent, task)) { return false; } else if (isInteresting(parent, task)) { if (parent instanceof TaskArchive) { return (revealInArchive(task) && shouldAlwaysShow(child, task, TasksUiPlugin.getDefault() .groupSubtasks(task))); } return true; } } } else if (child instanceof TaskArchive) { // Display Archive if contains otherwise non-visible tasks that should always show boolean hasTasksToReveal = false; for (AbstractTask task : ((TaskArchive) child).getChildren()) { if (revealInArchive(task) && shouldAlwaysShow(child, task, TasksUiPlugin.getDefault().groupSubtasks(task))) { hasTasksToReveal = true; break; } } return hasTasksToReveal; } else if (child instanceof AbstractTaskContainer) { Set<AbstractTask> children = ((AbstractTaskContainer) child).getChildren(); // Always display empty containers if (children.size() == 0) { return false; } for (AbstractTask task : children) { if (shouldAlwaysShow(child, task, TasksUiPlugin.getDefault().groupSubtasks(task))) { return true; } } } } catch (Throwable t) { StatusHandler.fail(t, "interest filter failed", false); } return false; }
diff --git a/src/com/sun/jini/jeri/internal/runtime/SelectionManager.java b/src/com/sun/jini/jeri/internal/runtime/SelectionManager.java index 44f54104..ef739caa 100644 --- a/src/com/sun/jini/jeri/internal/runtime/SelectionManager.java +++ b/src/com/sun/jini/jeri/internal/runtime/SelectionManager.java @@ -1,624 +1,625 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.jini.jeri.internal.runtime; import com.sun.jini.logging.Levels; import com.sun.jini.thread.Executor; import com.sun.jini.thread.GetThreadPoolAction; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedChannelException; import java.nio.channels.IllegalBlockingModeException; import java.nio.channels.Pipe; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.security.AccessController; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.logging.Level; import java.util.logging.Logger; /** * A SelectionManager provides an event dispatching layer on top of the * java.nio.Selector and java.nio.SelectableChannel abstractions; it manages * one-shot registrations of interest in I/O readiness events and * dispatching notifications of such events to registered callback objects. * * SelectionManager is designed to support multiple select/dispatch threads * to allow for improved I/O concurrency on symmetric multiprocessor systems. * * If interest in a particular I/O event is (re-)registered while there is a * blocking select operation in progress, that select operation must be woken * up so that it can take the new interest into account; this wakeup is * achieved by writing a byte to an internal pipe that is registered with the * underlying selector. * * A current limitation of this API is that it does not allow an executing * callback to yield control in such a way that it will be scheduled to * execute again without another I/O readiness event occurring. Therefore, * data that gets read during a callback must also get processed, unless such * processing depends on more data that has not yet been read (like the * remainder of a partial message). * * <p>This implementation uses the {@link Logger} named * <code>com.sun.jini.jeri.internal.runtime.SelectionManager</code> to * log information at the following levels: * * <p><table summary="Describes what is logged by SelectionManager at * various logging levels" border=1 cellpadding=5> * * <tr> <th> Level <th> Description * * <tr> <td> {@link Levels#HANDLED HANDLED} <td> I/O exception caught * from select operation * * </table> * * @author Sun Microsystems, Inc. **/ public final class SelectionManager { /** number of concurrent I/O processing threads */ private static final int concurrency = 1; // REMIND: get from property? private static final Logger logger = Logger.getLogger( "com.sun.jini.jeri.internal.runtime.SelectionManager"); /** pool of threads for executing tasks in system thread group */ private static final Executor systemThreadPool = (Executor) AccessController.doPrivileged(new GetThreadPoolAction(false)); /** shared Selector used by this SelectionManager */ private final Selector selector; /** internal pipe used to wake up a blocked select operation */ private final Pipe.SinkChannel wakeupPipeSink; private final Pipe.SourceChannel wakeupPipeSource; private final SelectionKey wakeupPipeKey; private final ByteBuffer wakeupBuffer = ByteBuffer.allocate(2); /** set of registered channels, to detect duplicate registrations */ private final Map registeredChannels = Collections.synchronizedMap(new WeakHashMap()); /** * lock guarding selectingThread, wakeupPending, renewQueue, readyQueue, * renewMaskRef, and mutable state of all Key instances. */ private final Object lock = new Object(); /** thread with exclusive right to perform a select operation, if any */ private Thread selectingThread = null; /** true if a wakeup has been requested but not yet processed */ private boolean wakeupPending = false; /* * The following two queues of Key objects are implemented as LIFO * linked lists with internally threaded links for fast addition and * removal of elements (no memory allocation overhead) and so that * multiple entries for the same channel get implicitly combined. * LIFO ordering is OK because the entire queue always gets drained * and processed at once, and in between such processing, addition * order is arbitrary anyway. */ /** queue of keys that need to have interest masks updated */ private Key renewQueue = null; /** queue of keys that have I/O operations ready to be handled */ private Key readyQueue = null; /** holder used for pass-by-reference invocations */ private final int[] renewMaskRef = new int[1]; /** * Creates a new SelectionManager. * * REMIND: Is this necessary, or should we just provide access to * a singleton instance? */ public SelectionManager() throws IOException { // REMIND: create threads and other resources lazily? selector = Selector.open(); Pipe pipe = Pipe.open(); wakeupPipeSink = pipe.sink(); wakeupPipeSource = pipe.source(); wakeupPipeSource.configureBlocking(false); wakeupPipeKey = wakeupPipeSource.register(selector, SelectionKey.OP_READ); for (int i = 0; i < concurrency; i++) { systemThreadPool.execute(new SelectLoop(), "I/O SelectionManager-" + i); } // REMIND: How do these threads and other resources get cleaned up? // REMIND: Should there be an explicit close method? } /** * Registers the given SelectableChannel with this SelectionManager. * After registration, the returned Key's renewInterestMask method may * be used to register one-shot interest in particular I/O events. */ public Key register(SelectableChannel channel, SelectionHandler handler) { if (registeredChannels.containsKey(channel)) { throw new IllegalStateException("channel already registered"); } Key key = new Key(channel, handler); registeredChannels.put(channel, null); return key; } /** * SelectionHandler is the callback interface for an object that will * process an I/O readiness event that has been detected by a * SelectionManager. */ public interface SelectionHandler { void handleSelection(int readyMask, Key key); } /** * A Key represents a given SelectableChannel's registration with this * SelectionManager. Externally, this object is used to re-register * interest in I/O readiness events that have been previously detected * and dispatched. */ public final class Key { /** the channel that this Key represents a registration for */ final SelectableChannel channel; /** the supplied callback object for dispatching I/O events */ final SelectionHandler handler; // mutable instance state guarded by enclosing SelectionManager's lock: /** * the SelectionKey representing this Key's registration with the * internal Selector, or null if it hasn't yet been registered */ SelectionKey selectionKey = null; /** the current interest mask established with the SelectionKey */ int interestMask = 0; boolean onRenewQueue = false; // invariant: == (renewMask != 0) Key renewQueueNext = null; // null if !onRenewQueue int renewMask = 0; boolean onReadyQueue = false; // invariant: == (readyMask != 0) Key readyQueueNext = null; // null if !onReadyQueue int readyMask = 0; /* * other invariants: * * (renewMask & interestMask) == 0 * (interestMask & readyMask) == 0 * (renewMask & readyMask) == 0 */ Key(SelectableChannel channel, SelectionHandler handler) { this.channel = channel; this.handler = handler; } /** * Renews interest in receiving notifications when the I/O operations * identified by the specified mask are ready for the associated * SelectableChannel. The specified mask identifies I/O operations * with the same bit values as would a java.nio.SelectionKey for the * same SelectableChannel. * * Some time after one of the operations specified in the mask is * detected to be ready, the previously-registered SelectionHandler * callback object will be invoked to handle the readiness event. * * An event for each operation specified will only be dispatched to the * callback handler once for the invocation of this method; to * re-register interest in subsequent readiness of the same operation * for the given channel, this method must be invoked again. */ public void renewInterestMask(int mask) throws ClosedChannelException { if (!channel.isOpen()) { throw new ClosedChannelException(); } if ((mask & ~channel.validOps()) != 0) { throw new IllegalArgumentException( "invalid mask " + mask + " (valid mask " + channel.validOps() + ")"); } if (channel.isBlocking()) { throw new IllegalBlockingModeException(); } synchronized (lock) { int delta = mask & ~(renewMask | interestMask | readyMask); if (delta != 0) { addOrUpdateRenewQueue(this, delta); if (selectingThread != null && !wakeupPending) { wakeupSelector(); wakeupPending = true; } } } } } /** * SelectLoop provides the main loop for each I/O processing thread. */ private class SelectLoop implements Runnable { private long lastExceptionTime = 0L; // local to select thread private int recentExceptionCount; // local to select thread public void run() { int[] readyMaskRef = new int[1]; while (true) { try { Key readyKey = waitForReadyKey(readyMaskRef); readyKey.handler.handleSelection(readyMaskRef[0], readyKey); } catch (Throwable t) { try { logger.log(Level.WARNING, "select loop throws", t); } catch (Throwable tt) { } throttleLoopOnException(); } } } /** * Throttles the select loop after an exception has been * caught: if a burst of 10 exceptions in 5 seconds occurs, * then wait for 10 seconds to curb busy CPU usage. **/ private void throttleLoopOnException() { long now = System.currentTimeMillis(); if (lastExceptionTime == 0L || (now - lastExceptionTime) > 5000) { // last exception was long ago (or this is the first) lastExceptionTime = now; recentExceptionCount = 0; } else { // exception burst window was started recently if (++recentExceptionCount >= 10) { try { Thread.sleep(10000); } catch (InterruptedException ignore) { } } } } } /** * Waits until one of the registered channels is ready for one or more * I/O operations. The Key for the ready channel is returned, and the * first element of the supplied array is set to the mask of the * channel's ready operations. * * If there is a ready channel available, then its key is returned. * If another thread is already performing a select operation, then the * current thread waits for that thread to complete and then begins * again. Otherwise, the current thread assumes the responsibility of * performing the next select operation. */ private Key waitForReadyKey(int[] readyMaskOut) throws InterruptedException { assert !Thread.holdsLock(lock); assert readyMaskOut != null && readyMaskOut.length == 1; boolean needToClearSelectingThread = false; Set selectedKeys = selector.selectedKeys(); try { synchronized (lock) { while (isReadyQueueEmpty() && selectingThread != null) { lock.wait(); } if (!isReadyQueueEmpty()) { Key readyKey = removeFromReadyQueue(readyMaskOut); lock.notify(); return readyKey; } assert selectingThread == null; selectingThread = Thread.currentThread(); needToClearSelectingThread = true; processRenewQueue(); } // wakeup allowed while (true) { try { int n = selector.select(); if (Thread.interrupted()) { throw new InterruptedException(); } } catch (Error e) { - if (e.getMessage().startsWith("POLLNVAL")) { + String message = e.getMessage(); + if (message != null && message.startsWith("POLLNVAL")) { Thread.yield(); continue; // work around 4458268 } else { throw e; } } catch (CancelledKeyException e) { continue; // work around 4458268 } catch (NullPointerException e) { continue; // work around 4729342 } catch (IOException e) { logger.log(Levels.HANDLED, "thrown by select, continuing", e); continue; // work around 4504001 } synchronized (lock) { if (wakeupPending && selectedKeys.contains(wakeupPipeKey)) { drainWakeupPipe(); // clear wakeup state wakeupPending = false; selectedKeys.remove(wakeupPipeKey); } if (selectedKeys.isEmpty()) { processRenewQueue(); continue; } selectingThread = null; needToClearSelectingThread = false; lock.notify(); Iterator iter = selectedKeys.iterator(); assert iter.hasNext(); // there must be at least one while (iter.hasNext()) { SelectionKey selectionKey = (SelectionKey) iter.next(); Key key = (Key) selectionKey.attachment(); int readyMask = 0; try { readyMask = selectionKey.readyOps(); assert readyMask != 0; assert (key.interestMask & readyMask) == readyMask; /* * Remove interest in I/O events detected to be * ready; interest must be renewed after each * notification. */ int newInterestMask = key.interestMask & ~readyMask; assert key.interestMask == selectionKey.interestOps(); key.selectionKey.interestOps(newInterestMask); key.interestMask = newInterestMask; } catch (CancelledKeyException e) { /* * If channel is closed, then all interested events * become considered ready immediately. */ readyMask |= key.interestMask; key.interestMask = 0; } addOrUpdateReadyQueue(key, readyMask); iter.remove(); } return removeFromReadyQueue(readyMaskOut); } // wakeup NOT allowed } } finally { if (needToClearSelectingThread) { synchronized (lock) { if (wakeupPending && selectedKeys.contains(wakeupPipeKey)) { drainWakeupPipe(); // clear wakeup state wakeupPending = false; selectedKeys.remove(wakeupPipeKey); } selectingThread = null; needToClearSelectingThread = false; lock.notify(); } // wakeup NOT allowed } } } private void wakeupSelector() { assert Thread.holdsLock(lock); assert wakeupPending == false; wakeupBuffer.clear().limit(1); try { wakeupPipeSink.write(wakeupBuffer); } catch (IOException e) { // REMIND: what if thread was interrupted? Error error = new AssertionError("unexpected I/O exception"); error.initCause(e); throw error; } } private void drainWakeupPipe() { assert Thread.holdsLock(lock); assert selectingThread != null; do { wakeupBuffer.clear(); try { wakeupPipeSource.read(wakeupBuffer); } catch (IOException e) { // REMIND: what if thread was interrupted? Error error = new AssertionError("unexpected I/O exception"); error.initCause(e); throw error; } } while (!wakeupBuffer.hasRemaining()); } /** * In preparation for performing a select operation, process all new * and renewed interest registrations so that current SelectionKey * interest masks are up to date. * * This method must not be invoked while there is a select operation in * progress (because otherwise it could block indefinitely); therefore, * it must be invoked only by a thread that has the exclusive right to * perform a select operation. */ private void processRenewQueue() { assert Thread.holdsLock(lock); assert selectingThread != null; while (!isRenewQueueEmpty()) { Key key = removeFromRenewQueue(renewMaskRef); int renewMask = renewMaskRef[0]; assert renewMask != 0; if (key.selectionKey == null) { assert key.interestMask == 0 && key.readyMask == 0; try { key.selectionKey = key.channel.register(selector, renewMask); key.selectionKey.attach(key); key.interestMask = renewMask; } catch (ClosedChannelException e) { addOrUpdateReadyQueue(key, renewMask); } catch (IllegalBlockingModeException e) { addOrUpdateReadyQueue(key, renewMask); } } else { assert (key.interestMask & renewMask) == 0; int newInterestMask = key.interestMask | renewMask; try { assert key.interestMask == key.selectionKey.interestOps(); key.selectionKey.interestOps(newInterestMask); key.interestMask = newInterestMask; } catch (CancelledKeyException e) { addOrUpdateReadyQueue(key, newInterestMask); key.interestMask = 0; } assert (key.interestMask & key.readyMask) == 0; } } } /* * Queue manipulation utilities: */ private boolean isRenewQueueEmpty() { assert Thread.holdsLock(lock); return renewQueue == null; } private Key removeFromRenewQueue(int[] renewMaskOut) { assert renewMaskOut != null && renewMaskOut.length == 1; assert Thread.holdsLock(lock); Key key = renewQueue; assert key != null; assert key.onRenewQueue; assert key.renewMask != 0; renewMaskOut[0] = key.renewMask; key.renewMask = 0; renewQueue = key.renewQueueNext; key.renewQueueNext = null; key.onRenewQueue = false; return key; } private void addOrUpdateRenewQueue(Key key, int newRenewMask) { assert newRenewMask != 0; assert Thread.holdsLock(lock); if (!key.onRenewQueue) { assert key.renewMask == 0; assert key.renewQueueNext == null; key.renewMask = newRenewMask; key.renewQueueNext = renewQueue; renewQueue = key; key.onRenewQueue = true; } else { assert key.renewMask != 0; assert (key.renewMask & newRenewMask) == 0; key.renewMask |= newRenewMask; } } private boolean isReadyQueueEmpty() { assert Thread.holdsLock(lock); return readyQueue == null; } private Key removeFromReadyQueue(int[] readyMaskOut) { assert readyMaskOut != null && readyMaskOut.length == 1; assert Thread.holdsLock(lock); Key key = readyQueue; assert key != null; assert key.onReadyQueue; assert key.readyMask != 0; readyMaskOut[0] = key.readyMask; key.readyMask = 0; readyQueue = key.readyQueueNext; key.readyQueueNext = null; key.onReadyQueue = false; return key; } private void addOrUpdateReadyQueue(Key key, int newReadyMask) { assert newReadyMask != 0; assert Thread.holdsLock(lock); if (!key.onReadyQueue) { assert key.readyMask == 0; assert key.readyQueueNext == null; key.readyMask = newReadyMask; key.readyQueueNext = readyQueue; readyQueue = key; key.onReadyQueue = true; } else { assert key.readyMask != 0; assert (key.readyMask & newReadyMask) == 0; key.readyMask |= newReadyMask; } } }
true
true
private Key waitForReadyKey(int[] readyMaskOut) throws InterruptedException { assert !Thread.holdsLock(lock); assert readyMaskOut != null && readyMaskOut.length == 1; boolean needToClearSelectingThread = false; Set selectedKeys = selector.selectedKeys(); try { synchronized (lock) { while (isReadyQueueEmpty() && selectingThread != null) { lock.wait(); } if (!isReadyQueueEmpty()) { Key readyKey = removeFromReadyQueue(readyMaskOut); lock.notify(); return readyKey; } assert selectingThread == null; selectingThread = Thread.currentThread(); needToClearSelectingThread = true; processRenewQueue(); } // wakeup allowed while (true) { try { int n = selector.select(); if (Thread.interrupted()) { throw new InterruptedException(); } } catch (Error e) { if (e.getMessage().startsWith("POLLNVAL")) { Thread.yield(); continue; // work around 4458268 } else { throw e; } } catch (CancelledKeyException e) { continue; // work around 4458268 } catch (NullPointerException e) { continue; // work around 4729342 } catch (IOException e) { logger.log(Levels.HANDLED, "thrown by select, continuing", e); continue; // work around 4504001 } synchronized (lock) { if (wakeupPending && selectedKeys.contains(wakeupPipeKey)) { drainWakeupPipe(); // clear wakeup state wakeupPending = false; selectedKeys.remove(wakeupPipeKey); } if (selectedKeys.isEmpty()) { processRenewQueue(); continue; } selectingThread = null; needToClearSelectingThread = false; lock.notify(); Iterator iter = selectedKeys.iterator(); assert iter.hasNext(); // there must be at least one while (iter.hasNext()) { SelectionKey selectionKey = (SelectionKey) iter.next(); Key key = (Key) selectionKey.attachment(); int readyMask = 0; try { readyMask = selectionKey.readyOps(); assert readyMask != 0; assert (key.interestMask & readyMask) == readyMask; /* * Remove interest in I/O events detected to be * ready; interest must be renewed after each * notification. */ int newInterestMask = key.interestMask & ~readyMask; assert key.interestMask == selectionKey.interestOps(); key.selectionKey.interestOps(newInterestMask); key.interestMask = newInterestMask; } catch (CancelledKeyException e) { /* * If channel is closed, then all interested events * become considered ready immediately. */ readyMask |= key.interestMask; key.interestMask = 0; } addOrUpdateReadyQueue(key, readyMask); iter.remove(); } return removeFromReadyQueue(readyMaskOut); } // wakeup NOT allowed } } finally { if (needToClearSelectingThread) { synchronized (lock) { if (wakeupPending && selectedKeys.contains(wakeupPipeKey)) { drainWakeupPipe(); // clear wakeup state wakeupPending = false; selectedKeys.remove(wakeupPipeKey); } selectingThread = null; needToClearSelectingThread = false; lock.notify(); } // wakeup NOT allowed } } }
private Key waitForReadyKey(int[] readyMaskOut) throws InterruptedException { assert !Thread.holdsLock(lock); assert readyMaskOut != null && readyMaskOut.length == 1; boolean needToClearSelectingThread = false; Set selectedKeys = selector.selectedKeys(); try { synchronized (lock) { while (isReadyQueueEmpty() && selectingThread != null) { lock.wait(); } if (!isReadyQueueEmpty()) { Key readyKey = removeFromReadyQueue(readyMaskOut); lock.notify(); return readyKey; } assert selectingThread == null; selectingThread = Thread.currentThread(); needToClearSelectingThread = true; processRenewQueue(); } // wakeup allowed while (true) { try { int n = selector.select(); if (Thread.interrupted()) { throw new InterruptedException(); } } catch (Error e) { String message = e.getMessage(); if (message != null && message.startsWith("POLLNVAL")) { Thread.yield(); continue; // work around 4458268 } else { throw e; } } catch (CancelledKeyException e) { continue; // work around 4458268 } catch (NullPointerException e) { continue; // work around 4729342 } catch (IOException e) { logger.log(Levels.HANDLED, "thrown by select, continuing", e); continue; // work around 4504001 } synchronized (lock) { if (wakeupPending && selectedKeys.contains(wakeupPipeKey)) { drainWakeupPipe(); // clear wakeup state wakeupPending = false; selectedKeys.remove(wakeupPipeKey); } if (selectedKeys.isEmpty()) { processRenewQueue(); continue; } selectingThread = null; needToClearSelectingThread = false; lock.notify(); Iterator iter = selectedKeys.iterator(); assert iter.hasNext(); // there must be at least one while (iter.hasNext()) { SelectionKey selectionKey = (SelectionKey) iter.next(); Key key = (Key) selectionKey.attachment(); int readyMask = 0; try { readyMask = selectionKey.readyOps(); assert readyMask != 0; assert (key.interestMask & readyMask) == readyMask; /* * Remove interest in I/O events detected to be * ready; interest must be renewed after each * notification. */ int newInterestMask = key.interestMask & ~readyMask; assert key.interestMask == selectionKey.interestOps(); key.selectionKey.interestOps(newInterestMask); key.interestMask = newInterestMask; } catch (CancelledKeyException e) { /* * If channel is closed, then all interested events * become considered ready immediately. */ readyMask |= key.interestMask; key.interestMask = 0; } addOrUpdateReadyQueue(key, readyMask); iter.remove(); } return removeFromReadyQueue(readyMaskOut); } // wakeup NOT allowed } } finally { if (needToClearSelectingThread) { synchronized (lock) { if (wakeupPending && selectedKeys.contains(wakeupPipeKey)) { drainWakeupPipe(); // clear wakeup state wakeupPending = false; selectedKeys.remove(wakeupPipeKey); } selectingThread = null; needToClearSelectingThread = false; lock.notify(); } // wakeup NOT allowed } } }
diff --git a/src/output/OutputIpe.java b/src/output/OutputIpe.java index 24af6d1..33d8f86 100644 --- a/src/output/OutputIpe.java +++ b/src/output/OutputIpe.java @@ -1,355 +1,355 @@ package output; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Locale; import java.util.Set; import model.Schedule; import model.Task; import model.TaskInstance; /** * This class can be used to output a schedule to an IPE file. * * @author Thom Castermans */ public class OutputIpe { /** List of colors supported by Ipe. */ public static final String[] IPE_COLORS = { "red", "green", "blue", "yellow", "orange", "gold", "purple", "gray", "brown", "navy", "pink", "seagreen", "turquoise", "violet", "darkblue", "darkcyan", "darkgray", "darkgreen", "darkmagenta", "darkorange", "darkred", "lightblue", "lightcyan", "lightgray", "lightgreen", "lightyellow" }; /** Size of grid, used in outputting graph. */ public static final int GRID_SIZE = 16; /** * Offset for graph in Ipe file, over X-axis. This is the X-coordinate of * the upper-left corner of the drawing. */ public static final int OFFSET_X = 16 + 7 * GRID_SIZE; /** * Offset for graph in Ipe file, over Y-axis. This is the Y-coordinate of * the upper-left corner of the drawing. */ public static final int OFFSET_Y = 832 - 4 * GRID_SIZE; /** Padding, used in drawing squares. */ public static final double PADDING = 0.5; /** Space around text. */ public static final int TEXT_MARGIN = GRID_SIZE / 5; private PrintStream output; private File outFile = null; /** * Create a new object capable of outputting to the default output. */ public OutputIpe() { output = System.out; } /** * Create a new object capable of outputting to the given file. * * @param file * The file to write to. * @throws FileNotFoundException * If given file cannot be found. */ public OutputIpe(File file) throws FileNotFoundException { output = new PrintStream(new FileOutputStream(file)); outFile = file; } /** * Output the given schedule to the file given at construction or standard * output, depending on how this object was constructed. * * @param schedule * The schedule to be outputted. * @param options * Options for output. */ public void outputIpeFile(Schedule schedule, OutputIpeOptions options) { if (outFile != null) { try { output = new PrintStream(new FileOutputStream(outFile)); } catch (FileNotFoundException e) { // Does not occur by construction, see constructor: we check it // there already e.printStackTrace(); } } // Compress schedule, it is easier to have nice output like this schedule.compress(); // Get tasks in the schedule, convert this to a list and // sort the list so that tasks are sorted by name Set<Task> tasksSet = schedule.getTasks(); ArrayList<Task> tasks = new ArrayList<Task>(tasksSet); Collections.sort(tasks, new Comparator<Task>() { @Override public int compare(Task o1, Task o2) { return o2.getName().compareTo(o1.getName()); } }); // Some variable declarations TaskInstance curTaskInstance, prevTaskInstance = null; int i, j; // Ipe header outputHeader(); // Draw tasks double time = 0; while (time < schedule.getLcm()) { curTaskInstance = schedule.getTaskInstanceAt(time); if (curTaskInstance == null) { if (schedule.getNextTaskAt(time) == null) break; time = schedule.getNextTaskAt(time).getStart(); curTaskInstance = schedule.getTaskInstanceAt(time); } j = 0; for (Task tt : tasks) { if (tt.equals(curTaskInstance.getTask())) break; j++; } // deciding the colors based on the options String lineColor; String fillColor; if (options.getBooleanOption("useColors")) { lineColor = IPE_COLORS[j % IPE_COLORS.length]; } else { lineColor = "black"; } if (options.getBooleanOption("fill")) { fillColor = lineColor; } else { fillColor = "white"; } writeSquareFilled( OFFSET_X + GRID_SIZE * curTaskInstance.getStart() + (prevTaskInstance != null && curTaskInstance.getTask().equals( prevTaskInstance.getTask()) ? -PADDING : PADDING), OFFSET_Y + GRID_SIZE * (j - tasks.size()) + PADDING, GRID_SIZE * (curTaskInstance.getEnd() - curTaskInstance .getStart()) - (prevTaskInstance != null && curTaskInstance.getTask().equals( prevTaskInstance.getTask()) ? 0 : 2 * PADDING), GRID_SIZE - 2 * PADDING, lineColor, fillColor); prevTaskInstance = curTaskInstance; time = curTaskInstance.getEnd(); } // Draw axis writeLine(OFFSET_X, OFFSET_Y - GRID_SIZE * tasks.size(), OFFSET_X + GRID_SIZE * schedule.getLcm(), OFFSET_Y - GRID_SIZE * tasks.size(), "black", null); writeLine(OFFSET_X, OFFSET_Y, OFFSET_X, OFFSET_Y - GRID_SIZE * tasks.size(), "black", null); // write X-axis scale int xAxisNumbering = options.getIntegerOption("xAxisNumbering"); if (xAxisNumbering != 0) { // we want to use a numbering // getting pre-/postfix String prefix = options.getStringOption("xAxisPreLabelText"); String postfix = options.getStringOption("xAxisPostLabelText"); // writing the numbers int stepSize = xAxisNumbering < 0 ? 1 : (schedule.getLcm() / (xAxisNumbering - 1)); int maxOption = options.getIntegerOption("scheduleMaxLength"); int until = maxOption == 0 ? schedule.getLcm() : maxOption; for (i = 0; i <= until; i += stepSize) { writeString(prefix + i + postfix, OFFSET_X + GRID_SIZE * i, OFFSET_Y - GRID_SIZE * tasks.size() - TEXT_MARGIN, "center", "top"); } // always draw the last writeString(prefix + until + postfix, OFFSET_X + GRID_SIZE * until, OFFSET_Y - GRID_SIZE * tasks.size() - TEXT_MARGIN, "center", "top"); } // write Y-axis task names - String taskPrefix = options.getStringOption("xAxisPreLabelText"); - String taskPostfix = options.getStringOption("xAxisPostLabelText"); + String taskPrefix = options.getStringOption("yAxisPreLabelText"); + String taskPostfix = options.getStringOption("yAxisPostLabelText"); // looping over the tasks j = 0; for (Task tt : tasks) { String string = taskPrefix + tt.getName() + taskPostfix; writeString(string, OFFSET_X - TEXT_MARGIN, OFFSET_Y + GRID_SIZE * (j - tasks.size()) + GRID_SIZE / 2, "right", "center"); j++; } // Draw deadline miss, if any if (!schedule.isFeasible()) { // First, draw dashed border around last instance of task that // missed its deadline and draw a dashed line where the deadline is. TaskInstance lastTaskInstance = schedule .getMissedTaskLastInstance(); j = 0; for (Task tt : tasks) { if (tt.equals(lastTaskInstance.getTask())) break; j++; } writeSquare( OFFSET_X + GRID_SIZE * lastTaskInstance.getStart(), OFFSET_Y + GRID_SIZE * (j - tasks.size()), GRID_SIZE * (lastTaskInstance.getEnd() - lastTaskInstance .getStart()), GRID_SIZE, "black", "dashed"); writeLine( OFFSET_X + GRID_SIZE * lastTaskInstance.getTask().getAbsoluteDeadline( lastTaskInstance.getStart()), OFFSET_Y - GRID_SIZE * tasks.size(), OFFSET_X + GRID_SIZE * lastTaskInstance.getTask().getAbsoluteDeadline( lastTaskInstance.getStart()), OFFSET_Y + GRID_SIZE, "black", "dashed"); } // show the schedule name // Ipe footer outputFooter(); // Close stream if (output != System.out) output.close(); } private void outputFromFile(String path) { InputStream is = getClass().getResourceAsStream(path); // Read header from file and output it to the stream byte[] buffer = new byte[4096]; // tweaking this number may increase // performance int len; try { while ((len = is.read(buffer)) != -1) { output.write(buffer, 0, len); } output.flush(); output.println(); is.close(); } catch (IOException e) { e.printStackTrace(); } } private void outputFooter() { outputFromFile("/res/ipe_footer.txt"); } private void outputHeader() { outputFromFile("/res/ipe_header.txt"); } /* methods to write "shapes" to the Ipe file */ private final String SQUARE = "<path layer=\"alpha\" stroke=\"%s\" dash=\"%s\"> \n" + "%f %f m \n" + "%f %f l \n" + "%f %f l \n" + "%f %f l \n" + "h \n" + "</path> \n"; private final String SQUARE_FILLED = "<path layer=\"alpha\" stroke=\"%s\" fill=\"%s\"> \n" + "%f %f m \n" + "%f %f l \n" + "%f %f l \n" + "%f %f l \n" + "h \n" + "</path> \n"; @SuppressWarnings("boxing") private void writeSquare(double x, double y, double width, double height, String color, String dashed) { String square = String.format(Locale.US, SQUARE, color, dashed, x, y, x + width, y, x + width, y + height, x, y + height); try { output.write(square.getBytes()); } catch (IOException e) { e.printStackTrace(); } } @SuppressWarnings("boxing") private void writeSquareFilled(double x, double y, double width, double height, String lineColor, String color) { String square = String .format(Locale.US, SQUARE_FILLED, lineColor, color, x, y, x + width, y, x + width, y + height, x, y + height); try { output.write(square.getBytes()); } catch (IOException e) { e.printStackTrace(); } } private final String LINE = "<path stroke=\"%s\"> \n" + "%f %f m \n" + "%f %f l \n" + "</path> \n"; private final String LINE_DASHED = "<path stroke=\"%s\" dash=\"%s\"> \n" + "%f %f m \n" + "%f %f l \n" + "</path> \n"; @SuppressWarnings("boxing") private void writeLine(double x1, double y1, double x2, double y2, String color, String dashed) { String line = ""; if (dashed != null) { line = String.format(Locale.US, LINE_DASHED, color, dashed, x1, y1, x2, y2); } else { line = String.format(Locale.US, LINE, color, x1, y1, x2, y2); } try { output.write(line.getBytes()); } catch (IOException e) { e.printStackTrace(); } } private final String STRING = "<text transformations=\"translations\" pos=\"%f %f\" " + "stroke=\"black\" type=\"label\" depth=\"0\" " + "halign=\"%s\" valign=\"%s\">%s</text> \n"; @SuppressWarnings("boxing") private void writeString(String text, double x, double y, String halign, String valign) { String string = String.format(Locale.US, STRING, x, y, halign, valign, text); try { output.write(string.getBytes()); } catch (IOException e) { e.printStackTrace(); } } }
true
true
public void outputIpeFile(Schedule schedule, OutputIpeOptions options) { if (outFile != null) { try { output = new PrintStream(new FileOutputStream(outFile)); } catch (FileNotFoundException e) { // Does not occur by construction, see constructor: we check it // there already e.printStackTrace(); } } // Compress schedule, it is easier to have nice output like this schedule.compress(); // Get tasks in the schedule, convert this to a list and // sort the list so that tasks are sorted by name Set<Task> tasksSet = schedule.getTasks(); ArrayList<Task> tasks = new ArrayList<Task>(tasksSet); Collections.sort(tasks, new Comparator<Task>() { @Override public int compare(Task o1, Task o2) { return o2.getName().compareTo(o1.getName()); } }); // Some variable declarations TaskInstance curTaskInstance, prevTaskInstance = null; int i, j; // Ipe header outputHeader(); // Draw tasks double time = 0; while (time < schedule.getLcm()) { curTaskInstance = schedule.getTaskInstanceAt(time); if (curTaskInstance == null) { if (schedule.getNextTaskAt(time) == null) break; time = schedule.getNextTaskAt(time).getStart(); curTaskInstance = schedule.getTaskInstanceAt(time); } j = 0; for (Task tt : tasks) { if (tt.equals(curTaskInstance.getTask())) break; j++; } // deciding the colors based on the options String lineColor; String fillColor; if (options.getBooleanOption("useColors")) { lineColor = IPE_COLORS[j % IPE_COLORS.length]; } else { lineColor = "black"; } if (options.getBooleanOption("fill")) { fillColor = lineColor; } else { fillColor = "white"; } writeSquareFilled( OFFSET_X + GRID_SIZE * curTaskInstance.getStart() + (prevTaskInstance != null && curTaskInstance.getTask().equals( prevTaskInstance.getTask()) ? -PADDING : PADDING), OFFSET_Y + GRID_SIZE * (j - tasks.size()) + PADDING, GRID_SIZE * (curTaskInstance.getEnd() - curTaskInstance .getStart()) - (prevTaskInstance != null && curTaskInstance.getTask().equals( prevTaskInstance.getTask()) ? 0 : 2 * PADDING), GRID_SIZE - 2 * PADDING, lineColor, fillColor); prevTaskInstance = curTaskInstance; time = curTaskInstance.getEnd(); } // Draw axis writeLine(OFFSET_X, OFFSET_Y - GRID_SIZE * tasks.size(), OFFSET_X + GRID_SIZE * schedule.getLcm(), OFFSET_Y - GRID_SIZE * tasks.size(), "black", null); writeLine(OFFSET_X, OFFSET_Y, OFFSET_X, OFFSET_Y - GRID_SIZE * tasks.size(), "black", null); // write X-axis scale int xAxisNumbering = options.getIntegerOption("xAxisNumbering"); if (xAxisNumbering != 0) { // we want to use a numbering // getting pre-/postfix String prefix = options.getStringOption("xAxisPreLabelText"); String postfix = options.getStringOption("xAxisPostLabelText"); // writing the numbers int stepSize = xAxisNumbering < 0 ? 1 : (schedule.getLcm() / (xAxisNumbering - 1)); int maxOption = options.getIntegerOption("scheduleMaxLength"); int until = maxOption == 0 ? schedule.getLcm() : maxOption; for (i = 0; i <= until; i += stepSize) { writeString(prefix + i + postfix, OFFSET_X + GRID_SIZE * i, OFFSET_Y - GRID_SIZE * tasks.size() - TEXT_MARGIN, "center", "top"); } // always draw the last writeString(prefix + until + postfix, OFFSET_X + GRID_SIZE * until, OFFSET_Y - GRID_SIZE * tasks.size() - TEXT_MARGIN, "center", "top"); } // write Y-axis task names String taskPrefix = options.getStringOption("xAxisPreLabelText"); String taskPostfix = options.getStringOption("xAxisPostLabelText"); // looping over the tasks j = 0; for (Task tt : tasks) { String string = taskPrefix + tt.getName() + taskPostfix; writeString(string, OFFSET_X - TEXT_MARGIN, OFFSET_Y + GRID_SIZE * (j - tasks.size()) + GRID_SIZE / 2, "right", "center"); j++; } // Draw deadline miss, if any if (!schedule.isFeasible()) { // First, draw dashed border around last instance of task that // missed its deadline and draw a dashed line where the deadline is. TaskInstance lastTaskInstance = schedule .getMissedTaskLastInstance(); j = 0; for (Task tt : tasks) { if (tt.equals(lastTaskInstance.getTask())) break; j++; } writeSquare( OFFSET_X + GRID_SIZE * lastTaskInstance.getStart(), OFFSET_Y + GRID_SIZE * (j - tasks.size()), GRID_SIZE * (lastTaskInstance.getEnd() - lastTaskInstance .getStart()), GRID_SIZE, "black", "dashed"); writeLine( OFFSET_X + GRID_SIZE * lastTaskInstance.getTask().getAbsoluteDeadline( lastTaskInstance.getStart()), OFFSET_Y - GRID_SIZE * tasks.size(), OFFSET_X + GRID_SIZE * lastTaskInstance.getTask().getAbsoluteDeadline( lastTaskInstance.getStart()), OFFSET_Y + GRID_SIZE, "black", "dashed"); } // show the schedule name // Ipe footer outputFooter(); // Close stream if (output != System.out) output.close(); }
public void outputIpeFile(Schedule schedule, OutputIpeOptions options) { if (outFile != null) { try { output = new PrintStream(new FileOutputStream(outFile)); } catch (FileNotFoundException e) { // Does not occur by construction, see constructor: we check it // there already e.printStackTrace(); } } // Compress schedule, it is easier to have nice output like this schedule.compress(); // Get tasks in the schedule, convert this to a list and // sort the list so that tasks are sorted by name Set<Task> tasksSet = schedule.getTasks(); ArrayList<Task> tasks = new ArrayList<Task>(tasksSet); Collections.sort(tasks, new Comparator<Task>() { @Override public int compare(Task o1, Task o2) { return o2.getName().compareTo(o1.getName()); } }); // Some variable declarations TaskInstance curTaskInstance, prevTaskInstance = null; int i, j; // Ipe header outputHeader(); // Draw tasks double time = 0; while (time < schedule.getLcm()) { curTaskInstance = schedule.getTaskInstanceAt(time); if (curTaskInstance == null) { if (schedule.getNextTaskAt(time) == null) break; time = schedule.getNextTaskAt(time).getStart(); curTaskInstance = schedule.getTaskInstanceAt(time); } j = 0; for (Task tt : tasks) { if (tt.equals(curTaskInstance.getTask())) break; j++; } // deciding the colors based on the options String lineColor; String fillColor; if (options.getBooleanOption("useColors")) { lineColor = IPE_COLORS[j % IPE_COLORS.length]; } else { lineColor = "black"; } if (options.getBooleanOption("fill")) { fillColor = lineColor; } else { fillColor = "white"; } writeSquareFilled( OFFSET_X + GRID_SIZE * curTaskInstance.getStart() + (prevTaskInstance != null && curTaskInstance.getTask().equals( prevTaskInstance.getTask()) ? -PADDING : PADDING), OFFSET_Y + GRID_SIZE * (j - tasks.size()) + PADDING, GRID_SIZE * (curTaskInstance.getEnd() - curTaskInstance .getStart()) - (prevTaskInstance != null && curTaskInstance.getTask().equals( prevTaskInstance.getTask()) ? 0 : 2 * PADDING), GRID_SIZE - 2 * PADDING, lineColor, fillColor); prevTaskInstance = curTaskInstance; time = curTaskInstance.getEnd(); } // Draw axis writeLine(OFFSET_X, OFFSET_Y - GRID_SIZE * tasks.size(), OFFSET_X + GRID_SIZE * schedule.getLcm(), OFFSET_Y - GRID_SIZE * tasks.size(), "black", null); writeLine(OFFSET_X, OFFSET_Y, OFFSET_X, OFFSET_Y - GRID_SIZE * tasks.size(), "black", null); // write X-axis scale int xAxisNumbering = options.getIntegerOption("xAxisNumbering"); if (xAxisNumbering != 0) { // we want to use a numbering // getting pre-/postfix String prefix = options.getStringOption("xAxisPreLabelText"); String postfix = options.getStringOption("xAxisPostLabelText"); // writing the numbers int stepSize = xAxisNumbering < 0 ? 1 : (schedule.getLcm() / (xAxisNumbering - 1)); int maxOption = options.getIntegerOption("scheduleMaxLength"); int until = maxOption == 0 ? schedule.getLcm() : maxOption; for (i = 0; i <= until; i += stepSize) { writeString(prefix + i + postfix, OFFSET_X + GRID_SIZE * i, OFFSET_Y - GRID_SIZE * tasks.size() - TEXT_MARGIN, "center", "top"); } // always draw the last writeString(prefix + until + postfix, OFFSET_X + GRID_SIZE * until, OFFSET_Y - GRID_SIZE * tasks.size() - TEXT_MARGIN, "center", "top"); } // write Y-axis task names String taskPrefix = options.getStringOption("yAxisPreLabelText"); String taskPostfix = options.getStringOption("yAxisPostLabelText"); // looping over the tasks j = 0; for (Task tt : tasks) { String string = taskPrefix + tt.getName() + taskPostfix; writeString(string, OFFSET_X - TEXT_MARGIN, OFFSET_Y + GRID_SIZE * (j - tasks.size()) + GRID_SIZE / 2, "right", "center"); j++; } // Draw deadline miss, if any if (!schedule.isFeasible()) { // First, draw dashed border around last instance of task that // missed its deadline and draw a dashed line where the deadline is. TaskInstance lastTaskInstance = schedule .getMissedTaskLastInstance(); j = 0; for (Task tt : tasks) { if (tt.equals(lastTaskInstance.getTask())) break; j++; } writeSquare( OFFSET_X + GRID_SIZE * lastTaskInstance.getStart(), OFFSET_Y + GRID_SIZE * (j - tasks.size()), GRID_SIZE * (lastTaskInstance.getEnd() - lastTaskInstance .getStart()), GRID_SIZE, "black", "dashed"); writeLine( OFFSET_X + GRID_SIZE * lastTaskInstance.getTask().getAbsoluteDeadline( lastTaskInstance.getStart()), OFFSET_Y - GRID_SIZE * tasks.size(), OFFSET_X + GRID_SIZE * lastTaskInstance.getTask().getAbsoluteDeadline( lastTaskInstance.getStart()), OFFSET_Y + GRID_SIZE, "black", "dashed"); } // show the schedule name // Ipe footer outputFooter(); // Close stream if (output != System.out) output.close(); }
diff --git a/src/org/meta_environment/rascal/interpreter/Typeifier.java b/src/org/meta_environment/rascal/interpreter/Typeifier.java index 0e41d9a72e..5abd2ec3e3 100644 --- a/src/org/meta_environment/rascal/interpreter/Typeifier.java +++ b/src/org/meta_environment/rascal/interpreter/Typeifier.java @@ -1,210 +1,210 @@ package org.meta_environment.rascal.interpreter; import java.util.LinkedList; import java.util.List; import org.eclipse.imp.pdb.facts.IConstructor; import org.eclipse.imp.pdb.facts.IList; import org.eclipse.imp.pdb.facts.IString; import org.eclipse.imp.pdb.facts.ITuple; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.type.ITypeVisitor; import org.eclipse.imp.pdb.facts.type.Type; import org.eclipse.imp.pdb.facts.type.TypeFactory; import org.eclipse.imp.pdb.facts.type.TypeStore; import org.meta_environment.rascal.interpreter.asserts.ImplementationError; import org.meta_environment.rascal.interpreter.types.ReifiedType; /** * This class helps transforming reified types back to types and to extract type * declarations from reified types. * * See also {@link TypeReifier}. */ public class Typeifier { private Typeifier(){ super(); } /** * Retrieve the type that is reified by the given value * * @param typeValue a reified type value produced by {@link TypeReifier}. * @return the plain Type that typeValue represented */ public static Type toType(IConstructor typeValue) { Type anonymous = typeValue.getType(); if (anonymous instanceof ReifiedType) { ReifiedType reified = (ReifiedType) anonymous; return reified.getTypeParameters().getFieldType(0); } throw new UnsupportedOperationException("Not a reified type: " + typeValue.getType()); } /** * Locate all declared types in a reified type value, such as abstract data types * constructors and aliases and stores them in the given TypeStore. * * @param typeValue a reified type which is produced by {@link TypeReifier} * @param store a TypeStore to collect declarations in * @return the plain Type that typeValue represented */ public static Type declare(IConstructor typeValue, final TypeStore store) { final List<IConstructor> todo = new LinkedList<IConstructor>(); todo.add(typeValue); while (!todo.isEmpty()) { final IConstructor next = todo.get(0); todo.remove(0); Type type = toType(next); // We dispatch on the real type which is isomorphic to the typeValue. type.accept(new ITypeVisitor<Type>() { private final TypeFactory tf = TypeFactory.getInstance(); public Type visitAbstractData(Type type) { store.declareAbstractDataType(type); declareParameters(next); declareConstructors(type, next); return type; } public Type visitAlias(Type type) { IConstructor aliased = getAliased(next); todo.add(aliased); declareParameters(aliased); return type; } public Type visitBool(Type boolType) { return boolType; } public Type visitConstructor(Type type) { throw new ImplementationError("should not have to typeify this: " + type); } public Type visitExternal(Type externalType) { throw new ImplementationError("should not have to typeify this: " + externalType); } public Type visitInteger(Type type) { return type; } public Type visitList(Type type) { todo.add(getElement(next)); return type; } public Type visitMap(Type type) { todo.add(getKey(next)); todo.add(getValue(next)); return type; } public Type visitNode(Type type) { return type; } public Type visitParameter(Type parameterType) { throw new ImplementationError("reified parameter types are not supported"); } public Type visitReal(Type type) { return type; } public Type visitRelationType(Type type) { for (IValue child : next) { todo.add((IConstructor) child); } return type; } public Type visitSet(Type type) { todo.add(getElement(next)); return type; } public Type visitSourceLocation(Type type) { return type; } public Type visitString(Type type) { return type; } public Type visitTuple(Type type) { for (IValue child : (IList) next.get(0)) { - todo.add((IConstructor) ((ITuple) child).get(0)); + todo.add((IConstructor) child); } return type; } public Type visitValue(Type type) { return type; } public Type visitVoid(Type type) { return type; } private void declareParameters(IConstructor next) { for (IValue p : ((IList) next.get("parameters"))) { todo.add((IConstructor) p); } } private void declareConstructors(Type adt, IConstructor next) { IList constructors = getConstructors(next); for (IValue c : constructors) { IConstructor cons = (IConstructor) c; IList fields = (IList) cons.get(1); String name = getName(cons); Object[] args = new Object[fields.length() * 2]; int i = 0; for (IValue field : fields) { ITuple tuple = (ITuple) field; args[i++] = toType((IConstructor) tuple.get(0)); args[i++] = ((IString) tuple.get(1)).getValue(); } tf.constructor(store, adt, name, args); } } private IConstructor getElement(IConstructor next) { return (IConstructor) next.get("element"); } private String getName(final IConstructor next) { return ((IString) next.get("name")).getValue(); } private IConstructor getValue(IConstructor next) { return (IConstructor) next.get("key"); } private IConstructor getAliased(IConstructor next) { return (IConstructor) next.get("aliased"); } private IConstructor getKey(IConstructor next) { return (IConstructor) next.get("value"); } private IList getConstructors(IConstructor next) { return (IList) next.get("constructors"); } }); } return toType(typeValue); } }
true
true
public static Type declare(IConstructor typeValue, final TypeStore store) { final List<IConstructor> todo = new LinkedList<IConstructor>(); todo.add(typeValue); while (!todo.isEmpty()) { final IConstructor next = todo.get(0); todo.remove(0); Type type = toType(next); // We dispatch on the real type which is isomorphic to the typeValue. type.accept(new ITypeVisitor<Type>() { private final TypeFactory tf = TypeFactory.getInstance(); public Type visitAbstractData(Type type) { store.declareAbstractDataType(type); declareParameters(next); declareConstructors(type, next); return type; } public Type visitAlias(Type type) { IConstructor aliased = getAliased(next); todo.add(aliased); declareParameters(aliased); return type; } public Type visitBool(Type boolType) { return boolType; } public Type visitConstructor(Type type) { throw new ImplementationError("should not have to typeify this: " + type); } public Type visitExternal(Type externalType) { throw new ImplementationError("should not have to typeify this: " + externalType); } public Type visitInteger(Type type) { return type; } public Type visitList(Type type) { todo.add(getElement(next)); return type; } public Type visitMap(Type type) { todo.add(getKey(next)); todo.add(getValue(next)); return type; } public Type visitNode(Type type) { return type; } public Type visitParameter(Type parameterType) { throw new ImplementationError("reified parameter types are not supported"); } public Type visitReal(Type type) { return type; } public Type visitRelationType(Type type) { for (IValue child : next) { todo.add((IConstructor) child); } return type; } public Type visitSet(Type type) { todo.add(getElement(next)); return type; } public Type visitSourceLocation(Type type) { return type; } public Type visitString(Type type) { return type; } public Type visitTuple(Type type) { for (IValue child : (IList) next.get(0)) { todo.add((IConstructor) ((ITuple) child).get(0)); } return type; } public Type visitValue(Type type) { return type; } public Type visitVoid(Type type) { return type; } private void declareParameters(IConstructor next) { for (IValue p : ((IList) next.get("parameters"))) { todo.add((IConstructor) p); } } private void declareConstructors(Type adt, IConstructor next) { IList constructors = getConstructors(next); for (IValue c : constructors) { IConstructor cons = (IConstructor) c; IList fields = (IList) cons.get(1); String name = getName(cons); Object[] args = new Object[fields.length() * 2]; int i = 0; for (IValue field : fields) { ITuple tuple = (ITuple) field; args[i++] = toType((IConstructor) tuple.get(0)); args[i++] = ((IString) tuple.get(1)).getValue(); } tf.constructor(store, adt, name, args); } } private IConstructor getElement(IConstructor next) { return (IConstructor) next.get("element"); } private String getName(final IConstructor next) { return ((IString) next.get("name")).getValue(); } private IConstructor getValue(IConstructor next) { return (IConstructor) next.get("key"); } private IConstructor getAliased(IConstructor next) { return (IConstructor) next.get("aliased"); } private IConstructor getKey(IConstructor next) { return (IConstructor) next.get("value"); } private IList getConstructors(IConstructor next) { return (IList) next.get("constructors"); } }); } return toType(typeValue); }
public static Type declare(IConstructor typeValue, final TypeStore store) { final List<IConstructor> todo = new LinkedList<IConstructor>(); todo.add(typeValue); while (!todo.isEmpty()) { final IConstructor next = todo.get(0); todo.remove(0); Type type = toType(next); // We dispatch on the real type which is isomorphic to the typeValue. type.accept(new ITypeVisitor<Type>() { private final TypeFactory tf = TypeFactory.getInstance(); public Type visitAbstractData(Type type) { store.declareAbstractDataType(type); declareParameters(next); declareConstructors(type, next); return type; } public Type visitAlias(Type type) { IConstructor aliased = getAliased(next); todo.add(aliased); declareParameters(aliased); return type; } public Type visitBool(Type boolType) { return boolType; } public Type visitConstructor(Type type) { throw new ImplementationError("should not have to typeify this: " + type); } public Type visitExternal(Type externalType) { throw new ImplementationError("should not have to typeify this: " + externalType); } public Type visitInteger(Type type) { return type; } public Type visitList(Type type) { todo.add(getElement(next)); return type; } public Type visitMap(Type type) { todo.add(getKey(next)); todo.add(getValue(next)); return type; } public Type visitNode(Type type) { return type; } public Type visitParameter(Type parameterType) { throw new ImplementationError("reified parameter types are not supported"); } public Type visitReal(Type type) { return type; } public Type visitRelationType(Type type) { for (IValue child : next) { todo.add((IConstructor) child); } return type; } public Type visitSet(Type type) { todo.add(getElement(next)); return type; } public Type visitSourceLocation(Type type) { return type; } public Type visitString(Type type) { return type; } public Type visitTuple(Type type) { for (IValue child : (IList) next.get(0)) { todo.add((IConstructor) child); } return type; } public Type visitValue(Type type) { return type; } public Type visitVoid(Type type) { return type; } private void declareParameters(IConstructor next) { for (IValue p : ((IList) next.get("parameters"))) { todo.add((IConstructor) p); } } private void declareConstructors(Type adt, IConstructor next) { IList constructors = getConstructors(next); for (IValue c : constructors) { IConstructor cons = (IConstructor) c; IList fields = (IList) cons.get(1); String name = getName(cons); Object[] args = new Object[fields.length() * 2]; int i = 0; for (IValue field : fields) { ITuple tuple = (ITuple) field; args[i++] = toType((IConstructor) tuple.get(0)); args[i++] = ((IString) tuple.get(1)).getValue(); } tf.constructor(store, adt, name, args); } } private IConstructor getElement(IConstructor next) { return (IConstructor) next.get("element"); } private String getName(final IConstructor next) { return ((IString) next.get("name")).getValue(); } private IConstructor getValue(IConstructor next) { return (IConstructor) next.get("key"); } private IConstructor getAliased(IConstructor next) { return (IConstructor) next.get("aliased"); } private IConstructor getKey(IConstructor next) { return (IConstructor) next.get("value"); } private IList getConstructors(IConstructor next) { return (IList) next.get("constructors"); } }); } return toType(typeValue); }
diff --git a/sigfood-android/src/de/sigfood/SigfoodActivity.java b/sigfood-android/src/de/sigfood/SigfoodActivity.java index 70f898c..2c6aec2 100644 --- a/sigfood-android/src/de/sigfood/SigfoodActivity.java +++ b/sigfood-android/src/de/sigfood/SigfoodActivity.java @@ -1,467 +1,467 @@ package de.sigfood; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Random; import org.apache.http.*; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.*; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RatingBar; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; public class SigfoodActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LinearLayout tv = (LinearLayout)this.findViewById(R.id.scroller); tv.removeAllViews(); TextView loadingtext = new TextView(getBaseContext(), null, android.R.attr.textAppearanceMedium); loadingtext.setText("Starting up"); tv.addView(loadingtext); Button prev_date = (Button)this.findViewById(R.id.prev_date); Button next_date = (Button)this.findViewById(R.id.next_date); next_date.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if (sigfood != null) { if (sigfood.naechstertag != null) { fillspeiseplan(sigfood.naechstertag); } } } }); prev_date.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if (sigfood != null) { if (sigfood.vorherigertag != null) { fillspeiseplan(sigfood.vorherigertag); } } } }); fillspeiseplan(null); } SigfoodApi sigfood; public void fillspeiseplan(Date d) { LinearLayout parent = (LinearLayout)this.findViewById(R.id.scroller); TextView datum = (TextView)this.findViewById(R.id.datum); /* First clear and show loading text */ datum.setText("Loading..."); parent.removeAllViews(); /* This actually downloads the plan, so can be rather costly */ sigfood = new SigfoodApi(d); /* Now start to fill plan and download pictures */ final Date sfspd = sigfood.speiseplandatum; datum.setText(String.format("%tA, %td.%tm.%tY", sfspd, sfspd, sfspd, sfspd)); Button next_date = (Button)this.findViewById(R.id.next_date); next_date.setEnabled(sigfood.naechstertag != null); Button prev_date = (Button)this.findViewById(R.id.prev_date); prev_date.setEnabled(sigfood.vorherigertag != null); for (final MensaEssen e : sigfood.essen) { LinearLayout essen = (LinearLayout)LayoutInflater.from(getBaseContext()).inflate(R.layout.mensaessen, null); TextView t2 = (TextView)essen.findViewById(R.id.hauptgerichtBezeichnung); t2.setText(Html.fromHtml(e.hauptgericht.bezeichnung) + "(" + e.hauptgericht.bewertung.schnitt + "/" + e.hauptgericht.bewertung.anzahl + "/" + e.hauptgericht.bewertung.stddev + ")"); TextView ueberschrift = (TextView)essen.findViewById(R.id.ueberschrift); ueberschrift.setText("Linie: " + e.linie); final Button ratingbutton = (Button)essen.findViewById(R.id.button1); TextView kommentare1 = (TextView)essen.findViewById(R.id.kommentare1); String tmp = ""; for (String s : e.hauptgericht.kommentare) { - tmp += "\"" + s + "\"" + "\n"; + tmp += "\"" + Html.fromHtml(s) + "\"" + "\n"; } kommentare1.setText(tmp); final RatingBar bar1 = (RatingBar)essen.findViewById(R.id.ratingBar1); bar1.setMax(5); bar1.setProgress((int) (e.hauptgericht.bewertung.schnitt + 0.5f)); ratingbutton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if(bar1.isIndicator()) { ratingbutton.setText("Bewertung jetzt abgeben"); bar1.setIsIndicator(false); } else { bar1.setIsIndicator(true); ratingbutton.setEnabled(false); if (bewerten(e.hauptgericht, (int)bar1.getRating(), sfspd)) ratingbutton.setText("Bewertung abgegeben"); } } }); final Button kommentieren = (Button)essen.findViewById(R.id.kommentieren); final LinearLayout kommentar = (LinearLayout)essen.findViewById(R.id.kommentar); final EditText kommentar_name = (EditText)essen.findViewById(R.id.kommentar_name); final EditText kommentar_text = (EditText)essen.findViewById(R.id.kommentar_text); kommentieren.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if(kommentar.getVisibility() == View.GONE) { kommentar.setVisibility(View.VISIBLE); kommentieren.setText("Kommentar abschicken"); } else { kommentar.setVisibility(View.GONE); String name = kommentar_name.getText().toString(); String text = kommentar_text.getText().toString(); if(name.length() > 0 && text.length() > 0) { if(kommentieren(e.hauptgericht, sfspd, name, text)) { kommentieren.setText("Kommentar abgegeben"); kommentieren.setEnabled(false); return; } } kommentieren.setText("Kommentieren fehlgeschlagen"); } } }); ImageButton btn = (ImageButton)essen.findViewById(R.id.imageButton1); for (final Hauptgericht beilage : e.beilagen) { TextView beilage_bezeichnung = new TextView(getBaseContext(), null, android.R.attr.textAppearanceMedium); beilage_bezeichnung.setText(Html.fromHtml(beilage.bezeichnung) + "(" + beilage.bewertung.schnitt + "/" + beilage.bewertung.anzahl + "/" + e.hauptgericht.bewertung.stddev + ")"); essen.addView(beilage_bezeichnung); final RatingBar bar2 = new RatingBar(this, null,android.R.attr.ratingBarStyle); bar2.setIsIndicator(true); bar2.setNumStars(5); bar2.setMax(5); bar2.setStepSize(1); bar2.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)); bar2.setRating((int) (beilage.bewertung.schnitt + 0.5f)); essen.addView(bar2); final Button ratingbutton2 = new Button(this, null,android.R.attr.buttonStyleSmall); ratingbutton2.setText("Beilage bewerten"); ratingbutton2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if(bar2.isIndicator()) { ratingbutton2.setText("Bewertung jetzt abgeben"); bar2.setIsIndicator(false); } else { bar2.setIsIndicator(true); ratingbutton2.setEnabled(false); if (bewerten(beilage, (int)bar2.getRating(), sfspd)) ratingbutton.setText("Bewertung abgegeben"); } } }); essen.addView(ratingbutton2); TextView kommentare2 = new TextView(getBaseContext(), null, android.R.attr.textAppearanceSmall); String tmp2 = ""; for(String s : beilage.kommentare) { - tmp2 += "\"" + s + "\"" + "\n"; + tmp2 += "\"" + Html.fromHtml(s) + "\"" + "\n"; } kommentare2.setText(tmp2); essen.addView(kommentare2); } btn.setTag(e); btn.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { takePhoto(v); } }); if (e.hauptgericht.bilder.size() > 0) { Random rng = new Random(); int bild_id = e.hauptgericht.bilder.get(rng.nextInt(e.hauptgericht.bilder.size())); URL myFileUrl =null; try { myFileUrl= new URL("http://www.sigfood.de/?do=getimage&bildid=" + bild_id + "&width=320"); } catch (MalformedURLException e1) { Bitmap bmImg = BitmapFactory.decodeResource(getResources(), R.drawable.picdownloadfailed); btn.setImageBitmap(bmImg); } try { HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection(); conn.setDoInput(true); conn.connect(); //int length = conn.getContentLength(); //int[] bitmapData =new int[length]; //byte[] bitmapData2 =new byte[length]; InputStream is = conn.getInputStream(); Bitmap bmImg = BitmapFactory.decodeStream(is); btn.setImageBitmap(bmImg); } catch (IOException e1) { Bitmap bmImg = BitmapFactory.decodeResource(getResources(), R.drawable.picdownloadfailed); btn.setImageBitmap(bmImg); } } else { Bitmap bmImg = BitmapFactory.decodeResource(getResources(), R.drawable.nophotoavailable003); btn.setImageBitmap(bmImg); } parent.addView(essen); } } boolean kommentieren(Hauptgericht e, Date tag, String name, String kommentar) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.sigfood.de/"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4); nameValuePairs.add(new BasicNameValuePair("do", "2")); nameValuePairs.add(new BasicNameValuePair("datum", String.format("%tY-%tm-%td", tag, tag, tag))); nameValuePairs.add(new BasicNameValuePair("gerid", Integer.toString(e.id))); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine() == null) { return false; } else { if (response.getStatusLine().getStatusCode() != 200) { return false; } } } catch (ClientProtocolException e1) { return false; } catch (IOException e1) { return false; } return true; } boolean bewerten(Hauptgericht e, int stars, Date tag) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.sigfood.de/"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4); nameValuePairs.add(new BasicNameValuePair("do", "1")); nameValuePairs.add(new BasicNameValuePair("datum", String.format("%tY-%tm-%td", tag, tag, tag))); nameValuePairs.add(new BasicNameValuePair("gerid", Integer.toString(e.id))); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine() == null) { return false; } else { if (response.getStatusLine().getStatusCode() != 200) { return false; } } } catch (ClientProtocolException e1) { return false; } catch (IOException e1) { return false; } return true; } private Uri imageUri; final int TAKE_PICTURE = 19238; final int PICK_FROM_FILE = 19239; ImageButton phototarget; public void takePhoto(View v) { ImageButton btn = (ImageButton)v; phototarget = btn; final String[] items = new String[] { "Select from file", "Take picture"}; ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item, items); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select Image"); builder.setAdapter( adapter, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int item ) { if (item == 0) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE); } else { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); File photo = new File(Environment.getExternalStorageDirectory(), "sigfood.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photo)); imageUri = Uri.fromFile(photo); startActivityForResult(intent, TAKE_PICTURE); dialog.cancel(); } } } ); final AlertDialog dialog = builder.create(); dialog.show(); } void uploadPic(MensaEssen e, Date d, String filepath) { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.sigfood.de/"); try { MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("do", new StringBody("4")); multipartEntity.addPart("beilagenid", new StringBody("-1")); multipartEntity.addPart("datum", new StringBody(String.format("%tY-%tm-%td", d, d, d))); multipartEntity.addPart("gerid", new StringBody(Integer.toString(e.hauptgericht.id))); File f = new File(filepath); multipartEntity.addPart("newimg", new FileBody(f)); httppost.setEntity(multipartEntity); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine() == null) { throw new RuntimeException("nostatusline"); } else { if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("badstatuscode"); } } } catch (ClientProtocolException e1) { // TODO Auto-generated catch block throw new RuntimeException(e1); } catch (IOException e1) { // TODO Auto-generated catch block throw new RuntimeException(e1); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { Uri selectedImage = null; switch (requestCode) { case TAKE_PICTURE: selectedImage = imageUri; break; case PICK_FROM_FILE: selectedImage = data.getData(); break; } if (selectedImage != null) { getContentResolver().notifyChange(selectedImage, null); ImageView imageView = phototarget; String path = ""; try { path = getRealPathFromURI(selectedImage); /* Try to resolve content:// crap URLs */ if (path == null) { /* Oups, that failed, so... */ path = selectedImage.getPath(); /* just take the path part of URL */ } Bitmap bitmap = BitmapFactory.decodeFile(path); imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 320, 200, false)); uploadPic((MensaEssen)phototarget.getTag(), ((MensaEssen)phototarget.getTag()).datumskopie, path); Toast.makeText(this, "Upload done" ,Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(this, "Failed to load or upload" + path, Toast.LENGTH_SHORT).show(); Log.e("Camera", e.toString()); } } } } /* I seriously haven't got the slightest clue what this does, it's copied from * some howto. The more interesting question is why I even need this crap, * and why there are no more sensible functions in the API, like * JUSTGIVEMETHEFUCKINGPATHOFTHATCONTENTCRAP() */ public String getRealPathFromURI(Uri contentUri) { String[] proj = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(contentUri, proj, null, null, null); if (cursor == null) { return null; } int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } }
false
true
public void fillspeiseplan(Date d) { LinearLayout parent = (LinearLayout)this.findViewById(R.id.scroller); TextView datum = (TextView)this.findViewById(R.id.datum); /* First clear and show loading text */ datum.setText("Loading..."); parent.removeAllViews(); /* This actually downloads the plan, so can be rather costly */ sigfood = new SigfoodApi(d); /* Now start to fill plan and download pictures */ final Date sfspd = sigfood.speiseplandatum; datum.setText(String.format("%tA, %td.%tm.%tY", sfspd, sfspd, sfspd, sfspd)); Button next_date = (Button)this.findViewById(R.id.next_date); next_date.setEnabled(sigfood.naechstertag != null); Button prev_date = (Button)this.findViewById(R.id.prev_date); prev_date.setEnabled(sigfood.vorherigertag != null); for (final MensaEssen e : sigfood.essen) { LinearLayout essen = (LinearLayout)LayoutInflater.from(getBaseContext()).inflate(R.layout.mensaessen, null); TextView t2 = (TextView)essen.findViewById(R.id.hauptgerichtBezeichnung); t2.setText(Html.fromHtml(e.hauptgericht.bezeichnung) + "(" + e.hauptgericht.bewertung.schnitt + "/" + e.hauptgericht.bewertung.anzahl + "/" + e.hauptgericht.bewertung.stddev + ")"); TextView ueberschrift = (TextView)essen.findViewById(R.id.ueberschrift); ueberschrift.setText("Linie: " + e.linie); final Button ratingbutton = (Button)essen.findViewById(R.id.button1); TextView kommentare1 = (TextView)essen.findViewById(R.id.kommentare1); String tmp = ""; for (String s : e.hauptgericht.kommentare) { tmp += "\"" + s + "\"" + "\n"; } kommentare1.setText(tmp); final RatingBar bar1 = (RatingBar)essen.findViewById(R.id.ratingBar1); bar1.setMax(5); bar1.setProgress((int) (e.hauptgericht.bewertung.schnitt + 0.5f)); ratingbutton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if(bar1.isIndicator()) { ratingbutton.setText("Bewertung jetzt abgeben"); bar1.setIsIndicator(false); } else { bar1.setIsIndicator(true); ratingbutton.setEnabled(false); if (bewerten(e.hauptgericht, (int)bar1.getRating(), sfspd)) ratingbutton.setText("Bewertung abgegeben"); } } }); final Button kommentieren = (Button)essen.findViewById(R.id.kommentieren); final LinearLayout kommentar = (LinearLayout)essen.findViewById(R.id.kommentar); final EditText kommentar_name = (EditText)essen.findViewById(R.id.kommentar_name); final EditText kommentar_text = (EditText)essen.findViewById(R.id.kommentar_text); kommentieren.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if(kommentar.getVisibility() == View.GONE) { kommentar.setVisibility(View.VISIBLE); kommentieren.setText("Kommentar abschicken"); } else { kommentar.setVisibility(View.GONE); String name = kommentar_name.getText().toString(); String text = kommentar_text.getText().toString(); if(name.length() > 0 && text.length() > 0) { if(kommentieren(e.hauptgericht, sfspd, name, text)) { kommentieren.setText("Kommentar abgegeben"); kommentieren.setEnabled(false); return; } } kommentieren.setText("Kommentieren fehlgeschlagen"); } } }); ImageButton btn = (ImageButton)essen.findViewById(R.id.imageButton1); for (final Hauptgericht beilage : e.beilagen) { TextView beilage_bezeichnung = new TextView(getBaseContext(), null, android.R.attr.textAppearanceMedium); beilage_bezeichnung.setText(Html.fromHtml(beilage.bezeichnung) + "(" + beilage.bewertung.schnitt + "/" + beilage.bewertung.anzahl + "/" + e.hauptgericht.bewertung.stddev + ")"); essen.addView(beilage_bezeichnung); final RatingBar bar2 = new RatingBar(this, null,android.R.attr.ratingBarStyle); bar2.setIsIndicator(true); bar2.setNumStars(5); bar2.setMax(5); bar2.setStepSize(1); bar2.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)); bar2.setRating((int) (beilage.bewertung.schnitt + 0.5f)); essen.addView(bar2); final Button ratingbutton2 = new Button(this, null,android.R.attr.buttonStyleSmall); ratingbutton2.setText("Beilage bewerten"); ratingbutton2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if(bar2.isIndicator()) { ratingbutton2.setText("Bewertung jetzt abgeben"); bar2.setIsIndicator(false); } else { bar2.setIsIndicator(true); ratingbutton2.setEnabled(false); if (bewerten(beilage, (int)bar2.getRating(), sfspd)) ratingbutton.setText("Bewertung abgegeben"); } } }); essen.addView(ratingbutton2); TextView kommentare2 = new TextView(getBaseContext(), null, android.R.attr.textAppearanceSmall); String tmp2 = ""; for(String s : beilage.kommentare) { tmp2 += "\"" + s + "\"" + "\n"; } kommentare2.setText(tmp2); essen.addView(kommentare2); } btn.setTag(e); btn.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { takePhoto(v); } }); if (e.hauptgericht.bilder.size() > 0) { Random rng = new Random(); int bild_id = e.hauptgericht.bilder.get(rng.nextInt(e.hauptgericht.bilder.size())); URL myFileUrl =null; try { myFileUrl= new URL("http://www.sigfood.de/?do=getimage&bildid=" + bild_id + "&width=320"); } catch (MalformedURLException e1) { Bitmap bmImg = BitmapFactory.decodeResource(getResources(), R.drawable.picdownloadfailed); btn.setImageBitmap(bmImg); } try { HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection(); conn.setDoInput(true); conn.connect(); //int length = conn.getContentLength(); //int[] bitmapData =new int[length]; //byte[] bitmapData2 =new byte[length]; InputStream is = conn.getInputStream(); Bitmap bmImg = BitmapFactory.decodeStream(is); btn.setImageBitmap(bmImg); } catch (IOException e1) { Bitmap bmImg = BitmapFactory.decodeResource(getResources(), R.drawable.picdownloadfailed); btn.setImageBitmap(bmImg); } } else { Bitmap bmImg = BitmapFactory.decodeResource(getResources(), R.drawable.nophotoavailable003); btn.setImageBitmap(bmImg); } parent.addView(essen); } }
public void fillspeiseplan(Date d) { LinearLayout parent = (LinearLayout)this.findViewById(R.id.scroller); TextView datum = (TextView)this.findViewById(R.id.datum); /* First clear and show loading text */ datum.setText("Loading..."); parent.removeAllViews(); /* This actually downloads the plan, so can be rather costly */ sigfood = new SigfoodApi(d); /* Now start to fill plan and download pictures */ final Date sfspd = sigfood.speiseplandatum; datum.setText(String.format("%tA, %td.%tm.%tY", sfspd, sfspd, sfspd, sfspd)); Button next_date = (Button)this.findViewById(R.id.next_date); next_date.setEnabled(sigfood.naechstertag != null); Button prev_date = (Button)this.findViewById(R.id.prev_date); prev_date.setEnabled(sigfood.vorherigertag != null); for (final MensaEssen e : sigfood.essen) { LinearLayout essen = (LinearLayout)LayoutInflater.from(getBaseContext()).inflate(R.layout.mensaessen, null); TextView t2 = (TextView)essen.findViewById(R.id.hauptgerichtBezeichnung); t2.setText(Html.fromHtml(e.hauptgericht.bezeichnung) + "(" + e.hauptgericht.bewertung.schnitt + "/" + e.hauptgericht.bewertung.anzahl + "/" + e.hauptgericht.bewertung.stddev + ")"); TextView ueberschrift = (TextView)essen.findViewById(R.id.ueberschrift); ueberschrift.setText("Linie: " + e.linie); final Button ratingbutton = (Button)essen.findViewById(R.id.button1); TextView kommentare1 = (TextView)essen.findViewById(R.id.kommentare1); String tmp = ""; for (String s : e.hauptgericht.kommentare) { tmp += "\"" + Html.fromHtml(s) + "\"" + "\n"; } kommentare1.setText(tmp); final RatingBar bar1 = (RatingBar)essen.findViewById(R.id.ratingBar1); bar1.setMax(5); bar1.setProgress((int) (e.hauptgericht.bewertung.schnitt + 0.5f)); ratingbutton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if(bar1.isIndicator()) { ratingbutton.setText("Bewertung jetzt abgeben"); bar1.setIsIndicator(false); } else { bar1.setIsIndicator(true); ratingbutton.setEnabled(false); if (bewerten(e.hauptgericht, (int)bar1.getRating(), sfspd)) ratingbutton.setText("Bewertung abgegeben"); } } }); final Button kommentieren = (Button)essen.findViewById(R.id.kommentieren); final LinearLayout kommentar = (LinearLayout)essen.findViewById(R.id.kommentar); final EditText kommentar_name = (EditText)essen.findViewById(R.id.kommentar_name); final EditText kommentar_text = (EditText)essen.findViewById(R.id.kommentar_text); kommentieren.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if(kommentar.getVisibility() == View.GONE) { kommentar.setVisibility(View.VISIBLE); kommentieren.setText("Kommentar abschicken"); } else { kommentar.setVisibility(View.GONE); String name = kommentar_name.getText().toString(); String text = kommentar_text.getText().toString(); if(name.length() > 0 && text.length() > 0) { if(kommentieren(e.hauptgericht, sfspd, name, text)) { kommentieren.setText("Kommentar abgegeben"); kommentieren.setEnabled(false); return; } } kommentieren.setText("Kommentieren fehlgeschlagen"); } } }); ImageButton btn = (ImageButton)essen.findViewById(R.id.imageButton1); for (final Hauptgericht beilage : e.beilagen) { TextView beilage_bezeichnung = new TextView(getBaseContext(), null, android.R.attr.textAppearanceMedium); beilage_bezeichnung.setText(Html.fromHtml(beilage.bezeichnung) + "(" + beilage.bewertung.schnitt + "/" + beilage.bewertung.anzahl + "/" + e.hauptgericht.bewertung.stddev + ")"); essen.addView(beilage_bezeichnung); final RatingBar bar2 = new RatingBar(this, null,android.R.attr.ratingBarStyle); bar2.setIsIndicator(true); bar2.setNumStars(5); bar2.setMax(5); bar2.setStepSize(1); bar2.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)); bar2.setRating((int) (beilage.bewertung.schnitt + 0.5f)); essen.addView(bar2); final Button ratingbutton2 = new Button(this, null,android.R.attr.buttonStyleSmall); ratingbutton2.setText("Beilage bewerten"); ratingbutton2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if(bar2.isIndicator()) { ratingbutton2.setText("Bewertung jetzt abgeben"); bar2.setIsIndicator(false); } else { bar2.setIsIndicator(true); ratingbutton2.setEnabled(false); if (bewerten(beilage, (int)bar2.getRating(), sfspd)) ratingbutton.setText("Bewertung abgegeben"); } } }); essen.addView(ratingbutton2); TextView kommentare2 = new TextView(getBaseContext(), null, android.R.attr.textAppearanceSmall); String tmp2 = ""; for(String s : beilage.kommentare) { tmp2 += "\"" + Html.fromHtml(s) + "\"" + "\n"; } kommentare2.setText(tmp2); essen.addView(kommentare2); } btn.setTag(e); btn.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { takePhoto(v); } }); if (e.hauptgericht.bilder.size() > 0) { Random rng = new Random(); int bild_id = e.hauptgericht.bilder.get(rng.nextInt(e.hauptgericht.bilder.size())); URL myFileUrl =null; try { myFileUrl= new URL("http://www.sigfood.de/?do=getimage&bildid=" + bild_id + "&width=320"); } catch (MalformedURLException e1) { Bitmap bmImg = BitmapFactory.decodeResource(getResources(), R.drawable.picdownloadfailed); btn.setImageBitmap(bmImg); } try { HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection(); conn.setDoInput(true); conn.connect(); //int length = conn.getContentLength(); //int[] bitmapData =new int[length]; //byte[] bitmapData2 =new byte[length]; InputStream is = conn.getInputStream(); Bitmap bmImg = BitmapFactory.decodeStream(is); btn.setImageBitmap(bmImg); } catch (IOException e1) { Bitmap bmImg = BitmapFactory.decodeResource(getResources(), R.drawable.picdownloadfailed); btn.setImageBitmap(bmImg); } } else { Bitmap bmImg = BitmapFactory.decodeResource(getResources(), R.drawable.nophotoavailable003); btn.setImageBitmap(bmImg); } parent.addView(essen); } }
diff --git a/src/newt/classes/jogamp/newt/driver/linux/LinuxMouseTracker.java b/src/newt/classes/jogamp/newt/driver/linux/LinuxMouseTracker.java index 885649d17..b8a326a6c 100644 --- a/src/newt/classes/jogamp/newt/driver/linux/LinuxMouseTracker.java +++ b/src/newt/classes/jogamp/newt/driver/linux/LinuxMouseTracker.java @@ -1,221 +1,222 @@ /** * Copyright 2012 JogAmp Community. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ package jogamp.newt.driver.linux; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import jogamp.newt.WindowImpl; import com.jogamp.newt.Window; import com.jogamp.newt.event.MouseEvent; import com.jogamp.newt.event.WindowEvent; import com.jogamp.newt.event.WindowListener; import com.jogamp.newt.event.WindowUpdateEvent; /** * Experimental native mouse tracker thread for GNU/Linux * just reading <code>/dev/input/mice</code> * within it's own polling thread. */ public class LinuxMouseTracker implements WindowListener { private static final LinuxMouseTracker lmt; static { lmt = new LinuxMouseTracker(); final Thread t = new Thread(lmt.mouseDevicePoller, "NEWT-LinuxMouseTracker"); t.setDaemon(true); t.start(); } public static LinuxMouseTracker getSingleton() { return lmt; } private volatile boolean stop = false; private int x = 0; private int y = 0; private int buttonDown = 0; private int old_x = 0; private int old_y = 0; private int old_buttonDown = 0; private WindowImpl focusedWindow = null; private MouseDevicePoller mouseDevicePoller = new MouseDevicePoller(); @Override public void windowResized(WindowEvent e) { } @Override public void windowMoved(WindowEvent e) { } @Override public void windowDestroyNotify(WindowEvent e) { Object s = e.getSource(); if(focusedWindow == s) { focusedWindow = null; } } @Override public void windowDestroyed(WindowEvent e) { } @Override public void windowGainedFocus(WindowEvent e) { Object s = e.getSource(); if(s instanceof WindowImpl) { focusedWindow = (WindowImpl) s; } } @Override public void windowLostFocus(WindowEvent e) { Object s = e.getSource(); if(focusedWindow == s) { focusedWindow = null; } } @Override public void windowRepaint(WindowUpdateEvent e) { } class MouseDevicePoller implements Runnable { @Override public void run() { final byte[] b = new byte[3]; final File f = new File("/dev/input/mice"); f.setReadOnly(); InputStream fis; try { fis = new FileInputStream(f); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } int xd=0,yd=0; //x/y movement delta boolean xo=false,yo=false; // x/y overflow (out of range -255 to +255) boolean lb=false,mb=false,rb=false,hs=false,vs=false; //left/middle/right mousebutton while(!stop) { int remaining=3; while(remaining>0) { int read = 0; try { read = fis.read(b, 0, remaining); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(read<0) { stop = true; // EOF of mouse !? } else { remaining -= read; } } lb=(b[0]&1)>0; rb=(b[0]&2)>0; mb=(b[0]&4)>0; hs=(b[0]&16)>0; vs=(b[0]&32)>0; xo=(b[0]&64)>0; yo=(b[0]&128)>0; xd=b[1]; yd=b[2]; x+=xd; - y+=yd; + y-=yd; if(x<0) { x=0; } if(y<0) { y=0; } + buttonDown = 0; if(lb) { buttonDown = MouseEvent.BUTTON1; } if(mb) { buttonDown = MouseEvent.BUTTON2; } if(rb) { buttonDown = MouseEvent.BUTTON3; } if(null != focusedWindow) { if( x >= focusedWindow.getScreen().getWidth() ) { x = focusedWindow.getScreen().getWidth() - 1; } if( y >= focusedWindow.getScreen().getHeight() ) { y = focusedWindow.getScreen().getHeight() - 1; } int wx = x - focusedWindow.getX(), wy = y - focusedWindow.getY(); if(old_x != x || old_y != y) { // mouse moved focusedWindow.sendMouseEvent(MouseEvent.EVENT_MOUSE_MOVED, 0, wx, wy, 0, 0 ); } if(old_buttonDown != buttonDown) { // press/release if( 0 != buttonDown ) { focusedWindow.sendMouseEvent( MouseEvent.EVENT_MOUSE_PRESSED, 0, wx, wy, buttonDown, 0 ); } else { focusedWindow.sendMouseEvent( MouseEvent.EVENT_MOUSE_RELEASED, 0, wx, wy, old_buttonDown, 0 ); } } } else { if(Window.DEBUG_MOUSE_EVENT) { System.out.println(x+"/"+y+", hs="+hs+",vs="+vs+",lb="+lb+",rb="+rb+",mb="+mb+",xo="+xo+",yo="+yo+"xd="+xd+",yd="+yd); } } old_x = x; old_y = y; old_buttonDown = buttonDown; } if(null != fis) { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
false
true
public void run() { final byte[] b = new byte[3]; final File f = new File("/dev/input/mice"); f.setReadOnly(); InputStream fis; try { fis = new FileInputStream(f); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } int xd=0,yd=0; //x/y movement delta boolean xo=false,yo=false; // x/y overflow (out of range -255 to +255) boolean lb=false,mb=false,rb=false,hs=false,vs=false; //left/middle/right mousebutton while(!stop) { int remaining=3; while(remaining>0) { int read = 0; try { read = fis.read(b, 0, remaining); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(read<0) { stop = true; // EOF of mouse !? } else { remaining -= read; } } lb=(b[0]&1)>0; rb=(b[0]&2)>0; mb=(b[0]&4)>0; hs=(b[0]&16)>0; vs=(b[0]&32)>0; xo=(b[0]&64)>0; yo=(b[0]&128)>0; xd=b[1]; yd=b[2]; x+=xd; y+=yd; if(x<0) { x=0; } if(y<0) { y=0; } if(lb) { buttonDown = MouseEvent.BUTTON1; } if(mb) { buttonDown = MouseEvent.BUTTON2; } if(rb) { buttonDown = MouseEvent.BUTTON3; } if(null != focusedWindow) { if( x >= focusedWindow.getScreen().getWidth() ) { x = focusedWindow.getScreen().getWidth() - 1; } if( y >= focusedWindow.getScreen().getHeight() ) { y = focusedWindow.getScreen().getHeight() - 1; } int wx = x - focusedWindow.getX(), wy = y - focusedWindow.getY(); if(old_x != x || old_y != y) { // mouse moved focusedWindow.sendMouseEvent(MouseEvent.EVENT_MOUSE_MOVED, 0, wx, wy, 0, 0 ); } if(old_buttonDown != buttonDown) { // press/release if( 0 != buttonDown ) { focusedWindow.sendMouseEvent( MouseEvent.EVENT_MOUSE_PRESSED, 0, wx, wy, buttonDown, 0 ); } else { focusedWindow.sendMouseEvent( MouseEvent.EVENT_MOUSE_RELEASED, 0, wx, wy, old_buttonDown, 0 ); } } } else { if(Window.DEBUG_MOUSE_EVENT) { System.out.println(x+"/"+y+", hs="+hs+",vs="+vs+",lb="+lb+",rb="+rb+",mb="+mb+",xo="+xo+",yo="+yo+"xd="+xd+",yd="+yd); } } old_x = x; old_y = y; old_buttonDown = buttonDown; } if(null != fis) { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public void run() { final byte[] b = new byte[3]; final File f = new File("/dev/input/mice"); f.setReadOnly(); InputStream fis; try { fis = new FileInputStream(f); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } int xd=0,yd=0; //x/y movement delta boolean xo=false,yo=false; // x/y overflow (out of range -255 to +255) boolean lb=false,mb=false,rb=false,hs=false,vs=false; //left/middle/right mousebutton while(!stop) { int remaining=3; while(remaining>0) { int read = 0; try { read = fis.read(b, 0, remaining); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(read<0) { stop = true; // EOF of mouse !? } else { remaining -= read; } } lb=(b[0]&1)>0; rb=(b[0]&2)>0; mb=(b[0]&4)>0; hs=(b[0]&16)>0; vs=(b[0]&32)>0; xo=(b[0]&64)>0; yo=(b[0]&128)>0; xd=b[1]; yd=b[2]; x+=xd; y-=yd; if(x<0) { x=0; } if(y<0) { y=0; } buttonDown = 0; if(lb) { buttonDown = MouseEvent.BUTTON1; } if(mb) { buttonDown = MouseEvent.BUTTON2; } if(rb) { buttonDown = MouseEvent.BUTTON3; } if(null != focusedWindow) { if( x >= focusedWindow.getScreen().getWidth() ) { x = focusedWindow.getScreen().getWidth() - 1; } if( y >= focusedWindow.getScreen().getHeight() ) { y = focusedWindow.getScreen().getHeight() - 1; } int wx = x - focusedWindow.getX(), wy = y - focusedWindow.getY(); if(old_x != x || old_y != y) { // mouse moved focusedWindow.sendMouseEvent(MouseEvent.EVENT_MOUSE_MOVED, 0, wx, wy, 0, 0 ); } if(old_buttonDown != buttonDown) { // press/release if( 0 != buttonDown ) { focusedWindow.sendMouseEvent( MouseEvent.EVENT_MOUSE_PRESSED, 0, wx, wy, buttonDown, 0 ); } else { focusedWindow.sendMouseEvent( MouseEvent.EVENT_MOUSE_RELEASED, 0, wx, wy, old_buttonDown, 0 ); } } } else { if(Window.DEBUG_MOUSE_EVENT) { System.out.println(x+"/"+y+", hs="+hs+",vs="+vs+",lb="+lb+",rb="+rb+",mb="+mb+",xo="+xo+",yo="+yo+"xd="+xd+",yd="+yd); } } old_x = x; old_y = y; old_buttonDown = buttonDown; } if(null != fis) { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
diff --git a/src/org/melonbrew/fe/command/commands/ConvertCommand.java b/src/org/melonbrew/fe/command/commands/ConvertCommand.java index 13c24fc..b11896e 100644 --- a/src/org/melonbrew/fe/command/commands/ConvertCommand.java +++ b/src/org/melonbrew/fe/command/commands/ConvertCommand.java @@ -1,135 +1,135 @@ package org.melonbrew.fe.command.commands; import java.util.ArrayList; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.melonbrew.fe.Fe; import org.melonbrew.fe.Phrase; import org.melonbrew.fe.command.CommandType; import org.melonbrew.fe.command.SubCommand; import org.melonbrew.fe.database.converter.Converter; import org.melonbrew.fe.database.converter.Response; import org.melonbrew.fe.database.converter.ResponseType; import org.melonbrew.fe.database.converter.converters.Converter_iConomy; import org.melonbrew.fe.database.databases.MySQLDB; public class ConvertCommand extends SubCommand { private final Fe plugin; private final List<Converter> converters; public ConvertCommand(Fe plugin){ super("convert", "fe.convert", "convert (plugin) (database)", Phrase.COMMAND_CONVERT, CommandType.CONSOLE); this.plugin = plugin; converters = new ArrayList<Converter>(); converters.add(new Converter_iConomy()); } private void sendConversionList(CommandSender sender){ String message = plugin.getEqualMessage(Phrase.CONVERSION.parse(), 7); sender.sendMessage(message); for (Converter converter : converters){ message = ChatColor.GOLD + converter.getName(); message += " " + ChatColor.DARK_GRAY + "(" + ChatColor.YELLOW; if (converter.isFlatFile()){ message += Phrase.FLAT_FILE.parse(); } if (converter.isMySQL()){ if (converter.isFlatFile()){ message += ", "; } message += Phrase.MYSQL.parse(); } message += ChatColor.DARK_GRAY + ")"; sender.sendMessage(message); } sender.sendMessage(plugin.getEndEqualMessage(message.length())); } private Converter getConverter(String name){ for (Converter converter : converters){ if (converter.getName().equalsIgnoreCase(name)){ return converter; } } return null; } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ if (args.length < 1){ sendConversionList(sender); return true; } if (args.length < 2){ return false; } String type = args[1]; - if (!type.equalsIgnoreCase(Phrase.FLAT_FILE.parse()) || type.equalsIgnoreCase(Phrase.MYSQL.parse())){ + if (!type.equalsIgnoreCase(Phrase.FLAT_FILE.parse().replace(" ", "")) || !type.equalsIgnoreCase(Phrase.MYSQL.parse().replace(" ", ""))){ return false; } Converter converter = getConverter(args[0]); if (converter == null){ sender.sendMessage(plugin.getMessagePrefix() + Phrase.CONVERTER_DOES_NOT_EXIST.parse()); return true; } String supported = null; if (type.equalsIgnoreCase(Phrase.FLAT_FILE.parse()) && !converter.isFlatFile()){ supported = Phrase.FLAT_FILE.parse(); }else if (type.equalsIgnoreCase(Phrase.MYSQL.parse())){ if (!converter.mySQLtoFlatFile() && !(plugin.getFeDatabase() instanceof MySQLDB)){ sender.sendMessage(Phrase.CONVERTER_DOES_NOT_SUPPORT.parse(Phrase.MYSQL_TO_FLAT_FILE.parse())); return true; } if (!converter.isMySQL()){ supported = Phrase.MYSQL.parse(); } } if (supported != null){ sender.sendMessage(plugin.getMessagePrefix() + Phrase.CONVERTER_DOES_NOT_SUPPORT.parse(supported)); return true; } Response response; if (type.equalsIgnoreCase(Phrase.FLAT_FILE.parse())){ response = converter.convertFlatFile(plugin); }else { response = converter.convertMySQL(plugin); } if (response.getType() == ResponseType.FAILED){ sender.sendMessage(plugin.getMessagePrefix() + Phrase.CONVERSION_FAILED.parse()); } return true; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ if (args.length < 1){ sendConversionList(sender); return true; } if (args.length < 2){ return false; } String type = args[1]; if (!type.equalsIgnoreCase(Phrase.FLAT_FILE.parse()) || type.equalsIgnoreCase(Phrase.MYSQL.parse())){ return false; } Converter converter = getConverter(args[0]); if (converter == null){ sender.sendMessage(plugin.getMessagePrefix() + Phrase.CONVERTER_DOES_NOT_EXIST.parse()); return true; } String supported = null; if (type.equalsIgnoreCase(Phrase.FLAT_FILE.parse()) && !converter.isFlatFile()){ supported = Phrase.FLAT_FILE.parse(); }else if (type.equalsIgnoreCase(Phrase.MYSQL.parse())){ if (!converter.mySQLtoFlatFile() && !(plugin.getFeDatabase() instanceof MySQLDB)){ sender.sendMessage(Phrase.CONVERTER_DOES_NOT_SUPPORT.parse(Phrase.MYSQL_TO_FLAT_FILE.parse())); return true; } if (!converter.isMySQL()){ supported = Phrase.MYSQL.parse(); } } if (supported != null){ sender.sendMessage(plugin.getMessagePrefix() + Phrase.CONVERTER_DOES_NOT_SUPPORT.parse(supported)); return true; } Response response; if (type.equalsIgnoreCase(Phrase.FLAT_FILE.parse())){ response = converter.convertFlatFile(plugin); }else { response = converter.convertMySQL(plugin); } if (response.getType() == ResponseType.FAILED){ sender.sendMessage(plugin.getMessagePrefix() + Phrase.CONVERSION_FAILED.parse()); } return true; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ if (args.length < 1){ sendConversionList(sender); return true; } if (args.length < 2){ return false; } String type = args[1]; if (!type.equalsIgnoreCase(Phrase.FLAT_FILE.parse().replace(" ", "")) || !type.equalsIgnoreCase(Phrase.MYSQL.parse().replace(" ", ""))){ return false; } Converter converter = getConverter(args[0]); if (converter == null){ sender.sendMessage(plugin.getMessagePrefix() + Phrase.CONVERTER_DOES_NOT_EXIST.parse()); return true; } String supported = null; if (type.equalsIgnoreCase(Phrase.FLAT_FILE.parse()) && !converter.isFlatFile()){ supported = Phrase.FLAT_FILE.parse(); }else if (type.equalsIgnoreCase(Phrase.MYSQL.parse())){ if (!converter.mySQLtoFlatFile() && !(plugin.getFeDatabase() instanceof MySQLDB)){ sender.sendMessage(Phrase.CONVERTER_DOES_NOT_SUPPORT.parse(Phrase.MYSQL_TO_FLAT_FILE.parse())); return true; } if (!converter.isMySQL()){ supported = Phrase.MYSQL.parse(); } } if (supported != null){ sender.sendMessage(plugin.getMessagePrefix() + Phrase.CONVERTER_DOES_NOT_SUPPORT.parse(supported)); return true; } Response response; if (type.equalsIgnoreCase(Phrase.FLAT_FILE.parse())){ response = converter.convertFlatFile(plugin); }else { response = converter.convertMySQL(plugin); } if (response.getType() == ResponseType.FAILED){ sender.sendMessage(plugin.getMessagePrefix() + Phrase.CONVERSION_FAILED.parse()); } return true; }
diff --git a/src/org/mozilla/javascript/ScriptableObject.java b/src/org/mozilla/javascript/ScriptableObject.java index e011035d..8b8188a7 100644 --- a/src/org/mozilla/javascript/ScriptableObject.java +++ b/src/org/mozilla/javascript/ScriptableObject.java @@ -1,2501 +1,2499 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Daniel Gredler * Bob Jervis * Roger Lawrence * Steve Weiss * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; import java.lang.reflect.*; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.io.*; import org.mozilla.javascript.debug.DebuggableObject; /** * This is the default implementation of the Scriptable interface. This * class provides convenient default behavior that makes it easier to * define host objects. * <p> * Various properties and methods of JavaScript objects can be conveniently * defined using methods of ScriptableObject. * <p> * Classes extending ScriptableObject must define the getClassName method. * * @see org.mozilla.javascript.Scriptable * @author Norris Boyd */ public abstract class ScriptableObject implements Scriptable, Serializable, DebuggableObject, ConstProperties { /** * The empty property attribute. * * Used by getAttributes() and setAttributes(). * * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int EMPTY = 0x00; /** * Property attribute indicating assignment to this property is ignored. * * @see org.mozilla.javascript.ScriptableObject * #put(String, Scriptable, Object) * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int READONLY = 0x01; /** * Property attribute indicating property is not enumerated. * * Only enumerated properties will be returned by getIds(). * * @see org.mozilla.javascript.ScriptableObject#getIds() * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int DONTENUM = 0x02; /** * Property attribute indicating property cannot be deleted. * * @see org.mozilla.javascript.ScriptableObject#delete(String) * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int PERMANENT = 0x04; /** * Property attribute indicating that this is a const property that has not * been assigned yet. The first 'const' assignment to the property will * clear this bit. */ public static final int UNINITIALIZED_CONST = 0x08; public static final int CONST = PERMANENT|READONLY|UNINITIALIZED_CONST; /** * The prototype of this object. */ private Scriptable prototypeObject; /** * The parent scope of this object. */ private Scriptable parentScopeObject; private static final Slot REMOVED = new Slot(null, 0, READONLY); static { REMOVED.wasDeleted = true; } private transient Slot[] slots; // If count >= 0, it gives number of keys or if count < 0, // it indicates sealed object where ~count gives number of keys private int count; // gateways into the definition-order linked list of slots private transient Slot firstAdded; private transient Slot lastAdded; // cache; may be removed for smaller memory footprint private transient Slot lastAccess = REMOVED; // associated values are not serialized private transient volatile Map<Object,Object> associatedValues; private static final int SLOT_QUERY = 1; private static final int SLOT_MODIFY = 2; private static final int SLOT_REMOVE = 3; private static final int SLOT_MODIFY_GETTER_SETTER = 4; private static final int SLOT_MODIFY_CONST = 5; private static class Slot implements Serializable { private static final long serialVersionUID = -6090581677123995491L; String name; // This can change due to caching int indexOrHash; private volatile short attributes; transient volatile boolean wasDeleted; volatile Object value; transient volatile Slot next; // next in hash table bucket transient volatile Slot orderedNext; // next in linked list Slot(String name, int indexOrHash, int attributes) { this.name = name; this.indexOrHash = indexOrHash; this.attributes = (short)attributes; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (name != null) { indexOrHash = name.hashCode(); } } final int getAttributes() { return attributes; } final synchronized void setAttributes(int value) { checkValidAttributes(value); attributes = (short)value; } final void checkNotReadonly() { if ((attributes & READONLY) != 0) { String str = (name != null ? name : Integer.toString(indexOrHash)); throw Context.reportRuntimeError1("msg.modify.readonly", str); } } } private static final class GetterSlot extends Slot { static final long serialVersionUID = -4900574849788797588L; Object getter; Object setter; GetterSlot(String name, int indexOrHash, int attributes) { super(name, indexOrHash, attributes); } } static void checkValidAttributes(int attributes) { final int mask = READONLY | DONTENUM | PERMANENT | UNINITIALIZED_CONST; if ((attributes & ~mask) != 0) { throw new IllegalArgumentException(String.valueOf(attributes)); } } public ScriptableObject() { } public ScriptableObject(Scriptable scope, Scriptable prototype) { if (scope == null) throw new IllegalArgumentException(); parentScopeObject = scope; prototypeObject = prototype; } /** * Return the name of the class. * * This is typically the same name as the constructor. * Classes extending ScriptableObject must implement this abstract * method. */ public abstract String getClassName(); /** * Returns true if the named property is defined. * * @param name the name of the property * @param start the object in which the lookup began * @return true if and only if the property was found in the object */ public boolean has(String name, Scriptable start) { return null != getSlot(name, 0, SLOT_QUERY); } /** * Returns true if the property index is defined. * * @param index the numeric index for the property * @param start the object in which the lookup began * @return true if and only if the property was found in the object */ public boolean has(int index, Scriptable start) { return null != getSlot(null, index, SLOT_QUERY); } /** * Returns the value of the named property or NOT_FOUND. * * If the property was created using defineProperty, the * appropriate getter method is called. * * @param name the name of the property * @param start the object in which the lookup began * @return the value of the property (may be null), or NOT_FOUND */ public Object get(String name, Scriptable start) { return getImpl(name, 0, start); } /** * Returns the value of the indexed property or NOT_FOUND. * * @param index the numeric index for the property * @param start the object in which the lookup began * @return the value of the property (may be null), or NOT_FOUND */ public Object get(int index, Scriptable start) { return getImpl(null, index, start); } /** * Sets the value of the named property, creating it if need be. * * If the property was created using defineProperty, the * appropriate setter method is called. <p> * * If the property's attributes include READONLY, no action is * taken. * This method will actually set the property in the start * object. * * @param name the name of the property * @param start the object whose property is being set * @param value value to set the property to */ public void put(String name, Scriptable start, Object value) { if (putImpl(name, 0, start, value, EMPTY)) return; if (start == this) throw Kit.codeBug(); start.put(name, start, value); } /** * Sets the value of the indexed property, creating it if need be. * * @param index the numeric index for the property * @param start the object whose property is being set * @param value value to set the property to */ public void put(int index, Scriptable start, Object value) { if (putImpl(null, index, start, value, EMPTY)) return; if (start == this) throw Kit.codeBug(); start.put(index, start, value); } /** * Removes a named property from the object. * * If the property is not found, or it has the PERMANENT attribute, * no action is taken. * * @param name the name of the property */ public void delete(String name) { checkNotSealed(name, 0); accessSlot(name, 0, SLOT_REMOVE); } /** * Removes the indexed property from the object. * * If the property is not found, or it has the PERMANENT attribute, * no action is taken. * * @param index the numeric index for the property */ public void delete(int index) { checkNotSealed(null, index); accessSlot(null, index, SLOT_REMOVE); } /** * Sets the value of the named const property, creating it if need be. * * If the property was created using defineProperty, the * appropriate setter method is called. <p> * * If the property's attributes include READONLY, no action is * taken. * This method will actually set the property in the start * object. * * @param name the name of the property * @param start the object whose property is being set * @param value value to set the property to */ public void putConst(String name, Scriptable start, Object value) { if (putImpl(name, 0, start, value, READONLY)) return; if (start == this) throw Kit.codeBug(); if (start instanceof ConstProperties) ((ConstProperties)start).putConst(name, start, value); else start.put(name, start, value); } public void defineConst(String name, Scriptable start) { if (putImpl(name, 0, start, Undefined.instance, UNINITIALIZED_CONST)) return; if (start == this) throw Kit.codeBug(); if (start instanceof ConstProperties) ((ConstProperties)start).defineConst(name, start); } /** * Returns true if the named property is defined as a const on this object. * @param name * @return true if the named property is defined as a const, false * otherwise. */ public boolean isConst(String name) { Slot slot = getSlot(name, 0, SLOT_QUERY); if (slot == null) { return false; } return (slot.getAttributes() & (PERMANENT|READONLY)) == (PERMANENT|READONLY); } /** * @deprecated Use {@link #getAttributes(String name)}. The engine always * ignored the start argument. */ public final int getAttributes(String name, Scriptable start) { return getAttributes(name); } /** * @deprecated Use {@link #getAttributes(int index)}. The engine always * ignored the start argument. */ public final int getAttributes(int index, Scriptable start) { return getAttributes(index); } /** * @deprecated Use {@link #setAttributes(String name, int attributes)}. * The engine always ignored the start argument. */ public final void setAttributes(String name, Scriptable start, int attributes) { setAttributes(name, attributes); } /** * @deprecated Use {@link #setAttributes(int index, int attributes)}. * The engine always ignored the start argument. */ public void setAttributes(int index, Scriptable start, int attributes) { setAttributes(index, attributes); } /** * Get the attributes of a named property. * * The property is specified by <code>name</code> * as defined for <code>has</code>.<p> * * @param name the identifier for the property * @return the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public int getAttributes(String name) { return findAttributeSlot(name, 0, SLOT_QUERY).getAttributes(); } /** * Get the attributes of an indexed property. * * @param index the numeric index for the property * @exception EvaluatorException if the named property is not found * is not found * @return the bitset of attributes * @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public int getAttributes(int index) { return findAttributeSlot(null, index, SLOT_QUERY).getAttributes(); } /** * Set the attributes of a named property. * * The property is specified by <code>name</code> * as defined for <code>has</code>.<p> * * The possible attributes are READONLY, DONTENUM, * and PERMANENT. Combinations of attributes * are expressed by the bitwise OR of attributes. * EMPTY is the state of no attributes set. Any unused * bits are reserved for future use. * * @param name the name of the property * @param attributes the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.Scriptable#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public void setAttributes(String name, int attributes) { checkNotSealed(name, 0); findAttributeSlot(name, 0, SLOT_MODIFY).setAttributes(attributes); } /** * Set the attributes of an indexed property. * * @param index the numeric index for the property * @param attributes the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.Scriptable#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public void setAttributes(int index, int attributes) { checkNotSealed(null, index); findAttributeSlot(null, index, SLOT_MODIFY).setAttributes(attributes); } /** * XXX: write docs. */ public void setGetterOrSetter(String name, int index, Callable getterOrSeter, boolean isSetter) { if (name != null && index != 0) throw new IllegalArgumentException(name); checkNotSealed(name, index); GetterSlot gslot = (GetterSlot)getSlot(name, index, SLOT_MODIFY_GETTER_SETTER); gslot.checkNotReadonly(); if (isSetter) { gslot.setter = getterOrSeter; } else { gslot.getter = getterOrSeter; } gslot.value = Undefined.instance; } /** * Get the getter or setter for a given property. Used by __lookupGetter__ * and __lookupSetter__. * * @param name Name of the object. If nonnull, index must be 0. * @param index Index of the object. If nonzero, name must be null. * @param isSetter If true, return the setter, otherwise return the getter. * @exception IllegalArgumentException if both name and index are nonnull * and nonzero respectively. * @return Null if the property does not exist. Otherwise returns either * the getter or the setter for the property, depending on * the value of isSetter (may be undefined if unset). */ public Object getGetterOrSetter(String name, int index, boolean isSetter) { if (name != null && index != 0) throw new IllegalArgumentException(name); Slot slot = getSlot(name, index, SLOT_QUERY); if (slot == null) return null; if (slot instanceof GetterSlot) { GetterSlot gslot = (GetterSlot)slot; Object result = isSetter ? gslot.setter : gslot.getter; return result != null ? result : Undefined.instance; } else return Undefined.instance; } /** * Returns whether a property is a getter or a setter * @param name property name * @param index property index * @param setter true to check for a setter, false for a getter * @return whether the property is a getter or a setter */ protected boolean isGetterOrSetter(String name, int index, boolean setter) { Slot slot = getSlot(name, index, SLOT_QUERY); if (slot instanceof GetterSlot) { if (setter && ((GetterSlot)slot).setter != null) return true; if (!setter && ((GetterSlot)slot).getter != null) return true; } return false; } void addLazilyInitializedValue(String name, int index, LazilyLoadedCtor init, int attributes) { if (name != null && index != 0) throw new IllegalArgumentException(name); checkNotSealed(name, index); GetterSlot gslot = (GetterSlot)getSlot(name, index, SLOT_MODIFY_GETTER_SETTER); gslot.setAttributes(attributes); gslot.getter = null; gslot.setter = null; gslot.value = init; } /** * Returns the prototype of the object. */ public Scriptable getPrototype() { return prototypeObject; } /** * Sets the prototype of the object. */ public void setPrototype(Scriptable m) { prototypeObject = m; } /** * Returns the parent (enclosing) scope of the object. */ public Scriptable getParentScope() { return parentScopeObject; } /** * Sets the parent (enclosing) scope of the object. */ public void setParentScope(Scriptable m) { parentScopeObject = m; } /** * Returns an array of ids for the properties of the object. * * <p>Any properties with the attribute DONTENUM are not listed. <p> * * @return an array of java.lang.Objects with an entry for every * listed property. Properties accessed via an integer index will * have a corresponding * Integer entry in the returned array. Properties accessed by * a String will have a String entry in the returned array. */ public Object[] getIds() { return getIds(false); } /** * Returns an array of ids for the properties of the object. * * <p>All properties, even those with attribute DONTENUM, are listed. <p> * * @return an array of java.lang.Objects with an entry for every * listed property. Properties accessed via an integer index will * have a corresponding * Integer entry in the returned array. Properties accessed by * a String will have a String entry in the returned array. */ public Object[] getAllIds() { return getIds(true); } /** * Implements the [[DefaultValue]] internal method. * * <p>Note that the toPrimitive conversion is a no-op for * every type other than Object, for which [[DefaultValue]] * is called. See ECMA 9.1.<p> * * A <code>hint</code> of null means "no hint". * * @param typeHint the type hint * @return the default value for the object * * See ECMA 8.6.2.6. */ public Object getDefaultValue(Class<?> typeHint) { return getDefaultValue(this, typeHint); } public static Object getDefaultValue(Scriptable object, Class<?> typeHint) { Context cx = null; for (int i=0; i < 2; i++) { boolean tryToString; if (typeHint == ScriptRuntime.StringClass) { tryToString = (i == 0); } else { tryToString = (i == 1); } String methodName; Object[] args; if (tryToString) { methodName = "toString"; args = ScriptRuntime.emptyArgs; } else { methodName = "valueOf"; args = new Object[1]; String hint; if (typeHint == null) { hint = "undefined"; } else if (typeHint == ScriptRuntime.StringClass) { hint = "string"; } else if (typeHint == ScriptRuntime.ScriptableClass) { hint = "object"; } else if (typeHint == ScriptRuntime.FunctionClass) { hint = "function"; } else if (typeHint == ScriptRuntime.BooleanClass || typeHint == Boolean.TYPE) { hint = "boolean"; } else if (typeHint == ScriptRuntime.NumberClass || typeHint == ScriptRuntime.ByteClass || typeHint == Byte.TYPE || typeHint == ScriptRuntime.ShortClass || typeHint == Short.TYPE || typeHint == ScriptRuntime.IntegerClass || typeHint == Integer.TYPE || typeHint == ScriptRuntime.FloatClass || typeHint == Float.TYPE || typeHint == ScriptRuntime.DoubleClass || typeHint == Double.TYPE) { hint = "number"; } else { throw Context.reportRuntimeError1( "msg.invalid.type", typeHint.toString()); } args[0] = hint; } Object v = getProperty(object, methodName); if (!(v instanceof Function)) continue; Function fun = (Function) v; if (cx == null) cx = Context.getContext(); v = fun.call(cx, fun.getParentScope(), object, args); if (v != null) { if (!(v instanceof Scriptable)) { return v; } if (typeHint == ScriptRuntime.ScriptableClass || typeHint == ScriptRuntime.FunctionClass) { return v; } if (tryToString && v instanceof Wrapper) { // Let a wrapped java.lang.String pass for a primitive // string. Object u = ((Wrapper)v).unwrap(); if (u instanceof String) return u; } } } // fall through to error String arg = (typeHint == null) ? "undefined" : typeHint.getName(); throw ScriptRuntime.typeError1("msg.default.value", arg); } /** * Implements the instanceof operator. * * <p>This operator has been proposed to ECMA. * * @param instance The value that appeared on the LHS of the instanceof * operator * @return true if "this" appears in value's prototype chain * */ public boolean hasInstance(Scriptable instance) { // Default for JS objects (other than Function) is to do prototype // chasing. This will be overridden in NativeFunction and non-JS // objects. return ScriptRuntime.jsDelegatesTo(instance, this); } /** * Emulate the SpiderMonkey (and Firefox) feature of allowing * custom objects to avoid detection by normal "object detection" * code patterns. This is used to implement document.all. * See https://bugzilla.mozilla.org/show_bug.cgi?id=412247. * This is an analog to JOF_DETECTING from SpiderMonkey; see * https://bugzilla.mozilla.org/show_bug.cgi?id=248549. * Other than this special case, embeddings should return false. * @return true if this object should avoid object detection * @since 1.7R1 */ public boolean avoidObjectDetection() { return false; } /** * Custom <tt>==</tt> operator. * Must return {@link Scriptable#NOT_FOUND} if this object does not * have custom equality operator for the given value, * <tt>Boolean.TRUE</tt> if this object is equivalent to <tt>value</tt>, * <tt>Boolean.FALSE</tt> if this object is not equivalent to * <tt>value</tt>. * <p> * The default implementation returns Boolean.TRUE * if <tt>this == value</tt> or {@link Scriptable#NOT_FOUND} otherwise. * It indicates that by default custom equality is available only if * <tt>value</tt> is <tt>this</tt> in which case true is returned. */ protected Object equivalentValues(Object value) { return (this == value) ? Boolean.TRUE : Scriptable.NOT_FOUND; } /** * Defines JavaScript objects from a Java class that implements Scriptable. * * If the given class has a method * <pre> * static void init(Context cx, Scriptable scope, boolean sealed);</pre> * * or its compatibility form * <pre> * static void init(Scriptable scope);</pre> * * then it is invoked and no further initialization is done.<p> * * However, if no such a method is found, then the class's constructors and * methods are used to initialize a class in the following manner.<p> * * First, the zero-parameter constructor of the class is called to * create the prototype. If no such constructor exists, * a {@link EvaluatorException} is thrown. <p> * * Next, all methods are scanned for special prefixes that indicate that they * have special meaning for defining JavaScript objects. * These special prefixes are * <ul> * <li><code>jsFunction_</code> for a JavaScript function * <li><code>jsStaticFunction_</code> for a JavaScript function that * is a property of the constructor * <li><code>jsGet_</code> for a getter of a JavaScript property * <li><code>jsSet_</code> for a setter of a JavaScript property * <li><code>jsConstructor</code> for a JavaScript function that * is the constructor * </ul><p> * * If the method's name begins with "jsFunction_", a JavaScript function * is created with a name formed from the rest of the Java method name * following "jsFunction_". So a Java method named "jsFunction_foo" will * define a JavaScript method "foo". Calling this JavaScript function * will cause the Java method to be called. The parameters of the method * must be of number and types as defined by the FunctionObject class. * The JavaScript function is then added as a property * of the prototype. <p> * * If the method's name begins with "jsStaticFunction_", it is handled * similarly except that the resulting JavaScript function is added as a * property of the constructor object. The Java method must be static. * * If the method's name begins with "jsGet_" or "jsSet_", the method is * considered to define a property. Accesses to the defined property * will result in calls to these getter and setter methods. If no * setter is defined, the property is defined as READONLY.<p> * * If the method's name is "jsConstructor", the method is * considered to define the body of the constructor. Only one * method of this name may be defined. * If no method is found that can serve as constructor, a Java * constructor will be selected to serve as the JavaScript * constructor in the following manner. If the class has only one * Java constructor, that constructor is used to define * the JavaScript constructor. If the the class has two constructors, * one must be the zero-argument constructor (otherwise an * {@link EvaluatorException} would have already been thrown * when the prototype was to be created). In this case * the Java constructor with one or more parameters will be used * to define the JavaScript constructor. If the class has three * or more constructors, an {@link EvaluatorException} * will be thrown.<p> * * Finally, if there is a method * <pre> * static void finishInit(Scriptable scope, FunctionObject constructor, * Scriptable prototype)</pre> * * it will be called to finish any initialization. The <code>scope</code> * argument will be passed, along with the newly created constructor and * the newly created prototype.<p> * * @param scope The scope in which to define the constructor. * @param clazz The Java class to use to define the JavaScript objects * and properties. * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @see org.mozilla.javascript.Function * @see org.mozilla.javascript.FunctionObject * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject * #defineProperty(String, Class, int) */ public static <T extends Scriptable> void defineClass( Scriptable scope, Class<T> clazz) throws IllegalAccessException, InstantiationException, InvocationTargetException { defineClass(scope, clazz, false, false); } /** * Defines JavaScript objects from a Java class, optionally * allowing sealing. * * Similar to <code>defineClass(Scriptable scope, Class clazz)</code> * except that sealing is allowed. An object that is sealed cannot have * properties added or removed. Note that sealing is not allowed in * the current ECMA/ISO language specification, but is likely for * the next version. * * @param scope The scope in which to define the constructor. * @param clazz The Java class to use to define the JavaScript objects * and properties. The class must implement Scriptable. * @param sealed Whether or not to create sealed standard objects that * cannot be modified. * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @since 1.4R3 */ public static <T extends Scriptable> void defineClass( Scriptable scope, Class<T> clazz, boolean sealed) throws IllegalAccessException, InstantiationException, InvocationTargetException { defineClass(scope, clazz, sealed, false); } /** * Defines JavaScript objects from a Java class, optionally * allowing sealing and mapping of Java inheritance to JavaScript * prototype-based inheritance. * * Similar to <code>defineClass(Scriptable scope, Class clazz)</code> * except that sealing and inheritance mapping are allowed. An object * that is sealed cannot have properties added or removed. Note that * sealing is not allowed in the current ECMA/ISO language specification, * but is likely for the next version. * * @param scope The scope in which to define the constructor. * @param clazz The Java class to use to define the JavaScript objects * and properties. The class must implement Scriptable. * @param sealed Whether or not to create sealed standard objects that * cannot be modified. * @param mapInheritance Whether or not to map Java inheritance to * JavaScript prototype-based inheritance. * @return the class name for the prototype of the specified class * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @since 1.6R2 */ public static <T extends Scriptable> String defineClass( Scriptable scope, Class<T> clazz, boolean sealed, boolean mapInheritance) throws IllegalAccessException, InstantiationException, InvocationTargetException { BaseFunction ctor = buildClassCtor(scope, clazz, sealed, mapInheritance); if (ctor == null) return null; String name = ctor.getClassPrototype().getClassName(); defineProperty(scope, name, ctor, ScriptableObject.DONTENUM); return name; } static <T extends Scriptable> BaseFunction buildClassCtor( Scriptable scope, Class<T> clazz, boolean sealed, boolean mapInheritance) throws IllegalAccessException, InstantiationException, InvocationTargetException { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < methods.length; i++) { Method method = methods[i]; if (!method.getName().equals("init")) continue; Class<?>[] parmTypes = method.getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ContextClass && parmTypes[1] == ScriptRuntime.ScriptableClass && parmTypes[2] == Boolean.TYPE && Modifier.isStatic(method.getModifiers())) { Object args[] = { Context.getContext(), scope, sealed ? Boolean.TRUE : Boolean.FALSE }; method.invoke(null, args); return null; } if (parmTypes.length == 1 && parmTypes[0] == ScriptRuntime.ScriptableClass && Modifier.isStatic(method.getModifiers())) { Object args[] = { scope }; method.invoke(null, args); return null; } } // If we got here, there isn't an "init" method with the right // parameter types. Constructor<?>[] ctors = clazz.getConstructors(); Constructor<?> protoCtor = null; for (int i=0; i < ctors.length; i++) { if (ctors[i].getParameterTypes().length == 0) { protoCtor = ctors[i]; break; } } if (protoCtor == null) { throw Context.reportRuntimeError1( "msg.zero.arg.ctor", clazz.getName()); } Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs); String className = proto.getClassName(); // Set the prototype's prototype, trying to map Java inheritance to JS // prototype-based inheritance if requested to do so. Scriptable superProto = null; if (mapInheritance) { Class<? super T> superClass = clazz.getSuperclass(); if (ScriptRuntime.ScriptableClass.isAssignableFrom(superClass) && !Modifier.isAbstract(superClass.getModifiers())) { Class<? extends Scriptable> superScriptable = extendsScriptable(superClass); String name = ScriptableObject.defineClass(scope, superScriptable, sealed, mapInheritance); if (name != null) { superProto = ScriptableObject.getClassPrototype(scope, name); } } } if (superProto == null) { superProto = ScriptableObject.getObjectPrototype(scope); } proto.setPrototype(superProto); // Find out whether there are any methods that begin with // "js". If so, then only methods that begin with special // prefixes will be defined as JavaScript entities. final String functionPrefix = "jsFunction_"; final String staticFunctionPrefix = "jsStaticFunction_"; final String getterPrefix = "jsGet_"; final String setterPrefix = "jsSet_"; final String ctorName = "jsConstructor"; Member ctorMember = FunctionObject.findSingleMethod(methods, ctorName); if (ctorMember == null) { if (ctors.length == 1) { ctorMember = ctors[0]; } else if (ctors.length == 2) { if (ctors[0].getParameterTypes().length == 0) ctorMember = ctors[1]; else if (ctors[1].getParameterTypes().length == 0) ctorMember = ctors[0]; } if (ctorMember == null) { throw Context.reportRuntimeError1( "msg.ctor.multiple.parms", clazz.getName()); } } FunctionObject ctor = new FunctionObject(className, ctorMember, scope); if (ctor.isVarArgsMethod()) { throw Context.reportRuntimeError1 ("msg.varargs.ctor", ctorMember.getName()); } ctor.initAsConstructor(scope, proto); Method finishInit = null; HashSet<String> names = new HashSet<String>(methods.length); for (int i=0; i < methods.length; i++) { if (methods[i] == ctorMember) { continue; } String name = methods[i].getName(); if (name.equals("finishInit")) { Class<?>[] parmTypes = methods[i].getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ScriptableClass && parmTypes[1] == FunctionObject.class && parmTypes[2] == ScriptRuntime.ScriptableClass && Modifier.isStatic(methods[i].getModifiers())) { finishInit = methods[i]; continue; } } // ignore any compiler generated methods. if (name.indexOf('$') != -1) continue; if (name.equals(ctorName)) continue; String prefix = null; if (name.startsWith(functionPrefix)) { prefix = functionPrefix; } else if (name.startsWith(staticFunctionPrefix)) { prefix = staticFunctionPrefix; if (!Modifier.isStatic(methods[i].getModifiers())) { throw Context.reportRuntimeError( "jsStaticFunction must be used with static method."); } } else if (name.startsWith(getterPrefix)) { prefix = getterPrefix; - } else if (name.startsWith(setterPrefix)) { - prefix = setterPrefix; } else { + // note that setterPrefix is among the unhandled names here - + // we deal with that when we see the getter continue; } String propName = name.substring(prefix.length()); if (names.contains(propName)) { throw Context.reportRuntimeError2("duplicate.defineClass.name", name, propName); } names.add(propName); name = name.substring(prefix.length()); - if (prefix == setterPrefix) - continue; // deal with set when we see get if (prefix == getterPrefix) { if (!(proto instanceof ScriptableObject)) { throw Context.reportRuntimeError2( "msg.extend.scriptable", proto.getClass().toString(), name); } Method setter = FunctionObject.findSingleMethod( methods, setterPrefix + name); int attr = ScriptableObject.PERMANENT | ScriptableObject.DONTENUM | (setter != null ? 0 : ScriptableObject.READONLY); ((ScriptableObject) proto).defineProperty(name, null, methods[i], setter, attr); continue; } FunctionObject f = new FunctionObject(name, methods[i], proto); if (f.isVarArgsConstructor()) { throw Context.reportRuntimeError1 ("msg.varargs.fun", ctorMember.getName()); } Scriptable dest = prefix == staticFunctionPrefix ? ctor : proto; defineProperty(dest, name, f, DONTENUM); if (sealed) { f.sealObject(); } } // Call user code to complete initialization if necessary. if (finishInit != null) { Object[] finishArgs = { scope, ctor, proto }; finishInit.invoke(null, finishArgs); } // Seal the object if necessary. if (sealed) { ctor.sealObject(); if (proto instanceof ScriptableObject) { ((ScriptableObject) proto).sealObject(); } } return ctor; } @SuppressWarnings({"unchecked"}) private static <T extends Scriptable> Class<T> extendsScriptable(Class<?> c) { if (ScriptRuntime.ScriptableClass.isAssignableFrom(c)) return (Class<T>) c; return null; } /** * Define a JavaScript property. * * Creates the property with an initial value and sets its attributes. * * @param propertyName the name of the property to define. * @param value the initial value of the property * @param attributes the attributes of the JavaScript property * @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object) */ public void defineProperty(String propertyName, Object value, int attributes) { checkNotSealed(propertyName, 0); put(propertyName, this, value); setAttributes(propertyName, attributes); } /** * Utility method to add properties to arbitrary Scriptable object. * If destination is instance of ScriptableObject, calls * defineProperty there, otherwise calls put in destination * ignoring attributes */ public static void defineProperty(Scriptable destination, String propertyName, Object value, int attributes) { if (!(destination instanceof ScriptableObject)) { destination.put(propertyName, destination, value); return; } ScriptableObject so = (ScriptableObject)destination; so.defineProperty(propertyName, value, attributes); } /** * Utility method to add properties to arbitrary Scriptable object. * If destination is instance of ScriptableObject, calls * defineProperty there, otherwise calls put in destination * ignoring attributes */ public static void defineConstProperty(Scriptable destination, String propertyName) { if (destination instanceof ConstProperties) { ConstProperties cp = (ConstProperties)destination; cp.defineConst(propertyName, destination); } else defineProperty(destination, propertyName, Undefined.instance, CONST); } /** * Define a JavaScript property with getter and setter side effects. * * If the setter is not found, the attribute READONLY is added to * the given attributes. <p> * * The getter must be a method with zero parameters, and the setter, if * found, must be a method with one parameter.<p> * * @param propertyName the name of the property to define. This name * also affects the name of the setter and getter * to search for. If the propertyId is "foo", then * <code>clazz</code> will be searched for "getFoo" * and "setFoo" methods. * @param clazz the Java class to search for the getter and setter * @param attributes the attributes of the JavaScript property * @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object) */ public void defineProperty(String propertyName, Class<?> clazz, int attributes) { int length = propertyName.length(); if (length == 0) throw new IllegalArgumentException(); char[] buf = new char[3 + length]; propertyName.getChars(0, length, buf, 3); buf[3] = Character.toUpperCase(buf[3]); buf[0] = 'g'; buf[1] = 'e'; buf[2] = 't'; String getterName = new String(buf); buf[0] = 's'; String setterName = new String(buf); Method[] methods = FunctionObject.getMethodList(clazz); Method getter = FunctionObject.findSingleMethod(methods, getterName); Method setter = FunctionObject.findSingleMethod(methods, setterName); if (setter == null) attributes |= ScriptableObject.READONLY; defineProperty(propertyName, null, getter, setter == null ? null : setter, attributes); } /** * Define a JavaScript property. * * Use this method only if you wish to define getters and setters for * a given property in a ScriptableObject. To create a property without * special getter or setter side effects, use * <code>defineProperty(String,int)</code>. * * If <code>setter</code> is null, the attribute READONLY is added to * the given attributes.<p> * * Several forms of getters or setters are allowed. In all cases the * type of the value parameter can be any one of the following types: * Object, String, boolean, Scriptable, byte, short, int, long, float, * or double. The runtime will perform appropriate conversions based * upon the type of the parameter (see description in FunctionObject). * The first forms are nonstatic methods of the class referred to * by 'this': * <pre> * Object getFoo(); * void setFoo(SomeType value);</pre> * Next are static methods that may be of any class; the object whose * property is being accessed is passed in as an extra argument: * <pre> * static Object getFoo(Scriptable obj); * static void setFoo(Scriptable obj, SomeType value);</pre> * Finally, it is possible to delegate to another object entirely using * the <code>delegateTo</code> parameter. In this case the methods are * nonstatic methods of the class delegated to, and the object whose * property is being accessed is passed in as an extra argument: * <pre> * Object getFoo(Scriptable obj); * void setFoo(Scriptable obj, SomeType value);</pre> * * @param propertyName the name of the property to define. * @param delegateTo an object to call the getter and setter methods on, * or null, depending on the form used above. * @param getter the method to invoke to get the value of the property * @param setter the method to invoke to set the value of the property * @param attributes the attributes of the JavaScript property */ public void defineProperty(String propertyName, Object delegateTo, Method getter, Method setter, int attributes) { MemberBox getterBox = null; if (getter != null) { getterBox = new MemberBox(getter); boolean delegatedForm; if (!Modifier.isStatic(getter.getModifiers())) { delegatedForm = (delegateTo != null); getterBox.delegateTo = delegateTo; } else { delegatedForm = true; // Ignore delegateTo for static getter but store // non-null delegateTo indicator. getterBox.delegateTo = Void.TYPE; } String errorId = null; Class<?>[] parmTypes = getter.getParameterTypes(); if (parmTypes.length == 0) { if (delegatedForm) { errorId = "msg.obj.getter.parms"; } } else if (parmTypes.length == 1) { Object argType = parmTypes[0]; // Allow ScriptableObject for compatibility if (!(argType == ScriptRuntime.ScriptableClass || argType == ScriptRuntime.ScriptableObjectClass)) { errorId = "msg.bad.getter.parms"; } else if (!delegatedForm) { errorId = "msg.bad.getter.parms"; } } else { errorId = "msg.bad.getter.parms"; } if (errorId != null) { throw Context.reportRuntimeError1(errorId, getter.toString()); } } MemberBox setterBox = null; if (setter != null) { if (setter.getReturnType() != Void.TYPE) throw Context.reportRuntimeError1("msg.setter.return", setter.toString()); setterBox = new MemberBox(setter); boolean delegatedForm; if (!Modifier.isStatic(setter.getModifiers())) { delegatedForm = (delegateTo != null); setterBox.delegateTo = delegateTo; } else { delegatedForm = true; // Ignore delegateTo for static setter but store // non-null delegateTo indicator. setterBox.delegateTo = Void.TYPE; } String errorId = null; Class<?>[] parmTypes = setter.getParameterTypes(); if (parmTypes.length == 1) { if (delegatedForm) { errorId = "msg.setter2.expected"; } } else if (parmTypes.length == 2) { Object argType = parmTypes[0]; // Allow ScriptableObject for compatibility if (!(argType == ScriptRuntime.ScriptableClass || argType == ScriptRuntime.ScriptableObjectClass)) { errorId = "msg.setter2.parms"; } else if (!delegatedForm) { errorId = "msg.setter1.parms"; } } else { errorId = "msg.setter.parms"; } if (errorId != null) { throw Context.reportRuntimeError1(errorId, setter.toString()); } } GetterSlot gslot = (GetterSlot)getSlot(propertyName, 0, SLOT_MODIFY_GETTER_SETTER); gslot.setAttributes(attributes); gslot.getter = getterBox; gslot.setter = setterBox; } /** * Search for names in a class, adding the resulting methods * as properties. * * <p> Uses reflection to find the methods of the given names. Then * FunctionObjects are constructed from the methods found, and * are added to this object as properties with the given names. * * @param names the names of the Methods to add as function properties * @param clazz the class to search for the Methods * @param attributes the attributes of the new properties * @see org.mozilla.javascript.FunctionObject */ public void defineFunctionProperties(String[] names, Class<?> clazz, int attributes) { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < names.length; i++) { String name = names[i]; Method m = FunctionObject.findSingleMethod(methods, name); if (m == null) { throw Context.reportRuntimeError2( "msg.method.not.found", name, clazz.getName()); } FunctionObject f = new FunctionObject(name, m, this); defineProperty(name, f, attributes); } } /** * Get the Object.prototype property. * See ECMA 15.2.4. */ public static Scriptable getObjectPrototype(Scriptable scope) { return getClassPrototype(scope, "Object"); } /** * Get the Function.prototype property. * See ECMA 15.3.4. */ public static Scriptable getFunctionPrototype(Scriptable scope) { return getClassPrototype(scope, "Function"); } /** * Get the prototype for the named class. * * For example, <code>getClassPrototype(s, "Date")</code> will first * walk up the parent chain to find the outermost scope, then will * search that scope for the Date constructor, and then will * return Date.prototype. If any of the lookups fail, or * the prototype is not a JavaScript object, then null will * be returned. * * @param scope an object in the scope chain * @param className the name of the constructor * @return the prototype for the named class, or null if it * cannot be found. */ public static Scriptable getClassPrototype(Scriptable scope, String className) { scope = getTopLevelScope(scope); Object ctor = getProperty(scope, className); Object proto; if (ctor instanceof BaseFunction) { proto = ((BaseFunction)ctor).getPrototypeProperty(); } else if (ctor instanceof Scriptable) { Scriptable ctorObj = (Scriptable)ctor; proto = ctorObj.get("prototype", ctorObj); } else { return null; } if (proto instanceof Scriptable) { return (Scriptable)proto; } return null; } /** * Get the global scope. * * <p>Walks the parent scope chain to find an object with a null * parent scope (the global object). * * @param obj a JavaScript object * @return the corresponding global scope */ public static Scriptable getTopLevelScope(Scriptable obj) { for (;;) { Scriptable parent = obj.getParentScope(); if (parent == null) { return obj; } obj = parent; } } /** * Seal this object. * * A sealed object may not have properties added or removed. Once * an object is sealed it may not be unsealed. * * @since 1.4R3 */ public synchronized void sealObject() { if (count >= 0) { count = ~count; } } /** * Return true if this object is sealed. * * It is an error to attempt to add or remove properties to * a sealed object. * * @return true if sealed, false otherwise. * @since 1.4R3 */ public final boolean isSealed() { return count < 0; } private void checkNotSealed(String name, int index) { if (!isSealed()) return; String str = (name != null) ? name : Integer.toString(index); throw Context.reportRuntimeError1("msg.modify.sealed", str); } /** * Gets a named property from an object or any object in its prototype chain. * <p> * Searches the prototype chain for a property named <code>name</code>. * <p> * @param obj a JavaScript object * @param name a property name * @return the value of a property with name <code>name</code> found in * <code>obj</code> or any object in its prototype chain, or * <code>Scriptable.NOT_FOUND</code> if not found * @since 1.5R2 */ public static Object getProperty(Scriptable obj, String name) { Scriptable start = obj; Object result; do { result = obj.get(name, start); if (result != Scriptable.NOT_FOUND) break; obj = obj.getPrototype(); } while (obj != null); return result; } /** * Gets an indexed property from an object or any object in its prototype chain. * <p> * Searches the prototype chain for a property with integral index * <code>index</code>. Note that if you wish to look for properties with numerical * but non-integral indicies, you should use getProperty(Scriptable,String) with * the string value of the index. * <p> * @param obj a JavaScript object * @param index an integral index * @return the value of a property with index <code>index</code> found in * <code>obj</code> or any object in its prototype chain, or * <code>Scriptable.NOT_FOUND</code> if not found * @since 1.5R2 */ public static Object getProperty(Scriptable obj, int index) { Scriptable start = obj; Object result; do { result = obj.get(index, start); if (result != Scriptable.NOT_FOUND) break; obj = obj.getPrototype(); } while (obj != null); return result; } /** * Returns whether a named property is defined in an object or any object * in its prototype chain. * <p> * Searches the prototype chain for a property named <code>name</code>. * <p> * @param obj a JavaScript object * @param name a property name * @return the true if property was found * @since 1.5R2 */ public static boolean hasProperty(Scriptable obj, String name) { return null != getBase(obj, name); } /** * If hasProperty(obj, name) would return true, then if the property that * was found is compatible with the new property, this method just returns. * If the property is not compatible, then an exception is thrown. * * A property redefinition is incompatible if the first definition was a * const declaration or if this one is. They are compatible only if neither * was const. */ public static void redefineProperty(Scriptable obj, String name, boolean isConst) { Scriptable base = getBase(obj, name); if (base == null) return; if (base instanceof ConstProperties) { ConstProperties cp = (ConstProperties)base; if (cp.isConst(name)) throw Context.reportRuntimeError1("msg.const.redecl", name); } if (isConst) throw Context.reportRuntimeError1("msg.var.redecl", name); } /** * Returns whether an indexed property is defined in an object or any object * in its prototype chain. * <p> * Searches the prototype chain for a property with index <code>index</code>. * <p> * @param obj a JavaScript object * @param index a property index * @return the true if property was found * @since 1.5R2 */ public static boolean hasProperty(Scriptable obj, int index) { return null != getBase(obj, index); } /** * Puts a named property in an object or in an object in its prototype chain. * <p> * Searches for the named property in the prototype chain. If it is found, * the value of the property in <code>obj</code> is changed through a call * to {@link Scriptable#put(String, Scriptable, Object)} on the * prototype passing <code>obj</code> as the <code>start</code> argument. * This allows the prototype to veto the property setting in case the * prototype defines the property with [[ReadOnly]] attribute. If the * property is not found, it is added in <code>obj</code>. * @param obj a JavaScript object * @param name a property name * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putProperty(Scriptable obj, String name, Object value) { Scriptable base = getBase(obj, name); if (base == null) base = obj; base.put(name, obj, value); } /** * Puts a named property in an object or in an object in its prototype chain. * <p> * Searches for the named property in the prototype chain. If it is found, * the value of the property in <code>obj</code> is changed through a call * to {@link Scriptable#put(String, Scriptable, Object)} on the * prototype passing <code>obj</code> as the <code>start</code> argument. * This allows the prototype to veto the property setting in case the * prototype defines the property with [[ReadOnly]] attribute. If the * property is not found, it is added in <code>obj</code>. * @param obj a JavaScript object * @param name a property name * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putConstProperty(Scriptable obj, String name, Object value) { Scriptable base = getBase(obj, name); if (base == null) base = obj; if (base instanceof ConstProperties) ((ConstProperties)base).putConst(name, obj, value); } /** * Puts an indexed property in an object or in an object in its prototype chain. * <p> * Searches for the indexed property in the prototype chain. If it is found, * the value of the property in <code>obj</code> is changed through a call * to {@link Scriptable#put(int, Scriptable, Object)} on the prototype * passing <code>obj</code> as the <code>start</code> argument. This allows * the prototype to veto the property setting in case the prototype defines * the property with [[ReadOnly]] attribute. If the property is not found, * it is added in <code>obj</code>. * @param obj a JavaScript object * @param index a property index * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putProperty(Scriptable obj, int index, Object value) { Scriptable base = getBase(obj, index); if (base == null) base = obj; base.put(index, obj, value); } /** * Removes the property from an object or its prototype chain. * <p> * Searches for a property with <code>name</code> in obj or * its prototype chain. If it is found, the object's delete * method is called. * @param obj a JavaScript object * @param name a property name * @return true if the property doesn't exist or was successfully removed * @since 1.5R2 */ public static boolean deleteProperty(Scriptable obj, String name) { Scriptable base = getBase(obj, name); if (base == null) return true; base.delete(name); return !base.has(name, obj); } /** * Removes the property from an object or its prototype chain. * <p> * Searches for a property with <code>index</code> in obj or * its prototype chain. If it is found, the object's delete * method is called. * @param obj a JavaScript object * @param index a property index * @return true if the property doesn't exist or was successfully removed * @since 1.5R2 */ public static boolean deleteProperty(Scriptable obj, int index) { Scriptable base = getBase(obj, index); if (base == null) return true; base.delete(index); return !base.has(index, obj); } /** * Returns an array of all ids from an object and its prototypes. * <p> * @param obj a JavaScript object * @return an array of all ids from all object in the prototype chain. * If a given id occurs multiple times in the prototype chain, * it will occur only once in this list. * @since 1.5R2 */ public static Object[] getPropertyIds(Scriptable obj) { if (obj == null) { return ScriptRuntime.emptyArgs; } Object[] result = obj.getIds(); ObjToIntMap map = null; for (;;) { obj = obj.getPrototype(); if (obj == null) { break; } Object[] ids = obj.getIds(); if (ids.length == 0) { continue; } if (map == null) { if (result.length == 0) { result = ids; continue; } map = new ObjToIntMap(result.length + ids.length); for (int i = 0; i != result.length; ++i) { map.intern(result[i]); } result = null; // Allow to GC the result } for (int i = 0; i != ids.length; ++i) { map.intern(ids[i]); } } if (map != null) { result = map.getKeys(); } return result; } /** * Call a method of an object. * @param obj the JavaScript object * @param methodName the name of the function property * @param args the arguments for the call * * @see Context#getCurrentContext() */ public static Object callMethod(Scriptable obj, String methodName, Object[] args) { return callMethod(null, obj, methodName, args); } /** * Call a method of an object. * @param cx the Context object associated with the current thread. * @param obj the JavaScript object * @param methodName the name of the function property * @param args the arguments for the call */ public static Object callMethod(Context cx, Scriptable obj, String methodName, Object[] args) { Object funObj = getProperty(obj, methodName); if (!(funObj instanceof Function)) { throw ScriptRuntime.notFunctionError(obj, methodName); } Function fun = (Function)funObj; // XXX: What should be the scope when calling funObj? // The following favor scope stored in the object on the assumption // that is more useful especially under dynamic scope setup. // An alternative is to check for dynamic scope flag // and use ScriptableObject.getTopLevelScope(fun) if the flag is not // set. But that require access to Context and messy code // so for now it is not checked. Scriptable scope = ScriptableObject.getTopLevelScope(obj); if (cx != null) { return fun.call(cx, scope, obj, args); } else { return Context.call(null, fun, scope, obj, args); } } private static Scriptable getBase(Scriptable obj, String name) { do { if (obj.has(name, obj)) break; obj = obj.getPrototype(); } while(obj != null); return obj; } private static Scriptable getBase(Scriptable obj, int index) { do { if (obj.has(index, obj)) break; obj = obj.getPrototype(); } while(obj != null); return obj; } /** * Get arbitrary application-specific value associated with this object. * @param key key object to select particular value. * @see #associateValue(Object key, Object value) */ public final Object getAssociatedValue(Object key) { Map<Object,Object> h = associatedValues; if (h == null) return null; return h.get(key); } /** * Get arbitrary application-specific value associated with the top scope * of the given scope. * The method first calls {@link #getTopLevelScope(Scriptable scope)} * and then searches the prototype chain of the top scope for the first * object containing the associated value with the given key. * * @param scope the starting scope. * @param key key object to select particular value. * @see #getAssociatedValue(Object key) */ public static Object getTopScopeValue(Scriptable scope, Object key) { scope = ScriptableObject.getTopLevelScope(scope); for (;;) { if (scope instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject)scope; Object value = so.getAssociatedValue(key); if (value != null) { return value; } } scope = scope.getPrototype(); if (scope == null) { return null; } } } /** * Associate arbitrary application-specific value with this object. * Value can only be associated with the given object and key only once. * The method ignores any subsequent attempts to change the already * associated value. * <p> The associated values are not serialized. * @param key key object to select particular value. * @param value the value to associate * @return the passed value if the method is called first time for the * given key or old value for any subsequent calls. * @see #getAssociatedValue(Object key) */ public synchronized final Object associateValue(Object key, Object value) { if (value == null) throw new IllegalArgumentException(); Map<Object,Object> h = associatedValues; if (h == null) { h = associatedValues; if (h == null) { h = new HashMap<Object,Object>(); associatedValues = h; } } return Kit.initHash(h, key, value); } private Object getImpl(String name, int index, Scriptable start) { Slot slot = getSlot(name, index, SLOT_QUERY); if (slot == null) { return Scriptable.NOT_FOUND; } if (!(slot instanceof GetterSlot)) { return slot.value; } Object getterObj = ((GetterSlot)slot).getter; if (getterObj != null) { if (getterObj instanceof MemberBox) { MemberBox nativeGetter = (MemberBox)getterObj; Object getterThis; Object[] args; if (nativeGetter.delegateTo == null) { getterThis = start; args = ScriptRuntime.emptyArgs; } else { getterThis = nativeGetter.delegateTo; args = new Object[] { start }; } return nativeGetter.invoke(getterThis, args); } else { Function f = (Function)getterObj; Context cx = Context.getContext(); return f.call(cx, f.getParentScope(), start, ScriptRuntime.emptyArgs); } } Object value = slot.value; if (value instanceof LazilyLoadedCtor) { LazilyLoadedCtor initializer = (LazilyLoadedCtor)value; try { initializer.init(); } finally { value = initializer.getValue(); slot.value = value; } } return value; } /** * * @param name * @param index * @param start * @param value * @param constFlag EMPTY means normal put. UNINITIALIZED_CONST means * defineConstProperty. READONLY means const initialization expression. * @return false if this != start and no slot was found. true if this == start * or this != start and a READONLY slot was found. */ private boolean putImpl(String name, int index, Scriptable start, Object value, int constFlag) { Slot slot; if (this != start) { slot = getSlot(name, index, SLOT_QUERY); if (slot == null) { return false; } } else { checkNotSealed(name, index); // either const hoisted declaration or initialization if (constFlag != EMPTY) { slot = getSlot(name, index, SLOT_MODIFY_CONST); int attr = slot.getAttributes(); if ((attr & READONLY) == 0) throw Context.reportRuntimeError1("msg.var.redecl", name); if ((attr & UNINITIALIZED_CONST) != 0) { slot.value = value; // clear the bit on const initialization if (constFlag != UNINITIALIZED_CONST) slot.setAttributes(attr & ~UNINITIALIZED_CONST); } return true; } slot = getSlot(name, index, SLOT_MODIFY); } if ((slot.getAttributes() & READONLY) != 0) return true; if (slot instanceof GetterSlot) { Object setterObj = ((GetterSlot)slot).setter; if (setterObj == null) { // Odd case: Assignment to a property with only a getter // defined. The assignment cancels out the getter. ((GetterSlot)slot).getter = null; } else { Context cx = Context.getContext(); if (setterObj instanceof MemberBox) { MemberBox nativeSetter = (MemberBox)setterObj; Class<?> pTypes[] = nativeSetter.argTypes; // XXX: cache tag since it is already calculated in // defineProperty ? Class<?> valueType = pTypes[pTypes.length - 1]; int tag = FunctionObject.getTypeTag(valueType); Object actualArg = FunctionObject.convertArg(cx, start, value, tag); Object setterThis; Object[] args; if (nativeSetter.delegateTo == null) { setterThis = start; args = new Object[] { actualArg }; } else { setterThis = nativeSetter.delegateTo; args = new Object[] { start, actualArg }; } nativeSetter.invoke(setterThis, args); } else { Function f = (Function)setterObj; f.call(cx, f.getParentScope(), start, new Object[] { value }); } return true; } } if (this == start) { slot.value = value; return true; } else { return false; } } private Slot findAttributeSlot(String name, int index, int accessType) { Slot slot = getSlot(name, index, accessType); if (slot == null) { String str = (name != null ? name : Integer.toString(index)); throw Context.reportRuntimeError1("msg.prop.not.found", str); } return slot; } /** * Locate the slot with given name or index. * * @param name property name or null if slot holds spare array index. * @param index index or 0 if slot holds property name. */ private Slot getSlot(String name, int index, int accessType) { Slot slot; // Query last access cache and check that it was not deleted. lastAccessCheck: { slot = lastAccess; if (name != null) { if (name != slot.name) break lastAccessCheck; // No String.equals here as successful slot search update // name object with fresh reference of the same string. } else { if (slot.name != null || index != slot.indexOrHash) break lastAccessCheck; } if (slot.wasDeleted) break lastAccessCheck; if (accessType == SLOT_MODIFY_GETTER_SETTER && !(slot instanceof GetterSlot)) break lastAccessCheck; return slot; } slot = accessSlot(name, index, accessType); if (slot != null) { // Update the cache lastAccess = slot; } return slot; } private Slot accessSlot(String name, int index, int accessType) { int indexOrHash = (name != null ? name.hashCode() : index); if (accessType == SLOT_QUERY || accessType == SLOT_MODIFY || accessType == SLOT_MODIFY_CONST || accessType == SLOT_MODIFY_GETTER_SETTER) { // Check the hashtable without using synchronization Slot[] slotsLocalRef = slots; // Get stable local reference if (slotsLocalRef == null) { if (accessType == SLOT_QUERY) return null; } else { int tableSize = slotsLocalRef.length; int slotIndex = getSlotIndex(tableSize, indexOrHash); Slot slot = slotsLocalRef[slotIndex]; while (slot != null) { String sname = slot.name; if (sname != null) { if (sname == name) break; if (name != null && indexOrHash == slot.indexOrHash) { if (name.equals(sname)) { // This will avoid calling String.equals when // slot is accessed with same string object // next time. slot.name = name; break; } } } else if (name == null && indexOrHash == slot.indexOrHash) { break; } slot = slot.next; } if (accessType == SLOT_QUERY) { return slot; } else if (accessType == SLOT_MODIFY) { if (slot != null) return slot; } else if (accessType == SLOT_MODIFY_GETTER_SETTER) { if (slot instanceof GetterSlot) return slot; } else if (accessType == SLOT_MODIFY_CONST) { if (slot != null) return slot; } } // A new slot has to be inserted or the old has to be replaced // by GetterSlot. Time to synchronize. synchronized (this) { // Refresh local ref if another thread triggered grow slotsLocalRef = slots; int insertPos; if (count == 0) { // Always throw away old slots if any on empty insert slotsLocalRef = new Slot[5]; slots = slotsLocalRef; insertPos = getSlotIndex(slotsLocalRef.length, indexOrHash); } else { int tableSize = slotsLocalRef.length; insertPos = getSlotIndex(tableSize, indexOrHash); Slot prev = slotsLocalRef[insertPos]; Slot slot = prev; while (slot != null) { if (slot.indexOrHash == indexOrHash && (slot.name == name || (name != null && name.equals(slot.name)))) { break; } prev = slot; slot = slot.next; } if (slot != null) { // Another thread just added a slot with same // name/index before this one entered synchronized // block. This is a race in application code and // probably indicates bug there. But for the hashtable // implementation it is harmless with the only // complication is the need to replace the added slot // if we need GetterSlot and the old one is not. if (accessType == SLOT_MODIFY_GETTER_SETTER && !(slot instanceof GetterSlot)) { GetterSlot newSlot = new GetterSlot(name, indexOrHash, slot.getAttributes()); newSlot.value = slot.value; newSlot.next = slot.next; // add new slot to linked list if (lastAdded != null) lastAdded.orderedNext = newSlot; if (firstAdded == null) firstAdded = newSlot; lastAdded = newSlot; // add new slot to hash table if (prev == slot) { slotsLocalRef[insertPos] = newSlot; } else { prev.next = newSlot; } // other housekeeping slot.wasDeleted = true; slot.value = null; slot.name = null; if (slot == lastAccess) { lastAccess = REMOVED; } slot = newSlot; } else if (accessType == SLOT_MODIFY_CONST) { return null; } return slot; } // Check if the table is not too full before inserting. if (4 * (count + 1) > 3 * slotsLocalRef.length) { slotsLocalRef = new Slot[slotsLocalRef.length * 2 + 1]; copyTable(slots, slotsLocalRef, count); slots = slotsLocalRef; insertPos = getSlotIndex(slotsLocalRef.length, indexOrHash); } } Slot newSlot = (accessType == SLOT_MODIFY_GETTER_SETTER ? new GetterSlot(name, indexOrHash, 0) : new Slot(name, indexOrHash, 0)); if (accessType == SLOT_MODIFY_CONST) newSlot.setAttributes(CONST); ++count; // add new slot to linked list if (lastAdded != null) lastAdded.orderedNext = newSlot; if (firstAdded == null) firstAdded = newSlot; lastAdded = newSlot; // add new slot to hash table, return it addKnownAbsentSlot(slotsLocalRef, newSlot, insertPos); return newSlot; } } else if (accessType == SLOT_REMOVE) { synchronized (this) { Slot[] slotsLocalRef = slots; if (count != 0) { int tableSize = slots.length; int slotIndex = getSlotIndex(tableSize, indexOrHash); Slot prev = slotsLocalRef[slotIndex]; Slot slot = prev; while (slot != null) { if (slot.indexOrHash == indexOrHash && (slot.name == name || (name != null && name.equals(slot.name)))) { break; } prev = slot; slot = slot.next; } if (slot != null && (slot.getAttributes() & PERMANENT) == 0) { count--; // remove slot from hash table if (prev == slot) { slotsLocalRef[slotIndex] = slot.next; } else { prev.next = slot.next; } // Mark the slot as removed. It is still referenced // from the order-added linked list, but will be // cleaned up later slot.wasDeleted = true; slot.value = null; slot.name = null; if (slot == lastAccess) { lastAccess = REMOVED; } } } } return null; } else { throw Kit.codeBug(); } } private static int getSlotIndex(int tableSize, int indexOrHash) { return (indexOrHash & 0x7fffffff) % tableSize; } // Must be inside synchronized (this) private static void copyTable(Slot[] slots, Slot[] newSlots, int count) { if (count == 0) throw Kit.codeBug(); int tableSize = newSlots.length; int i = slots.length; for (;;) { --i; Slot slot = slots[i]; while (slot != null) { int insertPos = getSlotIndex(tableSize, slot.indexOrHash); Slot next = slot.next; addKnownAbsentSlot(newSlots, slot, insertPos); slot.next = null; slot = next; if (--count == 0) return; } } } /** * Add slot with keys that are known to absent from the table. * This is an optimization to use when inserting into empty table, * after table growth or during deserialization. */ private static void addKnownAbsentSlot(Slot[] slots, Slot slot, int insertPos) { if (slots[insertPos] == null) { slots[insertPos] = slot; } else { Slot prev = slots[insertPos]; while (prev.next != null) { prev = prev.next; } prev.next = slot; } } Object[] getIds(boolean getAll) { Slot[] s = slots; Object[] a = ScriptRuntime.emptyArgs; if (s == null) return a; int c = 0; Slot slot = firstAdded; while (slot != null && slot.wasDeleted) { // as long as we're traversing the order-added linked list, // remove deleted slots slot = slot.orderedNext; } firstAdded = slot; while (slot != null) { if (getAll || (slot.getAttributes() & DONTENUM) == 0) { if (c == 0) a = new Object[s.length]; a[c++] = slot.name != null ? (Object) slot.name : new Integer(slot.indexOrHash); } Slot next = slot.orderedNext; while (next != null && next.wasDeleted) { // remove deleted slots next = next.orderedNext; } slot.orderedNext = next; slot = next; } if (c == a.length) return a; Object[] result = new Object[c]; System.arraycopy(a, 0, result, 0, c); return result; } private synchronized void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); int objectsCount = count; if (objectsCount < 0) { // "this" was sealed objectsCount = ~objectsCount; } if (objectsCount == 0) { out.writeInt(0); } else { out.writeInt(slots.length); Slot slot = firstAdded; while (slot != null && slot.wasDeleted) { // as long as we're traversing the order-added linked list, // remove deleted slots slot = slot.orderedNext; } firstAdded = slot; while (slot != null) { out.writeObject(slot); Slot next = slot.orderedNext; while (next != null && next.wasDeleted) { // remove deleted slots next = next.orderedNext; } slot.orderedNext = next; slot = next; } } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); lastAccess = REMOVED; int tableSize = in.readInt(); if (tableSize != 0) { slots = new Slot[tableSize]; int objectsCount = count; if (objectsCount < 0) { // "this" was sealed objectsCount = ~objectsCount; } Slot prev = null; for (int i=0; i != objectsCount; ++i) { lastAdded = (Slot)in.readObject(); if (i==0) { firstAdded = lastAdded; } else { prev.orderedNext = lastAdded; } int slotIndex = getSlotIndex(tableSize, lastAdded.indexOrHash); addKnownAbsentSlot(slots, lastAdded, slotIndex); prev = lastAdded; } } } }
false
true
static <T extends Scriptable> BaseFunction buildClassCtor( Scriptable scope, Class<T> clazz, boolean sealed, boolean mapInheritance) throws IllegalAccessException, InstantiationException, InvocationTargetException { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < methods.length; i++) { Method method = methods[i]; if (!method.getName().equals("init")) continue; Class<?>[] parmTypes = method.getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ContextClass && parmTypes[1] == ScriptRuntime.ScriptableClass && parmTypes[2] == Boolean.TYPE && Modifier.isStatic(method.getModifiers())) { Object args[] = { Context.getContext(), scope, sealed ? Boolean.TRUE : Boolean.FALSE }; method.invoke(null, args); return null; } if (parmTypes.length == 1 && parmTypes[0] == ScriptRuntime.ScriptableClass && Modifier.isStatic(method.getModifiers())) { Object args[] = { scope }; method.invoke(null, args); return null; } } // If we got here, there isn't an "init" method with the right // parameter types. Constructor<?>[] ctors = clazz.getConstructors(); Constructor<?> protoCtor = null; for (int i=0; i < ctors.length; i++) { if (ctors[i].getParameterTypes().length == 0) { protoCtor = ctors[i]; break; } } if (protoCtor == null) { throw Context.reportRuntimeError1( "msg.zero.arg.ctor", clazz.getName()); } Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs); String className = proto.getClassName(); // Set the prototype's prototype, trying to map Java inheritance to JS // prototype-based inheritance if requested to do so. Scriptable superProto = null; if (mapInheritance) { Class<? super T> superClass = clazz.getSuperclass(); if (ScriptRuntime.ScriptableClass.isAssignableFrom(superClass) && !Modifier.isAbstract(superClass.getModifiers())) { Class<? extends Scriptable> superScriptable = extendsScriptable(superClass); String name = ScriptableObject.defineClass(scope, superScriptable, sealed, mapInheritance); if (name != null) { superProto = ScriptableObject.getClassPrototype(scope, name); } } } if (superProto == null) { superProto = ScriptableObject.getObjectPrototype(scope); } proto.setPrototype(superProto); // Find out whether there are any methods that begin with // "js". If so, then only methods that begin with special // prefixes will be defined as JavaScript entities. final String functionPrefix = "jsFunction_"; final String staticFunctionPrefix = "jsStaticFunction_"; final String getterPrefix = "jsGet_"; final String setterPrefix = "jsSet_"; final String ctorName = "jsConstructor"; Member ctorMember = FunctionObject.findSingleMethod(methods, ctorName); if (ctorMember == null) { if (ctors.length == 1) { ctorMember = ctors[0]; } else if (ctors.length == 2) { if (ctors[0].getParameterTypes().length == 0) ctorMember = ctors[1]; else if (ctors[1].getParameterTypes().length == 0) ctorMember = ctors[0]; } if (ctorMember == null) { throw Context.reportRuntimeError1( "msg.ctor.multiple.parms", clazz.getName()); } } FunctionObject ctor = new FunctionObject(className, ctorMember, scope); if (ctor.isVarArgsMethod()) { throw Context.reportRuntimeError1 ("msg.varargs.ctor", ctorMember.getName()); } ctor.initAsConstructor(scope, proto); Method finishInit = null; HashSet<String> names = new HashSet<String>(methods.length); for (int i=0; i < methods.length; i++) { if (methods[i] == ctorMember) { continue; } String name = methods[i].getName(); if (name.equals("finishInit")) { Class<?>[] parmTypes = methods[i].getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ScriptableClass && parmTypes[1] == FunctionObject.class && parmTypes[2] == ScriptRuntime.ScriptableClass && Modifier.isStatic(methods[i].getModifiers())) { finishInit = methods[i]; continue; } } // ignore any compiler generated methods. if (name.indexOf('$') != -1) continue; if (name.equals(ctorName)) continue; String prefix = null; if (name.startsWith(functionPrefix)) { prefix = functionPrefix; } else if (name.startsWith(staticFunctionPrefix)) { prefix = staticFunctionPrefix; if (!Modifier.isStatic(methods[i].getModifiers())) { throw Context.reportRuntimeError( "jsStaticFunction must be used with static method."); } } else if (name.startsWith(getterPrefix)) { prefix = getterPrefix; } else if (name.startsWith(setterPrefix)) { prefix = setterPrefix; } else { continue; } String propName = name.substring(prefix.length()); if (names.contains(propName)) { throw Context.reportRuntimeError2("duplicate.defineClass.name", name, propName); } names.add(propName); name = name.substring(prefix.length()); if (prefix == setterPrefix) continue; // deal with set when we see get if (prefix == getterPrefix) { if (!(proto instanceof ScriptableObject)) { throw Context.reportRuntimeError2( "msg.extend.scriptable", proto.getClass().toString(), name); } Method setter = FunctionObject.findSingleMethod( methods, setterPrefix + name); int attr = ScriptableObject.PERMANENT | ScriptableObject.DONTENUM | (setter != null ? 0 : ScriptableObject.READONLY); ((ScriptableObject) proto).defineProperty(name, null, methods[i], setter, attr); continue; } FunctionObject f = new FunctionObject(name, methods[i], proto); if (f.isVarArgsConstructor()) { throw Context.reportRuntimeError1 ("msg.varargs.fun", ctorMember.getName()); } Scriptable dest = prefix == staticFunctionPrefix ? ctor : proto; defineProperty(dest, name, f, DONTENUM); if (sealed) { f.sealObject(); } } // Call user code to complete initialization if necessary. if (finishInit != null) { Object[] finishArgs = { scope, ctor, proto }; finishInit.invoke(null, finishArgs); } // Seal the object if necessary. if (sealed) { ctor.sealObject(); if (proto instanceof ScriptableObject) { ((ScriptableObject) proto).sealObject(); } } return ctor; }
static <T extends Scriptable> BaseFunction buildClassCtor( Scriptable scope, Class<T> clazz, boolean sealed, boolean mapInheritance) throws IllegalAccessException, InstantiationException, InvocationTargetException { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < methods.length; i++) { Method method = methods[i]; if (!method.getName().equals("init")) continue; Class<?>[] parmTypes = method.getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ContextClass && parmTypes[1] == ScriptRuntime.ScriptableClass && parmTypes[2] == Boolean.TYPE && Modifier.isStatic(method.getModifiers())) { Object args[] = { Context.getContext(), scope, sealed ? Boolean.TRUE : Boolean.FALSE }; method.invoke(null, args); return null; } if (parmTypes.length == 1 && parmTypes[0] == ScriptRuntime.ScriptableClass && Modifier.isStatic(method.getModifiers())) { Object args[] = { scope }; method.invoke(null, args); return null; } } // If we got here, there isn't an "init" method with the right // parameter types. Constructor<?>[] ctors = clazz.getConstructors(); Constructor<?> protoCtor = null; for (int i=0; i < ctors.length; i++) { if (ctors[i].getParameterTypes().length == 0) { protoCtor = ctors[i]; break; } } if (protoCtor == null) { throw Context.reportRuntimeError1( "msg.zero.arg.ctor", clazz.getName()); } Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs); String className = proto.getClassName(); // Set the prototype's prototype, trying to map Java inheritance to JS // prototype-based inheritance if requested to do so. Scriptable superProto = null; if (mapInheritance) { Class<? super T> superClass = clazz.getSuperclass(); if (ScriptRuntime.ScriptableClass.isAssignableFrom(superClass) && !Modifier.isAbstract(superClass.getModifiers())) { Class<? extends Scriptable> superScriptable = extendsScriptable(superClass); String name = ScriptableObject.defineClass(scope, superScriptable, sealed, mapInheritance); if (name != null) { superProto = ScriptableObject.getClassPrototype(scope, name); } } } if (superProto == null) { superProto = ScriptableObject.getObjectPrototype(scope); } proto.setPrototype(superProto); // Find out whether there are any methods that begin with // "js". If so, then only methods that begin with special // prefixes will be defined as JavaScript entities. final String functionPrefix = "jsFunction_"; final String staticFunctionPrefix = "jsStaticFunction_"; final String getterPrefix = "jsGet_"; final String setterPrefix = "jsSet_"; final String ctorName = "jsConstructor"; Member ctorMember = FunctionObject.findSingleMethod(methods, ctorName); if (ctorMember == null) { if (ctors.length == 1) { ctorMember = ctors[0]; } else if (ctors.length == 2) { if (ctors[0].getParameterTypes().length == 0) ctorMember = ctors[1]; else if (ctors[1].getParameterTypes().length == 0) ctorMember = ctors[0]; } if (ctorMember == null) { throw Context.reportRuntimeError1( "msg.ctor.multiple.parms", clazz.getName()); } } FunctionObject ctor = new FunctionObject(className, ctorMember, scope); if (ctor.isVarArgsMethod()) { throw Context.reportRuntimeError1 ("msg.varargs.ctor", ctorMember.getName()); } ctor.initAsConstructor(scope, proto); Method finishInit = null; HashSet<String> names = new HashSet<String>(methods.length); for (int i=0; i < methods.length; i++) { if (methods[i] == ctorMember) { continue; } String name = methods[i].getName(); if (name.equals("finishInit")) { Class<?>[] parmTypes = methods[i].getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ScriptableClass && parmTypes[1] == FunctionObject.class && parmTypes[2] == ScriptRuntime.ScriptableClass && Modifier.isStatic(methods[i].getModifiers())) { finishInit = methods[i]; continue; } } // ignore any compiler generated methods. if (name.indexOf('$') != -1) continue; if (name.equals(ctorName)) continue; String prefix = null; if (name.startsWith(functionPrefix)) { prefix = functionPrefix; } else if (name.startsWith(staticFunctionPrefix)) { prefix = staticFunctionPrefix; if (!Modifier.isStatic(methods[i].getModifiers())) { throw Context.reportRuntimeError( "jsStaticFunction must be used with static method."); } } else if (name.startsWith(getterPrefix)) { prefix = getterPrefix; } else { // note that setterPrefix is among the unhandled names here - // we deal with that when we see the getter continue; } String propName = name.substring(prefix.length()); if (names.contains(propName)) { throw Context.reportRuntimeError2("duplicate.defineClass.name", name, propName); } names.add(propName); name = name.substring(prefix.length()); if (prefix == getterPrefix) { if (!(proto instanceof ScriptableObject)) { throw Context.reportRuntimeError2( "msg.extend.scriptable", proto.getClass().toString(), name); } Method setter = FunctionObject.findSingleMethod( methods, setterPrefix + name); int attr = ScriptableObject.PERMANENT | ScriptableObject.DONTENUM | (setter != null ? 0 : ScriptableObject.READONLY); ((ScriptableObject) proto).defineProperty(name, null, methods[i], setter, attr); continue; } FunctionObject f = new FunctionObject(name, methods[i], proto); if (f.isVarArgsConstructor()) { throw Context.reportRuntimeError1 ("msg.varargs.fun", ctorMember.getName()); } Scriptable dest = prefix == staticFunctionPrefix ? ctor : proto; defineProperty(dest, name, f, DONTENUM); if (sealed) { f.sealObject(); } } // Call user code to complete initialization if necessary. if (finishInit != null) { Object[] finishArgs = { scope, ctor, proto }; finishInit.invoke(null, finishArgs); } // Seal the object if necessary. if (sealed) { ctor.sealObject(); if (proto instanceof ScriptableObject) { ((ScriptableObject) proto).sealObject(); } } return ctor; }
diff --git a/ic-depress-scm-gitonline/src/org/impressivecode/depress/scm/gitonline/GitonlineLogParser.java b/ic-depress-scm-gitonline/src/org/impressivecode/depress/scm/gitonline/GitonlineLogParser.java index f92059be..5cf72376 100644 --- a/ic-depress-scm-gitonline/src/org/impressivecode/depress/scm/gitonline/GitonlineLogParser.java +++ b/ic-depress-scm-gitonline/src/org/impressivecode/depress/scm/gitonline/GitonlineLogParser.java @@ -1,268 +1,274 @@ /* ImpressiveCode Depress Framework Copyright (C) 2013 ImpressiveCode contributors This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.impressivecode.depress.scm.gitonline; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.collect.Sets.newHashSet; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.NoHeadException; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.DiffEntry.ChangeType; import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.diff.RawTextComparator; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryBuilder; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.util.io.DisabledOutputStream; /** * <code>GitLogParser</code> converts git's log output into appropriate * structure. * * Expects to receive git log generated using the following command: * * git log --pretty=format:"%H%n%ct%n%an%n%B%n%H" --raw --no-merges --abbrev=40 * * * @author Tomasz Kuzemko * @author Sławomir Kapłoński * @author Marek Majchrzak, ImpressiveCode */ public class GitonlineLogParser { public List<GitCommit> parseEntries(final String path, final GitonlineParserOptions gitParserOptions) throws IOException, ParseException, NoHeadException, GitAPIException { checkArgument(!isNullOrEmpty(path), "Path has to be set."); List<GitCommit> commitsList = processRepo(path, gitParserOptions); return commitsList; } private List<GitCommit> processRepo(final String path, final GitonlineParserOptions gitParserOptions) throws IOException, NoHeadException, GitAPIException{ RepositoryBuilder gitRepoBuilder = new RepositoryBuilder(); Repository gitRepo = gitRepoBuilder.setGitDir(new File(path)).readEnvironment().findGitDir().build(); Git git = new Git(gitRepo); List<GitCommit> analyzedCommits = new ArrayList<GitCommit>(); Iterable<RevCommit> loglines = git.log().call(); Iterator<RevCommit> logIterator = loglines.iterator(); while (logIterator.hasNext()){ RevCommit commit = logIterator.next(); GitcommitProcessor proc = new GitcommitProcessor(gitParserOptions, gitRepo); proc.setRevCommit(commit); proc.processCommitData(); analyzedCommits.add(proc.getResult()); } return analyzedCommits; } class GitcommitProcessor { private final Pattern PATTERN = Pattern.compile("^(.*) [a-f0-9]{40} (A|C|D|M|R|T)"); private GitonlineParserOptions options; private GitCommit analyzedCommit = new GitCommit(); private Repository repository; private RevCommit revCommit; public GitcommitProcessor(final GitonlineParserOptions options, final Repository repository) { this.options = options; this.repository = repository; } public void setRevCommit (final RevCommit revcommit){ this.revCommit = revcommit; } public GitCommit getResult() { return this.analyzedCommit; } private void processCommitData() throws IOException { hash(); author(); date(); message(); files(); } private void files() throws IOException { List<String> filesList= getFilesInCommit(this.repository, this.revCommit); for (String fileLine : filesList){ Matcher matcher = PATTERN.matcher(fileLine); if (matcher.matches()) { parsePath(matcher); } } } private void message() { String message = this.revCommit.getFullMessage(); if (message.endsWith("\n")){ message = message.substring(0, message.length()-1); } this.analyzedCommit.addToMessage(message); this.analyzedCommit.setMarkers(this.parseMarkers(message)); } private void author() { this.analyzedCommit.setAuthor(this.revCommit.getAuthorIdent().getName()); } private void date() { this.analyzedCommit.setDate(this.revCommit.getAuthorIdent().getWhen()); } private void hash() { String[] commitId = this.revCommit.getId().toString().split(" "); this.analyzedCommit.setId(commitId[1]); } private Set<String> parseMarkers(final String message) { if (options.hasMarkerPattern()) { Set<String> markers = newHashSet(); Matcher matcher = options.getMarkerPattern().matcher(message); while (matcher.find()) { if (matcher.groupCount() >= 1){ markers.add(matcher.group(1)); } else { markers.add(matcher.group()); } } return markers; } return Collections.<String> emptySet(); } private void parsePath(final Matcher matcher) { String operationCode = matcher.group(2); String origin = matcher.group(1); String transformed = origin.replaceAll("/", "."); // only java classes if (include(transformed)) { GitCommitFile gitFile = new GitCommitFile(); gitFile.setRawOperation(operationCode.charAt(0)); gitFile.setPath(origin); gitFile.setJavaClass(parseJavaClass(transformed)); this.analyzedCommit.getFiles().add(gitFile); } } private boolean include(final String path) { boolean java = path.endsWith(".java"); if (java) { if (options.hasPackagePrefix()) { return path.indexOf(options.getPackagePrefix()) != -1; } else { return true; } } else { return false; } } private String parseJavaClass(final String path) { String javaClass = path.replace(".java", ""); if (options.hasPackagePrefix()) { javaClass = javaClass.substring(javaClass.indexOf(options.getPackagePrefix())); } return javaClass; } } //modified method from https://github.com/gitblit/gitblit/blob/master/src/main/java/com/gitblit/utils/JGitUtils.java#L718 private List<String> getFilesInCommit(Repository repository, RevCommit commit) throws IOException { RevWalk rw = new RevWalk(repository); List<String> filesList = new ArrayList<String>(); - //System.out.println("----"+commit.getId()); + System.out.println("----"+commit.getId()+"-------"); String fileLine = ""; if (commit.getParentCount() == 0) { TreeWalk tw = new TreeWalk(repository); tw.reset(); tw.setRecursive(true); tw.addTree(commit.getTree()); while (tw.next()) { fileLine = tw.getPathString()+" "+tw.getObjectId(0).getName()+" "+this.setOperationSymbol("ADD"); } tw.release(); } else { RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree()); for (DiffEntry diff : diffs) { String objectId = diff.getNewId().name(); + System.out.println(diff.getOldPath()+" - "+diff.getChangeType()); if (diff.getChangeType().equals(ChangeType.DELETE)) { fileLine = diff.getOldPath()+" "+objectId+" "+this.setOperationSymbol(diff.getChangeType().name()); + filesList.add(fileLine); } else if (diff.getChangeType().equals(ChangeType.RENAME)) { - fileLine = diff.getNewPath()+" "+objectId+" "+this.setOperationSymbol(diff.getChangeType().name()); + //in git log there is two operations for RENAME: DELETE old file and ADD new so we need to add also two files to log: + fileLine = diff.getOldPath()+" "+objectId+" "+this.setOperationSymbol(ChangeType.DELETE.name()); + filesList.add(fileLine); + fileLine = diff.getNewPath()+" "+objectId+" "+this.setOperationSymbol(ChangeType.ADD.name()); + filesList.add(fileLine); } else { fileLine = diff.getNewPath()+" "+objectId+" "+this.setOperationSymbol(diff.getChangeType().name()); + filesList.add(fileLine); } - filesList.add(fileLine); } } return filesList; } private char setOperationSymbol(final String operationCode) { char op; switch (operationCode) { case "MODIFY": op = 'M'; break; case "ADD": op = 'A'; break; case "COPY": op = 'C'; break; case "DELETE": op = 'D'; break; case "RENAME": op = 'R'; break; default: op = 'O'; break; } return op; } }
false
true
private List<String> getFilesInCommit(Repository repository, RevCommit commit) throws IOException { RevWalk rw = new RevWalk(repository); List<String> filesList = new ArrayList<String>(); //System.out.println("----"+commit.getId()); String fileLine = ""; if (commit.getParentCount() == 0) { TreeWalk tw = new TreeWalk(repository); tw.reset(); tw.setRecursive(true); tw.addTree(commit.getTree()); while (tw.next()) { fileLine = tw.getPathString()+" "+tw.getObjectId(0).getName()+" "+this.setOperationSymbol("ADD"); } tw.release(); } else { RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree()); for (DiffEntry diff : diffs) { String objectId = diff.getNewId().name(); if (diff.getChangeType().equals(ChangeType.DELETE)) { fileLine = diff.getOldPath()+" "+objectId+" "+this.setOperationSymbol(diff.getChangeType().name()); } else if (diff.getChangeType().equals(ChangeType.RENAME)) { fileLine = diff.getNewPath()+" "+objectId+" "+this.setOperationSymbol(diff.getChangeType().name()); } else { fileLine = diff.getNewPath()+" "+objectId+" "+this.setOperationSymbol(diff.getChangeType().name()); } filesList.add(fileLine); } } return filesList; }
private List<String> getFilesInCommit(Repository repository, RevCommit commit) throws IOException { RevWalk rw = new RevWalk(repository); List<String> filesList = new ArrayList<String>(); System.out.println("----"+commit.getId()+"-------"); String fileLine = ""; if (commit.getParentCount() == 0) { TreeWalk tw = new TreeWalk(repository); tw.reset(); tw.setRecursive(true); tw.addTree(commit.getTree()); while (tw.next()) { fileLine = tw.getPathString()+" "+tw.getObjectId(0).getName()+" "+this.setOperationSymbol("ADD"); } tw.release(); } else { RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree()); for (DiffEntry diff : diffs) { String objectId = diff.getNewId().name(); System.out.println(diff.getOldPath()+" - "+diff.getChangeType()); if (diff.getChangeType().equals(ChangeType.DELETE)) { fileLine = diff.getOldPath()+" "+objectId+" "+this.setOperationSymbol(diff.getChangeType().name()); filesList.add(fileLine); } else if (diff.getChangeType().equals(ChangeType.RENAME)) { //in git log there is two operations for RENAME: DELETE old file and ADD new so we need to add also two files to log: fileLine = diff.getOldPath()+" "+objectId+" "+this.setOperationSymbol(ChangeType.DELETE.name()); filesList.add(fileLine); fileLine = diff.getNewPath()+" "+objectId+" "+this.setOperationSymbol(ChangeType.ADD.name()); filesList.add(fileLine); } else { fileLine = diff.getNewPath()+" "+objectId+" "+this.setOperationSymbol(diff.getChangeType().name()); filesList.add(fileLine); } } } return filesList; }
diff --git a/src/com/ioabsoftware/gameraven/AllInOneV2.java b/src/com/ioabsoftware/gameraven/AllInOneV2.java index 9e2193a..7fb0d42 100644 --- a/src/com/ioabsoftware/gameraven/AllInOneV2.java +++ b/src/com/ioabsoftware/gameraven/AllInOneV2.java @@ -1,3109 +1,3109 @@ package com.ioabsoftware.gameraven; import java.io.File; import java.io.IOException; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import net.simonvt.menudrawer.MenuDrawer; import net.simonvt.menudrawer.MenuDrawer.OnDrawerStateChangeListener; import net.simonvt.menudrawer.MenuDrawer.Type; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.jsoup.Connection.Response; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh; import uk.co.senab.actionbarpulltorefresh.library.DefaultHeaderTransformer; import uk.co.senab.actionbarpulltorefresh.library.Options; import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout; import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.SearchManager; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnShowListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.util.TypedValue; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.webkit.WebView; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.ListView; import android.widget.ScrollView; import android.widget.SearchView; import android.widget.Spinner; import android.widget.TextView; import com.ioabsoftware.gameraven.db.HighlightListDBHelper; import com.ioabsoftware.gameraven.db.HighlightedUser; import com.ioabsoftware.gameraven.networking.HandlesNetworkResult.NetDesc; import com.ioabsoftware.gameraven.networking.Session; import com.ioabsoftware.gameraven.views.BaseRowData; import com.ioabsoftware.gameraven.views.ViewAdapter; import com.ioabsoftware.gameraven.views.rowdata.AMPRowData; import com.ioabsoftware.gameraven.views.rowdata.AdRowData; import com.ioabsoftware.gameraven.views.rowdata.BoardRowData; import com.ioabsoftware.gameraven.views.rowdata.BoardRowData.BoardType; import com.ioabsoftware.gameraven.views.rowdata.GameSearchRowData; import com.ioabsoftware.gameraven.views.rowdata.HeaderRowData; import com.ioabsoftware.gameraven.views.rowdata.MessageRowData; import com.ioabsoftware.gameraven.views.rowdata.PMDetailRowData; import com.ioabsoftware.gameraven.views.rowdata.PMRowData; import com.ioabsoftware.gameraven.views.rowdata.TopicRowData; import com.ioabsoftware.gameraven.views.rowdata.TopicRowData.ReadStatus; import com.ioabsoftware.gameraven.views.rowdata.TopicRowData.TopicType; import com.ioabsoftware.gameraven.views.rowdata.TrackedTopicRowData; import com.ioabsoftware.gameraven.views.rowdata.UserDetailRowData; import com.ioabsoftware.gameraven.views.rowview.MessageRowView; import de.keyboardsurfer.android.widget.crouton.Configuration; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class AllInOneV2 extends Activity { public static boolean isReleaseBuild = true; public static final int SEND_PM_DIALOG = 102; public static final int MESSAGE_ACTION_DIALOG = 103; public static final int REPORT_MESSAGE_DIALOG = 104; public static final int POLL_OPTIONS_DIALOG = 105; public static final int CHANGE_LOGGED_IN_DIALOG = 106; protected static final String ACCOUNTS_PREFNAME = "com.ioabsoftware.DroidFAQs.Accounts"; protected static String secureSalt; public static final String EMPTY_STRING = ""; public static String defaultSig; /** current session */ private Session session = null; public Session getSession() {return session;} private String boardID; public String getBoardID() {return boardID;} private String topicID; public String getTopicID() {return topicID;} private String messageIDForEditing; public String getMessageID() {return messageIDForEditing;} private String postPostUrl; public String getPostPostUrl() {return postPostUrl;} private String savedPostBody; public String getSavedPostBody() { if (settings.getBoolean("autoCensorEnable", true)) return autoCensor(savedPostBody); else return savedPostBody; } private String savedPostTitle; public String getSavedPostTitle() { if (settings.getBoolean("autoCensorEnable", true)) return autoCensor(savedPostTitle); else return savedPostTitle; } /** preference object for global settings */ private static SharedPreferences settings = null; public static SharedPreferences getSettingsPref() {return settings;} /** list of accounts (username, password) */ private static SecurePreferences accounts = null; public static SecurePreferences getAccounts() {return accounts;} private LinearLayout titleWrapper; private EditText postTitle; private EditText postBody; private TextView titleCounter; private TextView bodyCounter; private Button postButton; private Button cancelButton; private Button pollButton; private View pollSep; private boolean pollUse = false; public boolean isUsingPoll() {return pollUse;} private String pollTitle = EMPTY_STRING; public String getPollTitle() {return pollTitle;} private String[] pollOptions = new String[10]; public String[] getPollOptions() {return pollOptions;} private int pollMinLevel = -1; public String getPollMinLevel() {return Integer.toString(pollMinLevel);} private LinearLayout postWrapper; private PullToRefreshLayout ptrLayout; private ListView contentList; private ActionBar aBar; private MenuItem refreshIcon; private MenuItem postIcon; private MenuItem addFavIcon; private MenuItem remFavIcon; private MenuItem searchIcon; private MenuItem topicListIcon; private String tlUrl; private enum PostMode {ON_BOARD, ON_TOPIC, NEW_PM}; private PostMode pMode; private enum FavMode {ON_BOARD, ON_TOPIC}; private FavMode fMode; private TextView title; private Button firstPage, prevPage, nextPage, lastPage; private String firstPageUrl, prevPageUrl, nextPageUrl, lastPageUrl; private NetDesc pageJumperDesc; private TextView pageLabel; private View pageJumperWrapper; public int[] getScrollerVertLoc() { int firstVis = contentList.getFirstVisiblePosition(); return new int[] {firstVis, contentList.getChildAt(0).getTop()}; } private static boolean usingLightTheme; public static boolean getUsingLightTheme() {return usingLightTheme;} private static int accentColor, accentTextColor; public static int getAccentColor() {return accentColor;}; public static int getAccentTextColor() {return accentTextColor;} private static float textScale = 1f; public static float getTextScale() {return textScale;} private static boolean isAccentLight; public static boolean isAccentLight() {return isAccentLight;} private static Style croutonStyle; public static Style getCroutonStyle() {return croutonStyle;} private static Configuration croutonShort = new Configuration.Builder() .setDuration(2500).build(); private static HighlightListDBHelper hlDB; public static HighlightListDBHelper getHLDB() {return hlDB;} private MenuDrawer drawer; private static AllInOneV2 me; public static AllInOneV2 get() {return me;} /********************************************** * START METHODS **********************************************/ @Override public void onCreate(Bundle savedInstanceState) { me = this; settings = PreferenceManager.getDefaultSharedPreferences(this); accentColor = 0; usingLightTheme = settings.getBoolean("useLightTheme", false); if (usingLightTheme) { setTheme(R.style.MyThemes_LightTheme); } super.onCreate(savedInstanceState); setContentView(R.layout.allinonev2); aBar = getActionBar(); aBar.setDisplayHomeAsUpEnabled(true); aBar.setDisplayShowTitleEnabled(false); drawer = MenuDrawer.attach(this, Type.OVERLAY); drawer.setContentView(R.layout.allinonev2); drawer.setMenuView(R.layout.drawer); drawer.setOnDrawerStateChangeListener(new OnDrawerStateChangeListener() { @Override public void onDrawerStateChange(int oldState, int newState) { if (newState == MenuDrawer.STATE_CLOSED) drawer.findViewById(R.id.dwrScroller).scrollTo(0, 0); } @Override public void onDrawerSlide(float openRatio, int offsetPixels) { // not needed } }); if (usingLightTheme) drawer.findViewById(R.id.dwrScroller).setBackgroundResource(android.R.drawable.screen_background_light); else drawer.findViewById(R.id.dwrScroller).setBackgroundResource(android.R.drawable.screen_background_dark_transparent); ((Button) drawer.findViewById(R.id.dwrChangeAcc)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawer.closeMenu(true); showDialog(CHANGE_LOGGED_IN_DIALOG); } }); ((Button) drawer.findViewById(R.id.dwrBoardJumper)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawer.closeMenu(true); session.get(NetDesc.BOARD_JUMPER, "/boards", null); } }); ((Button) drawer.findViewById(R.id.dwrAMPList)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawer.closeMenu(true); session.get(NetDesc.AMP_LIST, buildAMPLink(), null); } }); ((Button) drawer.findViewById(R.id.dwrTrackedTopics)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawer.closeMenu(true); session.get(NetDesc.TRACKED_TOPICS, "/boards/tracked", null); } }); ((Button) drawer.findViewById(R.id.dwrPMInbox)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawer.closeMenu(true); session.get(NetDesc.PM_INBOX, "/pm/", null); } }); ((Button) drawer.findViewById(R.id.dwrCopyCurrURL)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setPrimaryClip(android.content.ClipData.newPlainText("simple text", session.getLastPath())); drawer.closeMenu(true); Crouton.showText(AllInOneV2.this, "URL copied to clipboard.", croutonStyle, ptrLayout); } }); ((Button) drawer.findViewById(R.id.dwrHighlightList)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawer.closeMenu(false); startActivity(new Intent(AllInOneV2.this, SettingsHighlightedUsers.class)); } }); ((Button) drawer.findViewById(R.id.dwrSettings)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawer.closeMenu(false); startActivity(new Intent(AllInOneV2.this, SettingsMain.class)); } }); ((Button) drawer.findViewById(R.id.dwrODBugRep)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onDemandBugReport(); } }); ((Button) drawer.findViewById(R.id.dwrExit)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AllInOneV2.this.finish(); } }); // The drawable that replaces the up indicator in the action bar if (usingLightTheme) drawer.setSlideDrawable(R.drawable.ic_drawer_light); else drawer.setSlideDrawable(R.drawable.ic_drawer); // Whether the previous drawable should be shown drawer.setDrawerIndicatorEnabled(true); if (!settings.contains("defaultAccount")) { // settings need to be set to default PreferenceManager.setDefaultValues(this, R.xml.settingsmain, false); Editor sEditor = settings.edit(); sEditor.putString("defaultAccount", SettingsMain.NO_DEFAULT_ACCOUNT) .putString("timezone", TimeZone.getDefault().getID()) .commit(); } wtl("getting accounts"); if (settings.contains("secureSalt")) secureSalt = settings.getString("secureSalt", null); else { secureSalt = UUID.randomUUID().toString(); settings.edit().putString("secureSalt", secureSalt).commit(); } accounts = new SecurePreferences(getApplicationContext(), ACCOUNTS_PREFNAME, secureSalt, false); ptrLayout = (PullToRefreshLayout) findViewById(R.id.ptr_layout); // Now setup the PullToRefreshLayout ActionBarPullToRefresh.from(this) .options(Options.create() .noMinimize() .refreshOnUp(true) .build()) // Mark All Children as pullable .allChildrenArePullable() // Set the OnRefreshListener .listener(new OnRefreshListener() { @Override public void onRefreshStarted(View view) { refreshClicked(view); } }) // Finally commit the setup to our PullToRefreshLayout .setup(ptrLayout); contentList = (ListView) findViewById(R.id.aioMainList); titleWrapper = (LinearLayout) findViewById(R.id.aioPostTitleWrapper); postTitle = (EditText) findViewById(R.id.aioPostTitle); postBody = (EditText) findViewById(R.id.aioPostBody); titleCounter = (TextView) findViewById(R.id.aioPostTitleCounter); bodyCounter = (TextView) findViewById(R.id.aioPostBodyCounter); title = (TextView) findViewById(R.id.aioTitle); title.setSelected(true); pageJumperWrapper = findViewById(R.id.aioPageJumperWrapper); firstPage = (Button) findViewById(R.id.aioFirstPage); firstPage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { session.get(pageJumperDesc, firstPageUrl, null); } }); prevPage = (Button) findViewById(R.id.aioPreviousPage); prevPage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { session.get(pageJumperDesc, prevPageUrl, null); } }); nextPage = (Button) findViewById(R.id.aioNextPage); nextPage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { session.get(pageJumperDesc, nextPageUrl, null); } }); lastPage = (Button) findViewById(R.id.aioLastPage); lastPage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { session.get(pageJumperDesc, lastPageUrl, null); } }); pageLabel = (TextView) findViewById(R.id.aioPageLabel); htBase = ((TextView) drawer.findViewById(R.id.dwrChangeAccHeader)).getTextSize(); btBase = ((TextView) drawer.findViewById(R.id.dwrChangeAcc)).getTextSize(); ttBase = title.getTextSize(); pjbBase = firstPage.getTextSize(); pjlBase = pageLabel.getTextSize(); postTitle.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { String escapedTitle = StringEscapeUtils.escapeHtml4(postTitle.getText().toString()); titleCounter.setText(escapedTitle.length() + "/80"); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); postBody.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { String escapedBody = StringEscapeUtils.escapeHtml4(postBody.getText().toString()); // GFAQs adds 13(!) characters onto bodies when they have a sig, apparently. int length = escapedBody.length() + getSig().length() + 13; bodyCounter.setText(length + "/4096"); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); postButton = (Button) findViewById(R.id.aioPostDo); cancelButton = (Button) findViewById(R.id.aioPostCancel); pollButton = (Button) findViewById(R.id.aioPollOptions); pollSep = findViewById(R.id.aioPollSep); postWrapper = (LinearLayout) findViewById(R.id.aioPostWrapper); wtl("creating default sig"); defaultSig = "Posted with GameRaven *grver*"; wtl("getting css directory"); File cssDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/gameraven"); if (!cssDirectory.exists()) { wtl("css directory does not exist, creating"); cssDirectory.mkdir(); } wtl("starting db creation"); hlDB = new HighlightListDBHelper(this); wtl("onCreate finishing"); } private boolean needToSetNavList = true; public void disableNavList() { drawer.findViewById(R.id.dwrNavWrapper).setVisibility(View.GONE); needToSetNavList = true; } public void setNavList(boolean isLoggedIn) { drawer.findViewById(R.id.dwrNavWrapper).setVisibility(View.VISIBLE); if (isLoggedIn) drawer.findViewById(R.id.dwrLoggedInNav).setVisibility(View.VISIBLE); else drawer.findViewById(R.id.dwrLoggedInNav).setVisibility(View.GONE); } @Override public boolean onSearchRequested() { if (searchIcon.isVisible()) searchIcon.expandActionView(); return false; } public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { drawer.toggleMenu(); return true; } else { return super.onKeyUp(keyCode, event); } } /** Adds menu items */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); searchIcon = menu.getItem(0); topicListIcon = menu.getItem(1); addFavIcon = menu.getItem(2); remFavIcon = menu.getItem(3); postIcon = menu.getItem(4); refreshIcon = menu.getItem(5); SearchView searchView = (SearchView) searchIcon.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() { public boolean onQueryTextChange(String newText) { // just do default return false; } public boolean onQueryTextSubmit(String query) { HashMap<String, String> data = new HashMap<String, String>(); if (session.getLastDesc() == NetDesc.BOARD) { wtl("searching board for query"); data.put("search", query); session.get(NetDesc.BOARD, session.getLastPathWithoutData(), data); } else if (session.getLastDesc() == NetDesc.BOARD_JUMPER || session.getLastDesc() == NetDesc.GAME_SEARCH) { wtl("searching for games"); data.put("game", query); session.get(NetDesc.GAME_SEARCH, "/search/index.html", data); } return true; } }; searchView.setOnQueryTextListener(queryTextListener); } else { // throw new NullPointerException("searchView is null"); } return true; } /** fires when a menu option is selected */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case android.R.id.home: wtl("toggling drawer"); drawer.toggleMenu(); return true; case R.id.search: onSearchRequested(); // MenuItemCompat.expandActionView(searchIcon); return true; case R.id.addFav: AlertDialog.Builder afb = new AlertDialog.Builder(this); afb.setNegativeButton("No", null); switch (fMode) { case ON_BOARD: afb.setTitle("Add Board to Favorites?"); afb.setPositiveButton("Yes", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String addFavUrl = session.getLastPath(); if (addFavUrl.contains("remfav")) addFavUrl = addFavUrl.replace("remfav", "addfav"); else if (addFavUrl.indexOf('?') != -1) addFavUrl += "&action=addfav"; else addFavUrl += "?action=addfav"; session.get(NetDesc.BOARD, addFavUrl, null); } }); break; case ON_TOPIC: afb.setTitle("Track Topic?"); afb.setPositiveButton("Yes", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String addFavUrl = session.getLastPath(); int x = addFavUrl.indexOf('#'); if (x != -1) addFavUrl = addFavUrl.substring(0, x); if (addFavUrl.contains("stoptrack")) addFavUrl = addFavUrl.replace("stoptrack", "tracktopic"); else if (addFavUrl.indexOf('?') != -1) addFavUrl += "&action=tracktopic"; else addFavUrl += "?action=tracktopic"; session.get(NetDesc.TOPIC, addFavUrl, null); } }); break; } afb.create().show(); return true; case R.id.remFav: AlertDialog.Builder rfb = new AlertDialog.Builder(this); rfb.setNegativeButton("No", null); switch (fMode) { case ON_BOARD: rfb.setTitle("Remove Board from Favorites?"); rfb.setPositiveButton("Yes", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String remFavUrl = session.getLastPath(); if (remFavUrl.contains("addfav")) remFavUrl = remFavUrl.replace("addfav", "remfav"); else if (remFavUrl.indexOf('?') != -1) remFavUrl += "&action=remfav"; else remFavUrl += "?action=remfav"; session.get(NetDesc.BOARD, remFavUrl, null); } }); break; case ON_TOPIC: rfb.setTitle("Stop Tracking Topic?"); rfb.setPositiveButton("Yes", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String remFavUrl = session.getLastPath(); int x = remFavUrl.indexOf('#'); if (x != -1) remFavUrl = remFavUrl.substring(0, x); if (remFavUrl.contains("tracktopic")) remFavUrl = remFavUrl.replace("tracktopic", "stoptrack"); else if (remFavUrl.indexOf('?') != -1) remFavUrl += "&action=stoptrack"; else remFavUrl += "?action=stoptrack"; session.get(NetDesc.TOPIC, remFavUrl, null); } }); break; } rfb.create().show(); return true; case R.id.topiclist: session.get(NetDesc.BOARD, tlUrl, null); return true; case R.id.post: if (pMode == PostMode.ON_BOARD) postSetup(false); else if (pMode == PostMode.ON_TOPIC) postSetup(true); else if (pMode == PostMode.NEW_PM) pmSetup(EMPTY_STRING, EMPTY_STRING, EMPTY_STRING); return true; case R.id.refresh: if (session.getLastPath() == null) { if (Session.isLoggedIn()) { wtl("starting new session from case R.id.refresh, logged in"); session = new Session(this, Session.getUser(), accounts.getString(Session.getUser())); } else { wtl("starting new session from R.id.refresh, no login"); session = new Session(this); } } else session.refresh(); return true; default: return super.onOptionsItemSelected(item); } } private float htBase, btBase, ttBase, pjbBase, pjlBase; @Override public void onResume() { wtl("onResume fired"); super.onResume(); ptrLayout.setEnabled(settings.getBoolean("enablePTR", false)); float oldScale = textScale; textScale = settings.getInt("textScale", 100) / 100f; if (textScale != oldScale) { int px = TypedValue.COMPLEX_UNIT_PX; title.setTextSize(px, ttBase * getTextScale()); firstPage.setTextSize(px, pjbBase * getTextScale()); prevPage.setTextSize(px, pjbBase * getTextScale()); nextPage.setTextSize(px, pjbBase * getTextScale()); lastPage.setTextSize(px, pjbBase * getTextScale()); pageLabel.setTextSize(px, pjlBase * getTextScale()); float htSize = htBase * getTextScale(); float btSize = btBase * getTextScale(); ((TextView) drawer.findViewById(R.id.dwrChangeAccHeader)).setTextSize(px, htSize); ((TextView) drawer.findViewById(R.id.dwrChangeAcc)).setTextSize(px, btSize); ((TextView) drawer.findViewById(R.id.dwrNavHeader)).setTextSize(px, htSize); ((TextView) drawer.findViewById(R.id.dwrBoardJumper)).setTextSize(px, btSize); ((TextView) drawer.findViewById(R.id.dwrAMPList)).setTextSize(px, btSize); ((TextView) drawer.findViewById(R.id.dwrTrackedTopics)).setTextSize(px, btSize); ((TextView) drawer.findViewById(R.id.dwrPMInbox)).setTextSize(px, btSize); ((TextView) drawer.findViewById(R.id.dwrFuncHeader)).setTextSize(px, htSize); ((TextView) drawer.findViewById(R.id.dwrCopyCurrURL)).setTextSize(px, btSize); ((TextView) drawer.findViewById(R.id.dwrHighlightList)).setTextSize(px, btSize); ((TextView) drawer.findViewById(R.id.dwrSettings)).setTextSize(px, btSize); ((TextView) drawer.findViewById(R.id.dwrODBugRep)).setTextSize(px, btSize); ((TextView) drawer.findViewById(R.id.dwrExit)).setTextSize(px, btSize); } int oldColor = accentColor; accentColor = settings.getInt("accentColor", (getResources().getColor(R.color.holo_blue))); if (accentColor != oldColor) { float[] hsv = new float[3]; Color.colorToHSV(accentColor, hsv); if (settings.getBoolean("useWhiteAccentText", false)) { // color is probably dark if (hsv[2] > 0) hsv[2] *= 1.2f; else hsv[2] = 0.2f; accentTextColor = Color.WHITE; isAccentLight = false; } else { // color is probably bright hsv[2] *= 0.8f; accentTextColor = Color.BLACK; isAccentLight = true; } Drawable aBarDrawable; if (usingLightTheme) aBarDrawable = getResources().getDrawable(R.drawable.ab_transparent_dark_holo); else aBarDrawable = getResources().getDrawable(R.drawable.ab_transparent_light_holo); aBarDrawable.setColorFilter(accentColor, PorterDuff.Mode.SRC_ATOP); aBar.setBackgroundDrawable(aBarDrawable); ((DefaultHeaderTransformer) ptrLayout.getHeaderTransformer()).setProgressBarColor(accentColor); findViewById(R.id.aioPJTopSep).setBackgroundColor(accentColor); findViewById(R.id.aioFirstPrevSep).setBackgroundColor(accentColor); findViewById(R.id.aioNextLastSep).setBackgroundColor(accentColor); findViewById(R.id.aioSep).setBackgroundColor(accentColor); findViewById(R.id.aioPostWrapperSep).setBackgroundColor(accentColor); findViewById(R.id.aioPostTitleSep).setBackgroundColor(accentColor); findViewById(R.id.aioPostBodySep).setBackgroundColor(accentColor); findViewById(R.id.aioBoldSep).setBackgroundColor(accentColor); findViewById(R.id.aioItalicSep).setBackgroundColor(accentColor); findViewById(R.id.aioCodeSep).setBackgroundColor(accentColor); findViewById(R.id.aioSpoilerSep).setBackgroundColor(accentColor); findViewById(R.id.aioCiteSep).setBackgroundColor(accentColor); findViewById(R.id.aioHTMLSep).setBackgroundColor(accentColor); findViewById(R.id.aioPostButtonSep).setBackgroundColor(accentColor); findViewById(R.id.aioPollSep).setBackgroundColor(accentColor); findViewById(R.id.aioPostSep).setBackgroundColor(accentColor); drawer.findViewById(R.id.dwrCAHSep).setBackgroundColor(accentColor); drawer.findViewById(R.id.dwrNavSep).setBackgroundColor(accentColor); drawer.findViewById(R.id.dwrFuncSep).setBackgroundColor(accentColor); croutonStyle = new Style.Builder() .setBackgroundColorValue(accentColor) .setTextColorValue(accentTextColor) .setConfiguration(croutonShort) .build(); } if (session != null) { if (settings.getBoolean("reloadOnResume", false)) { wtl("session exists, reload on resume is true, refreshing page"); isRoR = true; session.refresh(); } } else { String defaultAccount = settings.getString("defaultAccount", SettingsMain.NO_DEFAULT_ACCOUNT); if (accounts.containsKey(defaultAccount)) { wtl("starting new session from onResume, logged in"); session = new Session(this, defaultAccount, accounts.getString(defaultAccount)); } else { wtl("starting new session from onResume, no login"); session = new Session(this); } } title.setSelected(true); if (!settings.contains("beenWelcomed")) { settings.edit().putBoolean("beenWelcomed", true).apply(); AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle("Welcome!"); b.setMessage("Would you like to view the quick start help files? This dialog won't be shown again."); b.setPositiveButton("Yes", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/InsanityOnABun/GameRaven/wiki"))); } }); b.setNegativeButton("No", null); b.create().show(); } wtl("onResume finishing"); } @Override public void onDestroy() { Crouton.clearCroutonsForActivity(this); super.onDestroy(); } public void setLoginName(String name) { ((TextView) findViewById(R.id.dwrChangeAcc)).setText(name + " (Click to Change)"); } public void postError(String msg) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(msg); builder.setTitle("There was a problem with your post..."); builder.setPositiveButton("Ok", null); builder.create().show(); uiCleanup(); } public void genError(String errorTitle, String errorMsg) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(errorMsg); builder.setTitle(errorTitle); builder.setPositiveButton("Ok", null); builder.create().show(); uiCleanup(); } public void noNetworkConnection() { AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle("No Network Connection"); b.setMessage("Couldn't establish network connection. Check your network settings, then try again."); b.setNegativeButton("Dismiss", null); b.show(); } public void timeoutCleanup(NetDesc desc) { String msg = "timeout msg unset"; String title = "timeout title unset"; String posButtonText = "pos button text not set"; boolean retrySub = false; switch (desc) { case LOGIN_S1: case LOGIN_S2: title = "Login Timeout"; msg = "Login timed out, press retry to try again."; posButtonText = "Retry"; break; case POSTMSG_S1: case POSTMSG_S2: case POSTMSG_S3: case POSTTPC_S1: case POSTTPC_S2: case POSTTPC_S3: case QPOSTMSG_S1: case QPOSTMSG_S3: case QPOSTTPC_S1: case QPOSTTPC_S3: title = "Post Timeout"; msg = "Post timed out. Press refresh to check if your post made it through."; posButtonText = "Refresh"; break; default: retrySub = true; title = "Timeout"; msg = "Connection timed out, press retry to try again."; posButtonText = "Retry"; break; } final boolean retry = retrySub; AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle(title); b.setMessage(msg); b.setPositiveButton(posButtonText, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (retry) session.get(session.getLastAttemptedDesc(), session.getLastAttemptedPath(), null); else refreshClicked(new View(AllInOneV2.this)); } }); b.setNegativeButton("Dismiss", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch ((session.getLastRes() == null) ? 1 : 0) { case 0: try { processContent(session.getLastRes(), session.getLastDesc(), session.getLastRes().parse(), session.getLastRes().url().toString()); } catch (IOException e) { /* THIS SHOULD NEVER CRASH * No res should be able to get set to lastRes * if it is unparseable */ e.printStackTrace(); } case 1: postExecuteCleanup(session.getLastDesc()); break; } } }); b.create().show(); } private void uiCleanup() { ptrLayout.setRefreshing(false); if (refreshIcon != null) refreshIcon.setVisible(true); if (postWrapper.getVisibility() == View.VISIBLE) { postButton.setEnabled(true); cancelButton.setEnabled(true); pollButton.setEnabled(true); if (postIcon != null) postIcon.setVisible(true); } } public void preExecuteSetup(NetDesc desc) { wtl("GRAIO dPreES fired --NEL, desc: " + desc.name()); ptrLayout.setRefreshing(true); if (refreshIcon != null) refreshIcon.setVisible(false); if (searchIcon != null) searchIcon.setVisible(false); if (postIcon != null) postIcon.setVisible(false); if (addFavIcon != null) addFavIcon.setVisible(false); if (remFavIcon != null) remFavIcon.setVisible(false); if (topicListIcon != null) topicListIcon.setVisible(false); if (desc != NetDesc.POSTMSG_S1 && desc != NetDesc.POSTTPC_S1 && desc != NetDesc.QPOSTMSG_S1 && desc != NetDesc.QPOSTTPC_S1 && desc != NetDesc.QEDIT_MSG) postCleanup(); } private boolean isRoR = false; private void postCleanup() { if (!isRoR && postWrapper.getVisibility() == View.VISIBLE) { pageJumperWrapper.setVisibility(View.VISIBLE); wtl("postCleanup fired --NEL"); postWrapper.setVisibility(View.GONE); pollButton.setVisibility(View.GONE); pollSep.setVisibility(View.GONE); postBody.setText(null); postTitle.setText(null); clearPoll(); messageIDForEditing = null; postPostUrl = null; ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)). hideSoftInputFromWindow(postBody.getWindowToken(), 0); } } public void setAMPLinkVisible(boolean visible) { if (visible) findViewById(R.id.dwrAMPWrapper).setVisibility(View.VISIBLE); else findViewById(R.id.dwrAMPWrapper).setVisibility(View.GONE); } /******************************************** * START HNR * ******************************************/ ArrayList<BaseRowData> adapterRows = new ArrayList<BaseRowData>(); ViewAdapter viewAdapter = new ViewAdapter(this, adapterRows); boolean adapterSet = false; WebView web; String adBaseUrl; StringBuilder adBuilder = new StringBuilder(); Runnable loadAds = new Runnable() { @Override public void run() {web.loadDataWithBaseURL(adBaseUrl, adBuilder.toString(), null, "iso-8859-1", null);} }; @SuppressLint("SetJavaScriptEnabled") public void processContent(Response res, NetDesc desc, Document pRes, String resUrl) { wtl("GRAIO hNR fired, desc: " + desc.name()); ptrLayout.setEnabled(false); searchIcon.setVisible(false); searchIcon.collapseActionView(); postIcon.setVisible(false); addFavIcon.setVisible(false); remFavIcon.setVisible(false); topicListIcon.setVisible(false); adapterRows.clear(); boolean isDefaultAcc; if (Session.getUser() != null && Session.getUser().equals(settings.getString("defaultAccount", SettingsMain.NO_DEFAULT_ACCOUNT))) isDefaultAcc = true; else isDefaultAcc = false; try { if (res != null) { wtl("res is not null"); wtl("setting board, topic, message id to null"); boardID = null; topicID = null; messageIDForEditing = null; Element tbody; Element pj = null; String headerTitle; String firstPage = null; String prevPage = null; String currPage = "1"; String pageCount = "1"; String nextPage = null; String lastPage = null; String bgcolor; if (usingLightTheme) bgcolor = "#ffffff"; else bgcolor = "#000000"; adBuilder.setLength(0); adBuilder.append("<html>"); adBuilder.append(pRes.head().outerHtml()); adBuilder.append("<body bgcolor=\"" + bgcolor + "\">"); for (Element e : pRes.getElementsByClass("ad")) { adBuilder.append(e.outerHtml()); e.remove(); } for (Element e : pRes.getElementsByTag("script")) { adBuilder.append(e.outerHtml()); } adBuilder.append("</body></html>"); adBaseUrl = res.url().toString(); if (web == null) web = new WebView(this); web.getSettings().setJavaScriptEnabled(AllInOneV2.getSettingsPref().getBoolean("enableJS", true)); switch (desc) { case BOARD_JUMPER: case LOGIN_S2: updateHeaderNoJumper("Board Jumper", NetDesc.BOARD_JUMPER); adapterRows.add(new HeaderRowData("Announcements")); searchIcon.setVisible(true); processBoards(pRes, true); break; case BOARD_LIST: updateHeaderNoJumper(pRes.getElementsByTag("th").get(4).text(), NetDesc.BOARD_LIST); processBoards(pRes, true); break; case PM_INBOX: tbody = pRes.getElementsByTag("tbody").first(); headerTitle = Session.getUser() + "'s PM Inbox"; if (tbody != null) { pj = pRes.select("ul.paginate").first(); if (pj != null) { String pjText = pj.child(0).text(); if (pjText.contains("Previous")) pjText = pj.child(1).text(); //Page 1 of 5 int currPageStart = 5; int ofIndex = pjText.indexOf(" of "); currPage = pjText.substring(currPageStart, ofIndex); int pageCountEnd = pjText.length(); pageCount = pjText.substring(ofIndex + 4, pageCountEnd); int currPageNum = Integer.parseInt(currPage); int pageCountNum = Integer.parseInt(pageCount); if (currPageNum > 1) { firstPage = "/pm/"; prevPage = "/pm/?page=" + (currPageNum - 2); } if (currPageNum != pageCountNum) { nextPage = "/pm/?page=" + currPageNum; lastPage = "/pm/?page=" + (pageCountNum - 1); } } updateHeader(headerTitle, firstPage, prevPage, currPage, pageCount, nextPage, lastPage, NetDesc.PM_INBOX); if (isDefaultAcc) NotifierService.dismissPMNotif(this); for (Element row : tbody.getElementsByTag("tr")) { Elements cells = row.children(); // [icon] [sender] [subject] [time] [check] boolean isOld = true; if (cells.get(0).children().first().hasClass("icon-circle")) isOld = false; String sender = cells.get(1).text(); Element subjectLinkElem = cells.get(2).children().first(); String subject = subjectLinkElem.text(); String link = subjectLinkElem.attr("href"); String time = cells.get(3).text(); adapterRows.add(new PMRowData(subject, sender, time, link, isOld)); } } else { updateHeaderNoJumper(headerTitle, NetDesc.PM_INBOX); adapterRows.add(new HeaderRowData("You have no private messages at this time.")); } postIcon.setVisible(true); pMode = PostMode.NEW_PM; break; case PM_DETAIL: headerTitle = pRes.select("h2.title").first().text(); String pmTitle = headerTitle; if (!pmTitle.startsWith("Re: ")) pmTitle = "Re: " + pmTitle; String pmMessage = pRes.select("div.body").first().outerHtml(); Element foot = pRes.select("div.foot").first(); foot.child(1).remove(); String pmFoot = foot.outerHtml(); //Sent by: P4wn4g3 on 6/1/2013 2:15:55 PM String footText = foot.text(); String sender = footText.substring(9, footText.indexOf(" on ")); updateHeaderNoJumper(pmTitle, NetDesc.PM_DETAIL); adapterRows.add(new PMDetailRowData(sender, pmTitle, pmMessage + pmFoot)); break; case AMP_LIST: wtl("GRAIO hNR determined this is an amp response"); tbody = pRes.getElementsByTag("tbody").first(); headerTitle = Session.getUser() + "'s Active Messages"; if (pRes.select("ul.paginate").size() > 1) { pj = pRes.select("ul.paginate").get(1); if (pj != null && !pj.hasClass("user") && !pj.hasClass("tsort")) { int x = 0; String pjText = pj.child(x).text(); while (pjText.contains("First") || pjText.contains("Previous")) { x++; pjText = pj.child(x).text(); } // Page 2 of 3 int currPageStart = 5; int ofIndex = pjText.indexOf(" of "); currPage = pjText.substring(currPageStart, ofIndex); int pageCountEnd = pjText.length(); pageCount = pjText.substring(ofIndex + 4, pageCountEnd); int currPageNum = Integer.parseInt(currPage); int pageCountNum = Integer.parseInt(pageCount); String amp = buildAMPLink(); if (currPageNum > 1) { firstPage = amp; prevPage = amp + "&page=" + (currPageNum - 2); } if (currPageNum != pageCountNum) { nextPage = amp + "&page=" + currPageNum; lastPage = amp + "&page=" + (pageCountNum - 1); } } } updateHeader(headerTitle, firstPage, prevPage, currPage, pageCount, nextPage, lastPage, NetDesc.AMP_LIST); if (isDefaultAcc) NotifierService.dismissAMPNotif(this); if (!tbody.children().isEmpty()) { if (settings.getBoolean("notifsEnable", false) && isDefaultAcc) { Element lPost = pRes.select("td.lastpost").first(); if (lPost != null) { String lTime = lPost.text(); Date newDate; lTime = lTime.replace("Last:", EMPTY_STRING); if (lTime.contains("AM") || lTime.contains("PM")) newDate = new SimpleDateFormat("MM'/'dd hh':'mmaa", Locale.US).parse(lTime); else newDate = new SimpleDateFormat("MM'/'dd'/'yyyy", Locale.US).parse(lTime); long newTime = newDate.getTime(); long oldTime = settings.getLong("notifsLastPost", 0); if (newTime > oldTime) { wtl("time is newer"); settings.edit().putLong("notifsLastPost", newTime).commit(); } } } for (Element row : tbody.children()) { // [board] [title] [msg] [last post] [your last post] Elements cells = row.children(); String board = cells.get(0).text(); Element titleLinkElem = cells.get(1).child(0); String title = titleLinkElem.text(); String link = titleLinkElem.attr("href"); String mCount = cells.get(2).textNodes().get(0).text().trim(); Element lPostLinkElem = cells.get(3).child(1); String lPost = lPostLinkElem.text(); String lPostLink = lPostLinkElem.attr("href"); String ylpLink = cells.get(4).child(1).attr("href"); adapterRows.add(new AMPRowData(title, board, lPost, mCount, link, lPostLink, ylpLink)); } } else { adapterRows.add(new HeaderRowData("You have no active messages at this time.")); } wtl("amp response block finished"); break; case TRACKED_TOPICS: headerTitle = Session.getUser() + "'s Tracked Topics"; updateHeaderNoJumper(headerTitle, desc); if (isDefaultAcc) NotifierService.dismissTTNotif(this); tbody = pRes.getElementsByTag("tbody").first(); if (tbody != null) { for (Element row : tbody.children()) { // [remove] [title] [board name] [msgs] [last [pst] Elements cells = row.children(); String removeLink = cells.get(0).child(0) .attr("href"); String topicLink = cells.get(1).child(0) .attr("href"); String topicText = cells.get(1).text(); String board = cells.get(2).text(); String msgs = cells.get(3).text(); String lPostLink = cells.get(4).child(0) .attr("href"); String lPostText = cells.get(4).text(); adapterRows.add(new TrackedTopicRowData(board, topicText, lPostText, msgs, topicLink, removeLink, lPostLink)); } } else { adapterRows.add(new HeaderRowData("You have no tracked topics at this time.")); } break; case BOARD: wtl("GRAIO hNR determined this is a board response"); wtl("setting board id"); boardID = parseBoardID(resUrl); boolean isSplitList = false; if (pRes.getElementsByTag("th").first() != null) { if (pRes.getElementsByTag("th").first().text().equals("Board Title")) { wtl("is actually a split board list"); updateHeaderNoJumper(pRes.select("h1.page-title").first().text(), NetDesc.BOARD); processBoards(pRes, false); isSplitList = true; } } if (!isSplitList) { String url = resUrl; String searchQuery = EMPTY_STRING; String searchPJAddition = EMPTY_STRING; if (url.contains("search=")) { wtl("board search url: " + url); searchQuery = url.substring(url.indexOf("search=") + 7); int i = searchQuery.indexOf('&'); if (i != -1) searchQuery.replace(searchQuery.substring(i), EMPTY_STRING); searchPJAddition = "&search=" + searchQuery; searchQuery = URLDecoder.decode(searchQuery); } Element headerElem = pRes.getElementsByClass("page-title").first(); if (headerElem != null) headerTitle = headerElem.text(); else headerTitle = "GFAQs Cache Error, Board Title Not Found"; if (searchQuery.length() > 0) headerTitle += " (search: " + searchQuery + ")"; if (pRes.select("ul.paginate").size() > 1) { pj = pRes.select("ul.paginate").get(1); if (pj != null && !pj.hasClass("user")) { int x = 0; String pjText = pj.child(x).text(); while (pjText.contains("First") || pjText.contains("Previous")) { x++; pjText = pj.child(x).text(); } // Page [dropdown] of 3 // Page 1 of 3 int ofIndex = pjText.indexOf(" of "); int currPageStart = 5; if (pj.getElementsByTag("select").isEmpty()) currPage = pjText.substring(currPageStart, ofIndex); else currPage = pj .select("option[selected=selected]") .first().text(); int pageCountEnd = pjText.length(); pageCount = pjText.substring(ofIndex + 4, pageCountEnd); int currPageNum = Integer.parseInt(currPage); int pageCountNum = Integer.parseInt(pageCount); if (currPageNum > 1) { firstPage = "boards/" + boardID + "?page=0" + searchPJAddition; prevPage = "boards/" + boardID + "?page=" + (currPageNum - 2) + searchPJAddition; } if (currPageNum != pageCountNum) { nextPage = "boards/" + boardID + "?page=" + currPageNum + searchPJAddition; lastPage = "boards/" + boardID + "?page=" + (pageCountNum - 1) + searchPJAddition; } } } updateHeader(headerTitle, firstPage, prevPage, currPage, pageCount, nextPage, lastPage, NetDesc.BOARD); searchIcon.setVisible(true); if (Session.isLoggedIn()) { String favtext = pRes.getElementsByClass("user").first().text().toLowerCase(Locale.US); if (favtext.contains("add to favorites")) { addFavIcon.setVisible(true); fMode = FavMode.ON_BOARD; } else if (favtext.contains("remove favorite")) { remFavIcon.setVisible(true); fMode = FavMode.ON_BOARD; } updatePostingRights(pRes, false); } Element splitList = pRes.select("p:contains(this is a split board)").first(); if (splitList != null) { String splitListLink = splitList.child(0).attr("href"); adapterRows.add(new BoardRowData("This is a Split Board.", "Click here to return to the Split List.", null, null, null, splitListLink, BoardType.SPLIT)); } Element table = pRes.select("table.board").first(); if (table != null) { table.getElementsByTag("col").get(2).remove(); table.getElementsByTag("th").get(2).remove(); table.getElementsByTag("col").get(0).remove(); table.getElementsByTag("th").get(0).remove(); wtl("board row parsing start"); boolean skipFirst = true; Set<String> hlUsers = hlDB.getHighlightedUsers().keySet(); for (Element row : table.getElementsByTag("tr")) { if (!skipFirst) { Elements cells = row.getElementsByTag("td"); // cells = [image] [title] [author] [post count] [last post] String tImg = cells.get(0).child(0).className(); Element titleLinkElem = cells.get(1).child(0); String title = titleLinkElem.text(); String tUrl = titleLinkElem.attr("href"); String tc = cells.get(2).text(); Element lPostLinkElem = cells.get(4).child(0); String lastPost = lPostLinkElem.text(); String lpUrl = lPostLinkElem.attr("href"); String mCount = cells.get(3).text(); TopicType type = TopicType.NORMAL; if (tImg.contains("poll")) type = TopicType.POLL; else if (tImg.contains("sticky")) type = TopicType.PINNED; else if (tImg.contains("closed")) type = TopicType.LOCKED; else if (tImg.contains("archived")) type = TopicType.ARCHIVED; wtl(tImg + ", " + type.name()); ReadStatus status = ReadStatus.UNREAD; if (tImg.endsWith("_read")) status = ReadStatus.READ; else if (tImg.endsWith("_unread")) status = ReadStatus.NEW_POST; int hlColor = 0; if (hlUsers.contains(tc.toLowerCase(Locale.US))) { HighlightedUser hUser = hlDB.getHighlightedUsers().get(tc.toLowerCase(Locale.US)); hlColor = hUser.getColor(); tc += " (" + hUser.getLabel() + ")"; } adapterRows.add(new TopicRowData(title, tc, lastPost, mCount, tUrl, lpUrl, type, status, hlColor)); } else skipFirst = false; } wtl("board row parsing end"); } else { adapterRows.add(new HeaderRowData("There are no topics at this time.")); } } wtl("board response block finished"); break; case TOPIC: boardID = parseBoardID(resUrl); topicID = parseTopicID(resUrl); tlUrl = "boards/" + boardID; wtl(tlUrl); topicListIcon.setVisible(true); Element headerElem = pRes.getElementsByClass("title").first(); if (headerElem != null) headerTitle = headerElem.text(); else headerTitle = "GFAQs Cache Error, Title Not Found"; if (headerTitle.equals("Log In to GameFAQs")) { headerElem = pRes.getElementsByClass("title").get(1); if (headerElem != null) headerTitle = headerElem.text(); } if (pRes.select("ul.paginate").size() > 1) { pj = pRes.select("ul.paginate").get(1); if (pj != null && !pj.hasClass("user")) { int x = 0; String pjText = pj.child(x).text(); while (pjText.contains("First") || pjText.contains("Previous")) { x++; pjText = pj.child(x).text(); } // Page [dropdown] of 3 // Page 1 of 3 int ofIndex = pjText.indexOf(" of "); int currPageStart = 5; if (pj.getElementsByTag("select").isEmpty()) currPage = pjText.substring(currPageStart, ofIndex); else currPage = pj .select("option[selected=selected]") .first().text(); int pageCountEnd = pjText.length(); pageCount = pjText.substring(ofIndex + 4, pageCountEnd); int currPageNum = Integer.parseInt(currPage); int pageCountNum = Integer.parseInt(pageCount); if (currPageNum > 1) { firstPage = "boards/" + boardID + "/" + topicID; prevPage = "boards/" + boardID + "/" + topicID + "?page=" + (currPageNum - 2); } if (currPageNum != pageCountNum) { nextPage = "boards/" + boardID + "/" + topicID + "?page=" + currPageNum; lastPage = "boards/" + boardID + "/" + topicID + "?page=" + (pageCountNum - 1); } } } updateHeader(headerTitle, firstPage, prevPage, currPage, pageCount, nextPage, lastPage, NetDesc.TOPIC); if (Session.isLoggedIn()) { String favtext = pRes.getElementsByClass("user").first().text().toLowerCase(Locale.US); if (favtext.contains("track topic")) { addFavIcon.setVisible(true); fMode = FavMode.ON_TOPIC; } else if (favtext.contains("stop tracking")) { remFavIcon.setVisible(true); fMode = FavMode.ON_TOPIC; } updatePostingRights(pRes, true); } String goToThisPost = null; if (goToUrlDefinedPost) { String url = res.url().toString(); goToThisPost = url.substring(url.indexOf('#') + 1); } Elements rows = pRes.select("table.board").first().getElementsByTag("tr"); int rowCount = rows.size(); int msgIndex = 0; Set<String> hlUsers = hlDB.getHighlightedUsers().keySet(); for (int x = 0; x < rowCount; x++) { Element row = rows.get(x); String user = null; String postNum = null; String mID = null; String userTitles = EMPTY_STRING; String postTimeText = EMPTY_STRING; String postTime = EMPTY_STRING; Element msgBody = null; if (row.hasClass("left")) { // message poster display set to left of message Elements authorData = row.getElementsByClass("author_data"); user = row.getElementsByTag("b").first().text(); postNum = row.getElementsByTag("a").first().attr("name"); for (int i = 1; i < authorData.size(); i++) { Element e = authorData.get(i); String t = e.text(); if (t.startsWith("(")) userTitles += " " + t; else if (e.hasClass("tag")) userTitles += " (tagged as " + t + ")"; else if (t.startsWith("Posted")) postTime = t; else if (t.equals("message detail")) mID = parseMessageID(e.child(0).attr("href")); } msgBody = row.child(1).child(0); } else { // message poster display set to above message List<TextNode> textNodes = row.child(0).child(0).textNodes(); Elements elements = row.child(0).child(0).children(); int textNodesSize = textNodes.size(); for (int y = 0; y < textNodesSize; y++) { String text = textNodes.get(y).text(); if (text.startsWith("Posted")) postTimeText = text; else if (text.contains("(")) { userTitles += " " + text.substring(text.indexOf('('), text.lastIndexOf(')') + 1); } } user = elements.get(0).text(); int anchorCount = row.getElementsByTag("a").size(); postNum = row.getElementsByTag("a").get((anchorCount > 1 ? 1 : 0)).attr("name"); int elementsSize = elements.size(); for (int y = 0; y < elementsSize; y++) { Element e = elements.get(y); if (e.hasClass("tag")) userTitles += " (tagged as " + e.text() + ")"; else if (e.text().equals("message detail")) mID = parseMessageID(e.attr("href")); } //Posted 11/15/2012 11:20:27&nbsp;AM | (edited) [if archived] if (postTimeText.contains("(edited)")) userTitles += " (edited)"; int endPoint = postTimeText.indexOf('|') - 1; if (endPoint < 0) endPoint = postTimeText.length(); postTime = postTimeText.substring(0, endPoint); x++; msgBody = rows.get(x).child(0).child(0); } int hlColor = 0; if (hlUsers.contains(user.toLowerCase(Locale.US))) { HighlightedUser hUser = hlDB .getHighlightedUsers().get( user.toLowerCase(Locale.US)); hlColor = hUser.getColor(); userTitles += " (" + hUser.getLabel() + ")"; } if (goToUrlDefinedPost) { if (postNum.equals(goToThisPost)) goToThisIndex = msgIndex; } wtl("creating messagerowdata object"); adapterRows.add(new MessageRowData(user, userTitles, postNum, postTime, msgBody, boardID, topicID, mID, hlColor)); msgIndex++; } break; case MESSAGE_DETAIL: updateHeaderNoJumper("Message Detail", NetDesc.MESSAGE_DETAIL); boardID = parseBoardID(resUrl); topicID = parseTopicID(resUrl); Elements msgDRows = pRes.getElementsByTag("tr"); String user = msgDRows.first().child(0).child(0).text(); adapterRows.add(new HeaderRowData("Current Version")); Element currRow, body; MessageRowData msg; String postTime; String mID = parseMessageID(resUrl); for (int x = 0; x < msgDRows.size(); x++) { if (x == 1) adapterRows.add(new HeaderRowData("Previous Version(s)")); else { currRow = msgDRows.get(x); if (currRow.child(0).textNodes().size() > 1) postTime = currRow.child(0).textNodes().get(1).text(); else postTime = currRow.child(0).textNodes().get(0).text(); body = currRow.child(1); msg = new MessageRowData(user, null, null, postTime, body, boardID, topicID, mID, 0); msg.disableTopClick(); adapterRows.add(msg); } } break; case USER_DETAIL: wtl("starting user detail processing"); tbody = pRes.select("table.board").first().getElementsByTag("tbody").first(); Log.d("udtb", tbody.outerHtml()); String name = null; String ID = null; String level = null; String creation = null; String lVisit = null; String sig = null; String karma = null; String AMP = null; for (Element row : tbody.children()) { String label = row.child(0).text().toLowerCase(Locale.US); wtl("user detail row label: " + label); if (label.equals("user name")) name = row.child(1).text(); else if (label.equals("user id")) ID = row.child(1).text(); else if (label.equals("board user level")) { level = row.child(1).html(); wtl("set level: " + level); } else if (label.equals("account created")) creation = row.child(1).text(); else if (label.equals("last visit")) lVisit = row.child(1).text(); else if (label.equals("signature")) sig = row.child(1).html(); else if (label.equals("karma")) karma = row.child(1).text(); else if (label.equals("active messages posted")) AMP = row.child(1).text(); } updateHeaderNoJumper(name + "'s Details", NetDesc.USER_DETAIL); adapterRows.add(new UserDetailRowData(name, ID, level, creation, lVisit, sig, karma, AMP)); break; case GAME_SEARCH: wtl("GRAIO hNR determined this is a game search response"); String url = resUrl; wtl("game search url: " + url); String searchQuery = url.substring(url.indexOf("game=") + 5); int i = searchQuery.indexOf("&"); if (i != -1) searchQuery = searchQuery.replace(searchQuery.substring(i), EMPTY_STRING); int pageIndex = url.indexOf("page="); if (pageIndex != -1) { currPage = url.substring(pageIndex + 5); i = currPage.indexOf("&"); if (i != -1) currPage = currPage.replace(currPage.substring(i), EMPTY_STRING); } else { currPage = "0"; } int currPageNum = Integer.parseInt(currPage); Element nextPageElem = null; if (!pRes.getElementsContainingOwnText("Next Page").isEmpty()) nextPageElem = pRes.getElementsContainingOwnText("Next Page").first(); pageCount = "???"; if (nextPageElem != null) { nextPage = "/search/index.html?game=" + searchQuery + "&page=" + (currPageNum + 1); } if (currPageNum > 0) { prevPage = "/search/index.html?game=" + searchQuery + "&page=" + (currPageNum - 1); firstPage = "/search/index.html?game=" + searchQuery + "&page=0"; } headerTitle = "Searching games: " + URLDecoder.decode(searchQuery) + EMPTY_STRING; updateHeader(headerTitle, firstPage, prevPage, Integer.toString(currPageNum + 1), pageCount, nextPage, lastPage, NetDesc.GAME_SEARCH); searchIcon.setVisible(true); Elements gameSearchTables = pRes.select("table.results"); int tCount = gameSearchTables.size(); int tCounter = 0; if (!gameSearchTables.isEmpty()) { for (Element table : gameSearchTables) { tCounter++; if (tCounter < tCount) adapterRows.add(new HeaderRowData("Best Matches")); else adapterRows.add(new HeaderRowData("Good Matches")); String prevPlatform = EMPTY_STRING; wtl("board row parsing start"); for (Element row : table.getElementsByTag("tr")) { Elements cells = row.getElementsByTag("td"); // cells = [platform] [title] [faqs] [codes] [saves] [revs] [mygames] [q&a] [pics] [vids] [board] String platform = cells.get(0).text(); String bName = cells.get(1).text(); - String bUrl = cells.get(10).child(0).attr("href"); + String bUrl = cells.get(9).child(0).attr("href"); if (platform.codePointAt(0) == ('\u00A0')) { platform = prevPlatform; } else { prevPlatform = platform; } adapterRows.add(new GameSearchRowData(bName, platform, bUrl)); } wtl("board row parsing end"); } } else { adapterRows.add(new HeaderRowData("No results.")); } wtl("game search response block finished"); break; default: wtl("GRAIO hNR determined response type is unhandled"); title.setText("Page unhandled - " + resUrl); break; } try { ((ViewGroup) web.getParent()).removeView(web); } catch (Exception e1) {} adapterRows.add(new AdRowData(web)); contentList.post(loadAds); Element pmInboxLink = pRes.select("div.masthead_user").first().select("a[href=/pm/]").first(); if (pmInboxLink != null) { String text = pmInboxLink.text(); if (text.contains("(")) { int count = Integer.parseInt(text.substring(text.indexOf('(') + 1, text.indexOf(')'))); int prevCount = settings.getInt("unreadPMCount", 0); if (count > prevCount) { settings.edit().putInt("unreadPMCount", count).apply(); if (isDefaultAcc) settings.edit().putInt("notifsUnreadPMCount", count).apply(); if (count > 1) Crouton.showText(this, "You have " + count + " unread PMs", croutonStyle, ptrLayout); else Crouton.showText(this, "You have 1 unread PM", croutonStyle, ptrLayout); } } } Element trackedLink = pRes.select("div.masthead_user").first().select("a[href=/boards/tracked]").first(); if (trackedLink != null) { String text = trackedLink.text(); if (text.contains("(")) { int count = Integer.parseInt(text.substring(text.indexOf('(') + 1, text.indexOf(')'))); int prevCount = settings.getInt("unreadTTCount", 0); if (count > prevCount) { settings.edit().putInt("unreadTTCount", count).apply(); if (isDefaultAcc) settings.edit().putInt("notifsUnreadTTCount", count).apply(); if (count > 1) Crouton.showText(this, "You have " + count + " unread tracked topics", croutonStyle, ptrLayout); else Crouton.showText(this, "You have 1 unread tracked topic", croutonStyle, ptrLayout); } } } ptrLayout.setEnabled(settings.getBoolean("enablePTR", false)); } else { wtl("res is null"); adapterRows.add(new HeaderRowData("You broke it. Somehow processContent was called with a null response.")); } } catch (Exception e) { e.printStackTrace(); tryCaught(res.url().toString(), desc.toString(), ExceptionUtils.getStackTrace(e), res.body()); if (session.canGoBack()) session.goBack(false); } catch (StackOverflowError e) { e.printStackTrace(); tryCaught(res.url().toString(), desc.toString(), ExceptionUtils.getStackTrace(e), res.body()); if (session.canGoBack()) session.goBack(false); } if (!adapterSet) { contentList.setAdapter(viewAdapter); adapterSet = true; } else viewAdapter.notifyDataSetChanged(); if (consumeGoToUrlDefinedPost() && !Session.applySavedScroll) { contentList.post(new Runnable() { @Override public void run() { contentList.setSelection(goToThisIndex); } }); } else if (Session.applySavedScroll) { contentList.post(new Runnable() { @Override public void run() { contentList.setSelectionFromTop(Session.savedScrollVal[0], Session.savedScrollVal[1]); Session.applySavedScroll = false; } }); } else { contentList.post(new Runnable() { @Override public void run() { contentList.setSelectionAfterHeaderView(); } }); } if (ptrLayout.isRefreshing()) ptrLayout.setRefreshComplete(); wtl("GRAIO hNR finishing"); } /*********************************** * END HNR * *********************************/ private void processBoards(Document pRes, boolean includeBoardCategories) { Elements homeTables = pRes.select("table.board"); boolean skippedFirst = false; for (Element row : homeTables.first().getElementsByTag("tr")) { if (skippedFirst) { if (row.hasClass("head")) { adapterRows.add(new HeaderRowData(row.text())); } else { // [title + link] [topics] [msgs] [last post] Elements cells = row.children(); Element titleCell = cells.get(0); String lvlReq = EMPTY_STRING; String title = EMPTY_STRING; if (!titleCell.textNodes().isEmpty()) lvlReq = titleCell.textNodes().get(0).toString(); title = titleCell.child(0).text() + lvlReq; String boardDesc = null; if (titleCell.children().size() > 2) boardDesc = titleCell.child(2).text(); String link = titleCell.children().first().attr("href"); if (link.isEmpty()) link = null; String tCount = null; String mCount = null; String lPost = null; BoardType bvt; if (cells.size() > 3) { tCount = cells.get(1).text(); mCount = cells.get(2).text(); lPost = cells.get(3).text(); bvt = BoardType.NORMAL; } else bvt = BoardType.SPLIT; adapterRows.add(new BoardRowData(title, boardDesc, lPost, tCount, mCount, link, bvt)); } } else { skippedFirst = true; } } if (includeBoardCategories) { int rowX = 0; for (Element row : homeTables.get(1).getElementsByTag("tr")) { rowX++; if (rowX > 2) { Element cell = row.child(0); String title = cell.child(0).text(); String link = cell.child(0).attr("href"); String boardDesc = cell.child(2).text(); adapterRows.add(new BoardRowData(title, boardDesc, null, null, null, link, BoardType.LIST)); } else { if (rowX == 1) { adapterRows.add(new HeaderRowData("Message Board Categories")); } } } } } private void updatePostingRights(Document pRes, boolean onTopic) { if (onTopic) { if (pRes.getElementsByClass("user").first().text().contains("Post New Message")) { postIcon.setVisible(true); pMode = PostMode.ON_TOPIC; } } else { if (pRes.getElementsByClass("user").first().text().contains("New Topic")) { postIcon.setVisible(true); pMode = PostMode.ON_BOARD; } } } public void postExecuteCleanup(NetDesc desc) { wtl("GRAIO dPostEC --NEL, desc: " + (desc == null ? "null" : desc.name())); if (needToSetNavList) { setNavList(Session.isLoggedIn()); needToSetNavList = false; } ptrLayout.setRefreshing(false); if (refreshIcon != null) refreshIcon.setVisible(true); if (desc == NetDesc.BOARD || desc == NetDesc.TOPIC) postCleanup(); if (isRoR) isRoR = false; System.gc(); } private boolean goToUrlDefinedPost = false; private int goToThisIndex = 0; public void enableGoToUrlDefinedPost() {goToUrlDefinedPost = true;} private boolean consumeGoToUrlDefinedPost() { boolean temp = goToUrlDefinedPost; goToUrlDefinedPost = false; return temp; } private void updateHeader(String titleIn, String firstPageIn, String prevPageIn, String currPage, String pageCount, String nextPageIn, String lastPageIn, NetDesc desc) { title.setText(titleIn); if (currPage.equals("-1")) { pageJumperWrapper.setVisibility(View.GONE); } else { pageJumperWrapper.setVisibility(View.VISIBLE); pageJumperDesc = desc; pageLabel.setText(currPage + " / " + pageCount); if (firstPageIn != null) { firstPageUrl = firstPageIn; firstPage.setEnabled(true); } else { firstPage.setEnabled(false); } if (prevPageIn != null) { prevPageUrl = prevPageIn; prevPage.setEnabled(true); } else { prevPage.setEnabled(false); } if (nextPageIn != null) { nextPageUrl = nextPageIn; nextPage.setEnabled(true); } else { nextPage.setEnabled(false); } if (lastPageIn != null) { lastPageUrl = lastPageIn; lastPage.setEnabled(true); } else { lastPage.setEnabled(false); } } } private void updateHeaderNoJumper(String title, NetDesc desc) { updateHeader(title, null, null, "-1", "-1", null, null, desc); } private MessageRowView clickedMsg; private String quoteSelection; public void messageMenuClicked(MessageRowView msg) { clickedMsg = msg; quoteSelection = clickedMsg.getSelection(); showDialog(MESSAGE_ACTION_DIALOG); } private void editPostSetup(String msg, String msgID) { postBody.setText(msg); messageIDForEditing = msgID; postSetup(true); } private void quoteSetup(String user, String msg) { wtl("quoteSetup fired"); String quotedMsg = "<cite>" + user + " posted...</cite>\n" + "<quote>" + msg + "</quote>\n\n"; int start = Math.max(postBody.getSelectionStart(), 0); int end = Math.max(postBody.getSelectionEnd(), 0); postBody.getText().replace(Math.min(start, end), Math.max(start, end), quotedMsg); if (postWrapper.getVisibility() != View.VISIBLE) postSetup(true); else postBody.setSelection(Math.min(start, end) + quotedMsg.length()); wtl("quoteSetup finishing"); } private void postSetup(boolean postingOnTopic) { ((ScrollView) findViewById(R.id.aioHTMLScroller)).scrollTo(0, 0); pageJumperWrapper.setVisibility(View.GONE); postButton.setEnabled(true); cancelButton.setEnabled(true); if (postingOnTopic) { titleWrapper.setVisibility(View.GONE); postBody.requestFocus(); postBody.setSelection(postBody.getText().length()); } else { titleWrapper.setVisibility(View.VISIBLE); if (Session.userHasAdvancedPosting()) { pollButton.setEnabled(true); pollButton.setVisibility(View.VISIBLE); pollSep.setVisibility(View.VISIBLE); } postTitle.requestFocus(); } postWrapper.setVisibility(View.VISIBLE); postPostUrl = session.getLastPath(); if (postPostUrl.contains("#")) postPostUrl = postPostUrl.substring(0, postPostUrl.indexOf('#')); } public void postCancel(View view) { wtl("postCancel fired --NEL"); if (settings.getBoolean("confirmPostCancel", false)) { AlertDialog.Builder b = new AlertDialog.Builder(this); b.setMessage("Cancel this post?"); b.setPositiveButton("Yes", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { postCleanup(); } }); b.setNegativeButton("No", null); b.create().show(); } else postCleanup(); } public void postPollOptions(View view) { showDialog(POLL_OPTIONS_DIALOG); } public void postDo(View view) { wtl("postDo fired"); if (settings.getBoolean("confirmPostSubmit", false)) { AlertDialog.Builder b = new AlertDialog.Builder(this); b.setMessage("Submit this post?"); b.setPositiveButton("Yes", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { postSubmit(); } }); b.setNegativeButton("No", null); b.create().show(); } else postSubmit(); } private void postSubmit() { if (titleWrapper.getVisibility() == View.VISIBLE) { wtl("posting on a board"); // posting on a board String path = Session.ROOT + "/boards/post.php?board=" + boardID; int i = path.indexOf('-'); path = path.substring(0, i); wtl("post path: " + path); savedPostBody = postBody.getText().toString(); wtl("saved post body: " + savedPostBody); savedPostTitle = postTitle.getText().toString(); wtl("saved post title: " + savedPostTitle); wtl("sending topic"); postButton.setEnabled(false); pollButton.setEnabled(false); cancelButton.setEnabled(false); if (pollUse) { path += "&poll=1"; session.get(NetDesc.POSTTPC_S1, path, null); } else if (Session.userHasAdvancedPosting()) session.get(NetDesc.QPOSTTPC_S1, path, null); else session.get(NetDesc.POSTTPC_S1, path, null); } else { // posting on a topic wtl("posting on a topic"); String path = Session.ROOT + "/boards/post.php?board=" + boardID + "&topic=" + topicID; if (messageIDForEditing != null) path += "&message=" + messageIDForEditing; wtl("post path: " + path); savedPostBody = postBody.getText().toString(); wtl("saved post body: " + savedPostBody); wtl("sending post"); postButton.setEnabled(false); cancelButton.setEnabled(false); if (messageIDForEditing != null) session.get(NetDesc.QEDIT_MSG, path, null); else if (Session.userHasAdvancedPosting()) session.get(NetDesc.QPOSTMSG_S1, path, null); else session.get(NetDesc.POSTMSG_S1, path, null); } } private String reportCode; public String getReportCode() {return reportCode;} /** creates dialogs */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch (id) { case SEND_PM_DIALOG: dialog = createSendPMDialog(); break; case MESSAGE_ACTION_DIALOG: dialog = createMessageActionDialog(); break; case REPORT_MESSAGE_DIALOG: dialog = createReportMessageDialog(); break; case POLL_OPTIONS_DIALOG: dialog = createPollOptionsDialog(); break; case CHANGE_LOGGED_IN_DIALOG: dialog = createChangeLoggedInDialog(); break; } return dialog; } private Dialog createPollOptionsDialog() { AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle("Poll Options"); LayoutInflater inflater = getLayoutInflater(); final View v = inflater.inflate(R.layout.polloptions, null); b.setView(v); b.setCancelable(false); final EditText[] options = new EditText[10]; final CheckBox poUse = (CheckBox) v.findViewById(R.id.poUse); final EditText poTitle = (EditText) v.findViewById(R.id.poTitle); options[0] = (EditText) v.findViewById(R.id.po1); options[1] = (EditText) v.findViewById(R.id.po2); options[2] = (EditText) v.findViewById(R.id.po3); options[3] = (EditText) v.findViewById(R.id.po4); options[4] = (EditText) v.findViewById(R.id.po5); options[5] = (EditText) v.findViewById(R.id.po6); options[6] = (EditText) v.findViewById(R.id.po7); options[7] = (EditText) v.findViewById(R.id.po8); options[8] = (EditText) v.findViewById(R.id.po9); options[9] = (EditText) v.findViewById(R.id.po10); final Spinner minLevel = (Spinner) v.findViewById(R.id.poMinLevel); poUse.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { poTitle.setEnabled(isChecked); for (int x = 0; x < 10; x++) options[x].setEnabled(isChecked); } }); for (int x = 0; x < 10; x++) options[x].setText(pollOptions[x]); minLevel.setSelection(pollMinLevel); poTitle.setText(pollTitle); poUse.setChecked(pollUse); b.setPositiveButton("Save", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { pollUse = poUse.isChecked(); pollTitle = poTitle.getText().toString(); pollMinLevel = minLevel.getSelectedItemPosition(); for (int x = 0; x < 10; x++) pollOptions[x] = (options[x].getText().toString()); } }); b.setNegativeButton("Cancel", null); b.setNeutralButton("Clear", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { clearPoll(); } }); Dialog dialog = b.create(); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialog) { removeDialog(POLL_OPTIONS_DIALOG); } }); return dialog; } private void clearPoll() { pollUse = false; pollTitle = EMPTY_STRING; for (int x = 0; x < 10; x++) pollOptions[x] = EMPTY_STRING; pollMinLevel = -1; } private Dialog createReportMessageDialog() { AlertDialog.Builder reportMsgBuilder = new AlertDialog.Builder(this); reportMsgBuilder.setTitle("Report Message"); final String[] reportOptions = getResources().getStringArray(R.array.msgReportReasons); reportMsgBuilder.setItems(reportOptions, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { reportCode = getResources().getStringArray(R.array.msgReportCodes)[which]; session.get(NetDesc.MARKMSG_S1, clickedMsg.getMessageDetailLink(), null); } }); reportMsgBuilder.setNegativeButton("Cancel", null); Dialog dialog = reportMsgBuilder.create(); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialog) { removeDialog(REPORT_MESSAGE_DIALOG); } }); return dialog; } private Dialog createMessageActionDialog() { AlertDialog.Builder msgActionBuilder = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); final View v = inflater.inflate(R.layout.msgaction, null); msgActionBuilder.setView(v); msgActionBuilder.setTitle("Message Actions"); ArrayList<String> listBuilder = new ArrayList<String>(); if (clickedMsg.isEdited() && clickedMsg.getMessageID() != null) listBuilder.add("View Previous Version(s)"); if (Session.isLoggedIn()) { if (postIcon.isVisible()) listBuilder.add("Quote"); if (Session.getUser().trim().toLowerCase(Locale.US).equals(clickedMsg.getUser().toLowerCase(Locale.US))) { if (Session.userCanEditMsgs() && clickedMsg.isEditable()) listBuilder.add("Edit"); if (Session.userCanDeleteClose() && clickedMsg.getMessageID() != null) listBuilder.add("Delete"); } else if (Session.userCanMarkMsgs()) listBuilder.add("Report"); } listBuilder.add("Highlight User"); listBuilder.add("User Details"); ListView lv = (ListView) v.findViewById(R.id.maList); final LinearLayout wrapper = (LinearLayout) v.findViewById(R.id.maWrapper); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); adapter.addAll(listBuilder); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String selected = (String) parent.getItemAtPosition(position); if (selected.equals("View Previous Version(s)")) { session.get(NetDesc.MESSAGE_DETAIL, clickedMsg.getMessageDetailLink(), null); } else if (selected.equals("Quote")) { String msg = (quoteSelection != null ? quoteSelection : clickedMsg.getMessageForQuoting()); quoteSetup(clickedMsg.getUser(), msg); } else if (selected.equals("Edit")) { editPostSetup(clickedMsg.getMessageForEditing(), clickedMsg.getMessageID()); } else if (selected.equals("Delete")) { session.get(NetDesc.DLTMSG_S1, clickedMsg.getMessageDetailLink(), null); } else if (selected.equals("Report")) { showDialog(REPORT_MESSAGE_DIALOG); } else if (selected.equals("Highlight User")) { HighlightedUser user = hlDB.getHighlightedUsers().get(clickedMsg.getUser().toLowerCase(Locale.US)); HighlightListDBHelper.showHighlightUserDialog(AllInOneV2.this, user, clickedMsg.getUser(), null); } else if (selected.equals("User Details")) { session.get(NetDesc.USER_DETAIL, clickedMsg.getUserDetailLink(), null); } else { Crouton.showText(AllInOneV2.this, "not recognized: " + selected, croutonStyle, ptrLayout); } dismissDialog(MESSAGE_ACTION_DIALOG); } }); msgActionBuilder.setNegativeButton("Cancel", null); Dialog dialog = msgActionBuilder.create(); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialog) { removeDialog(MESSAGE_ACTION_DIALOG); } }); dialog.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialog) { if (quoteSelection != null) Crouton.showText(AllInOneV2.this, "Selected text prepped for quoting.", croutonStyle, wrapper); } }); return dialog; } private LinearLayout pmSending; private Dialog createSendPMDialog() { AlertDialog.Builder b = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); final View v = inflater.inflate(R.layout.sendpm, null); b.setView(v); b.setTitle("Send Private Message"); b.setCancelable(false); final EditText to = (EditText) v.findViewById(R.id.spTo); final EditText subject = (EditText) v.findViewById(R.id.spSubject); final EditText message = (EditText) v.findViewById(R.id.spMessage); pmSending = (LinearLayout) v.findViewById(R.id.spFootWrapper); to.setText(savedTo); subject.setText(savedSubject); message.setText(savedMessage); b.setPositiveButton("Send", null); b.setNegativeButton("Cancel", null); final AlertDialog d = b.create(); d.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialog) { d.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String toContent = to.getText().toString(); String subjectContent = subject.getText().toString(); String messageContent = message.getText().toString(); if (toContent.length() > 0) { if (subjectContent.length() > 0) { if (messageContent.length() > 0) { savedTo = toContent; savedSubject = subjectContent; savedMessage = messageContent; pmSending.setVisibility(View.VISIBLE); session.get(NetDesc.SEND_PM_S1, "/pm/new", null); } else Crouton.showText(AllInOneV2.this, "The message can't be empty.", croutonStyle, (ViewGroup) to.getParent()); } else Crouton.showText(AllInOneV2.this, "The subject can't be empty.", croutonStyle, (ViewGroup) to.getParent()); } else Crouton.showText(AllInOneV2.this, "The recepient can't be empty.", croutonStyle, (ViewGroup) to.getParent()); } }); } }); d.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialog) { pmSending = null; removeDialog(SEND_PM_DIALOG); } }); return d; } private Dialog createChangeLoggedInDialog() { AlertDialog.Builder accountChanger = new AlertDialog.Builder(this); String[] keys = accounts.getKeys(); final String[] usernames = new String[keys.length + 1]; usernames[0] = "Log Out"; for (int i = 1; i < usernames.length; i++) usernames[i] = keys[i - 1].toString(); final String currUser = Session.getUser(); int selected = 0; for (int x = 1; x < usernames.length; x++) { if (usernames[x].equals(currUser)) selected = x; } accountChanger.setTitle("Pick an Account"); accountChanger.setSingleChoiceItems(usernames, selected, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0 && currUser != null) session = new Session(AllInOneV2.this); else { String selUser = usernames[item].toString(); if (!selUser.equals(currUser)) if (session.hasNetworkConnection()) { session = new Session(AllInOneV2.this, selUser, accounts.getString(selUser), session.getLastPath(), session.getLastDesc()); } else noNetworkConnection(); } dismissDialog(CHANGE_LOGGED_IN_DIALOG); } }); accountChanger.setNegativeButton("Cancel", null); accountChanger.setPositiveButton("Manage Accounts", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(AllInOneV2.this, SettingsAccount.class)); } }); final AlertDialog d = accountChanger.create(); d.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialog) { Button posButton = d.getButton(DialogInterface.BUTTON_POSITIVE); Button negButton = d.getButton(DialogInterface.BUTTON_NEGATIVE); LayoutParams posParams = (LayoutParams) posButton.getLayoutParams(); posParams.weight = 1; posParams.width = LayoutParams.MATCH_PARENT; LayoutParams negParams = (LayoutParams) negButton.getLayoutParams(); negParams.weight = 1; negParams.width = LayoutParams.MATCH_PARENT; posButton.setLayoutParams(posParams); negButton.setLayoutParams(negParams); } }); d.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialog) { removeDialog(CHANGE_LOGGED_IN_DIALOG); } }); return d; } public String savedTo, savedSubject, savedMessage; public void pmSetup(String toIn, String subjectIn, String messageIn) { if (toIn != null && !toIn.equals("null")) savedTo = toIn; else savedTo = EMPTY_STRING; if (subjectIn != null && !subjectIn.equals("null")) savedSubject = subjectIn; else savedSubject = EMPTY_STRING; if (messageIn != null && !messageIn.equals("null")) savedMessage = messageIn; else savedMessage = EMPTY_STRING; savedTo = URLDecoder.decode(savedTo); savedSubject = URLDecoder.decode(savedSubject); savedMessage = URLDecoder.decode(savedMessage); showDialog(SEND_PM_DIALOG); } public void pmCleanup(boolean wasSuccessful, String error) { if (wasSuccessful) { Crouton.showText(this, "PM sent.", croutonStyle, ptrLayout); ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)). hideSoftInputFromWindow(pmSending.getWindowToken(), 0); dismissDialog(SEND_PM_DIALOG); } else { Crouton.showText(this, error, croutonStyle, (ViewGroup) pmSending.getParent()); pmSending.setVisibility(View.GONE); } } public void refreshClicked(View view) { wtl("refreshClicked fired --NEL"); if (view != null) view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); if (session.getLastPath() == null) { if (Session.isLoggedIn()) { wtl("starting new session from refreshClicked, logged in"); session = new Session(this, Session.getUser(), accounts.getString(Session.getUser())); } else { wtl("starting new session from refreshClicked, no login"); session = new Session(this); } } else session.refresh(); } public String getSig() { String sig = EMPTY_STRING; if (session != null) { if (Session.isLoggedIn()) sig = settings.getString("customSig" + Session.getUser(), EMPTY_STRING); } if (sig.length() == 0) sig = settings.getString("customSig", EMPTY_STRING); if (sig.length() == 0) sig = defaultSig; try { sig = sig.replace("*grver*", this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName); } catch (NameNotFoundException e) { sig = sig.replace("*grver*", EMPTY_STRING); e.printStackTrace(); } return sig; } private static long lastNano = 0; public void wtl(String msg) { if (!isReleaseBuild) { long currNano = System.nanoTime(); msg = msg.replaceAll("\\\\n", "(nl)"); long elapsed; if (lastNano == 0) elapsed = 0; else elapsed = currNano - lastNano; elapsed = elapsed / 1000000; if (elapsed > 100) Log.w("logger", "time since previous log was over 100 milliseconds"); lastNano = System.nanoTime(); msg = elapsed + "// " + msg; Log.d("logger", msg); } } private static final String ON_DEMAND_BUG_REPORT = "On Demand"; public void onDemandBugReport() { tryCaught(session.getLastPath() + "\nLast Attempted:\n" + session.getLastAttemptedPath(), session.getLastDesc() + "\nLast Attempted:\n" + session.getLastAttemptedDesc(), ON_DEMAND_BUG_REPORT, (session.getLastRes() != null ? session.getLastRes().body() : "res is null")); } public void tryCaught(String url, String desc, String stacktrace, String source) { String ver; try { ver = getPackageManager().getPackageInfo(getPackageName(), 0).versionName; } catch (NameNotFoundException e) { ver = "version not set"; } final String emailMsg = "\n\nVersion:\n" + ver + "\n\nURL:\n" + url + "\n\nDesc:\n" + desc + "\n\nStack trace:\n" + stacktrace + "\n\nPage source:\n" + source; AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle("Send Bug Report"); if (stacktrace.equals(ON_DEMAND_BUG_REPORT)) b.setMessage("NOTICE! Please include a comment on why you are sending this bug report in the text box " + "below! On demand bug reports do not include any crash information, so we can't determine the " + "bug without your input! Thanks!"); else b.setMessage("You've run into a bug! Would you like to email debug information to the developer? The email will contain " + "details on the crash itself, the url the server responded with, and the source for the page. " + "If so, please include a brief comment below on what you were trying to do."); final EditText input = new EditText(this); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); input.setLayoutParams(lp); input.setHint("Enter comment here..."); b.setView(input); b.setNegativeButton("Cancel", null); b.setPositiveButton("Email to dev", null); final AlertDialog d = b.create(); d.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialog) { d.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!input.getText().toString().isEmpty()) { Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", "[email protected]", null)); i.putExtra(Intent.EXTRA_SUBJECT, "GameRaven Error Report"); i.putExtra(Intent.EXTRA_TEXT , "Comment:\n" + input.getText() + emailMsg); try { startActivity(Intent.createChooser(i, "Send mail...")); } catch (android.content.ActivityNotFoundException ex) { Crouton.showText(AllInOneV2.this, "There are no email clients installed.", croutonStyle, ptrLayout); } d.dismiss(); } else { input.requestFocus(); Crouton.showText(AllInOneV2.this, "Please include a brief comment in the provided text box.", croutonStyle, (ViewGroup) input.getParent()); } } }); } }); d.show(); } private String parseBoardID(String url) { wtl("parseBoardID fired"); // board example: http://www.gamefaqs.com/boards/400-current-events String boardUrl = url.substring(Session.ROOT.length() + 8); int i = boardUrl.indexOf('/'); if (i != -1) { String replacer = boardUrl.substring(i); boardUrl = boardUrl.replace(replacer, EMPTY_STRING); } i = boardUrl.indexOf('?'); if (i != -1) { String replacer = boardUrl.substring(i); boardUrl = boardUrl.replace(replacer, EMPTY_STRING); } i = boardUrl.indexOf('#'); if (i != -1) { String replacer = boardUrl.substring(i); boardUrl = boardUrl.replace(replacer, EMPTY_STRING); } wtl("boardID: " + boardUrl); return boardUrl; } private String parseTopicID(String url) { wtl("parseTopicID fired"); // topic example: http://www.gamefaqs.com/boards/400-current-events/64300205 String topicUrl = url.substring(url.indexOf('/', Session.ROOT.length() + 8) + 1); int i = topicUrl.indexOf('/'); if (i != -1) { String replacer = topicUrl.substring(i); topicUrl = topicUrl.replace(replacer, EMPTY_STRING); } i = topicUrl.indexOf('?'); if (i != -1) { String replacer = topicUrl.substring(i); topicUrl = topicUrl.replace(replacer, EMPTY_STRING); } i = topicUrl.indexOf('#'); if (i != -1) { String replacer = topicUrl.substring(i); topicUrl = topicUrl.replace(replacer, EMPTY_STRING); } wtl("topicID: " + topicUrl); return topicUrl; } private String parseMessageID(String url) { wtl("parseMessageID fired"); String msgID = url.substring(url.lastIndexOf('/') + 1); wtl("messageIDForEditing: " + msgID); return msgID; } @Override public void onBackPressed() { if (searchIcon.isActionViewExpanded()) { searchIcon.collapseActionView(); } else if (drawer.isMenuVisible()) { drawer.closeMenu(true); } else if (postWrapper.getVisibility() == View.VISIBLE) { postCleanup(); } else { goBack(); } } private void goBack() { if (session.canGoBack()) { wtl("back pressed, history exists, going back"); session.goBack(false); } else { wtl("back pressed, no history, exiting app"); session = null; this.finish(); } } public static String buildAMPLink() { return "/boards/myposts.php?lp=" + settings.getString("ampSortOption", "-1"); } private String autoCensor(String text) { StringBuilder builder = new StringBuilder(text); String textLower = text.toLowerCase(Locale.US); for (String word : bannedList) censorWord(builder, textLower, word.toLowerCase(Locale.US)); return builder.toString(); } private void censorWord(StringBuilder builder, String textLower, String word) { int length = word.length(); String replacement = ""; for (int x = 0; x < length - 1; x++) replacement += '*'; while (textLower.contains(word)) { int start = textLower.indexOf(word); int end = start + length; builder.replace(start + 1, end, replacement); textLower = textLower.replaceFirst(word, replacement + '*'); } } public void htmlButtonClicked(View view) { String open = ((TextView) view).getText().toString(); String close = "</" + open.substring(1); int start = Math.max(postBody.getSelectionStart(), 0); int end = Math.max(postBody.getSelectionEnd(), 0); String insert; if (start != end) insert = open + postBody.getText().subSequence(start, end) + close; else insert = open + close; postBody.getText().replace(Math.min(start, end), Math.max(start, end), insert, 0, insert.length()); } private static final String[] bannedList = { "***hole", "68.13.103", "Arse Hole", "Arse-hole", "Ass hole", "Ass****", "Ass-hole", "Asshole", "�^�", "Bitch", "Bukkake", "Cheat Code Central", "CheatCC", "Clit", "Cunt", "Dave Allison", "David Allison", "Dildo", "Echo J", "Fag", "Format C:", "FreeFlatScreens.com", "FreeIPods.com", "Fuck", "GFNostalgia", "Gook", "Jism", "Jizm", "Jizz", "KingOfChaos", "Lesbo", "LUE2.tk", "Mod Files", "Mod Pics", "ModFiles", "ModPics", "Nigga", "Nigger", "Offiz.bei.t-online.de", "OutPimp", "OutWar.com", "PornStarGuru", "Pussies", "Pussy", "RavenBlack.net", "Shit", "Shiz", "SuprNova", "Tits", "Titties", "Titty", "UrbanDictionary", "Wigga", "Wigger", "YouDontKnowWhoIAm"}; }
true
true
public void processContent(Response res, NetDesc desc, Document pRes, String resUrl) { wtl("GRAIO hNR fired, desc: " + desc.name()); ptrLayout.setEnabled(false); searchIcon.setVisible(false); searchIcon.collapseActionView(); postIcon.setVisible(false); addFavIcon.setVisible(false); remFavIcon.setVisible(false); topicListIcon.setVisible(false); adapterRows.clear(); boolean isDefaultAcc; if (Session.getUser() != null && Session.getUser().equals(settings.getString("defaultAccount", SettingsMain.NO_DEFAULT_ACCOUNT))) isDefaultAcc = true; else isDefaultAcc = false; try { if (res != null) { wtl("res is not null"); wtl("setting board, topic, message id to null"); boardID = null; topicID = null; messageIDForEditing = null; Element tbody; Element pj = null; String headerTitle; String firstPage = null; String prevPage = null; String currPage = "1"; String pageCount = "1"; String nextPage = null; String lastPage = null; String bgcolor; if (usingLightTheme) bgcolor = "#ffffff"; else bgcolor = "#000000"; adBuilder.setLength(0); adBuilder.append("<html>"); adBuilder.append(pRes.head().outerHtml()); adBuilder.append("<body bgcolor=\"" + bgcolor + "\">"); for (Element e : pRes.getElementsByClass("ad")) { adBuilder.append(e.outerHtml()); e.remove(); } for (Element e : pRes.getElementsByTag("script")) { adBuilder.append(e.outerHtml()); } adBuilder.append("</body></html>"); adBaseUrl = res.url().toString(); if (web == null) web = new WebView(this); web.getSettings().setJavaScriptEnabled(AllInOneV2.getSettingsPref().getBoolean("enableJS", true)); switch (desc) { case BOARD_JUMPER: case LOGIN_S2: updateHeaderNoJumper("Board Jumper", NetDesc.BOARD_JUMPER); adapterRows.add(new HeaderRowData("Announcements")); searchIcon.setVisible(true); processBoards(pRes, true); break; case BOARD_LIST: updateHeaderNoJumper(pRes.getElementsByTag("th").get(4).text(), NetDesc.BOARD_LIST); processBoards(pRes, true); break; case PM_INBOX: tbody = pRes.getElementsByTag("tbody").first(); headerTitle = Session.getUser() + "'s PM Inbox"; if (tbody != null) { pj = pRes.select("ul.paginate").first(); if (pj != null) { String pjText = pj.child(0).text(); if (pjText.contains("Previous")) pjText = pj.child(1).text(); //Page 1 of 5 int currPageStart = 5; int ofIndex = pjText.indexOf(" of "); currPage = pjText.substring(currPageStart, ofIndex); int pageCountEnd = pjText.length(); pageCount = pjText.substring(ofIndex + 4, pageCountEnd); int currPageNum = Integer.parseInt(currPage); int pageCountNum = Integer.parseInt(pageCount); if (currPageNum > 1) { firstPage = "/pm/"; prevPage = "/pm/?page=" + (currPageNum - 2); } if (currPageNum != pageCountNum) { nextPage = "/pm/?page=" + currPageNum; lastPage = "/pm/?page=" + (pageCountNum - 1); } } updateHeader(headerTitle, firstPage, prevPage, currPage, pageCount, nextPage, lastPage, NetDesc.PM_INBOX); if (isDefaultAcc) NotifierService.dismissPMNotif(this); for (Element row : tbody.getElementsByTag("tr")) { Elements cells = row.children(); // [icon] [sender] [subject] [time] [check] boolean isOld = true; if (cells.get(0).children().first().hasClass("icon-circle")) isOld = false; String sender = cells.get(1).text(); Element subjectLinkElem = cells.get(2).children().first(); String subject = subjectLinkElem.text(); String link = subjectLinkElem.attr("href"); String time = cells.get(3).text(); adapterRows.add(new PMRowData(subject, sender, time, link, isOld)); } } else { updateHeaderNoJumper(headerTitle, NetDesc.PM_INBOX); adapterRows.add(new HeaderRowData("You have no private messages at this time.")); } postIcon.setVisible(true); pMode = PostMode.NEW_PM; break; case PM_DETAIL: headerTitle = pRes.select("h2.title").first().text(); String pmTitle = headerTitle; if (!pmTitle.startsWith("Re: ")) pmTitle = "Re: " + pmTitle; String pmMessage = pRes.select("div.body").first().outerHtml(); Element foot = pRes.select("div.foot").first(); foot.child(1).remove(); String pmFoot = foot.outerHtml(); //Sent by: P4wn4g3 on 6/1/2013 2:15:55 PM String footText = foot.text(); String sender = footText.substring(9, footText.indexOf(" on ")); updateHeaderNoJumper(pmTitle, NetDesc.PM_DETAIL); adapterRows.add(new PMDetailRowData(sender, pmTitle, pmMessage + pmFoot)); break; case AMP_LIST: wtl("GRAIO hNR determined this is an amp response"); tbody = pRes.getElementsByTag("tbody").first(); headerTitle = Session.getUser() + "'s Active Messages"; if (pRes.select("ul.paginate").size() > 1) { pj = pRes.select("ul.paginate").get(1); if (pj != null && !pj.hasClass("user") && !pj.hasClass("tsort")) { int x = 0; String pjText = pj.child(x).text(); while (pjText.contains("First") || pjText.contains("Previous")) { x++; pjText = pj.child(x).text(); } // Page 2 of 3 int currPageStart = 5; int ofIndex = pjText.indexOf(" of "); currPage = pjText.substring(currPageStart, ofIndex); int pageCountEnd = pjText.length(); pageCount = pjText.substring(ofIndex + 4, pageCountEnd); int currPageNum = Integer.parseInt(currPage); int pageCountNum = Integer.parseInt(pageCount); String amp = buildAMPLink(); if (currPageNum > 1) { firstPage = amp; prevPage = amp + "&page=" + (currPageNum - 2); } if (currPageNum != pageCountNum) { nextPage = amp + "&page=" + currPageNum; lastPage = amp + "&page=" + (pageCountNum - 1); } } } updateHeader(headerTitle, firstPage, prevPage, currPage, pageCount, nextPage, lastPage, NetDesc.AMP_LIST); if (isDefaultAcc) NotifierService.dismissAMPNotif(this); if (!tbody.children().isEmpty()) { if (settings.getBoolean("notifsEnable", false) && isDefaultAcc) { Element lPost = pRes.select("td.lastpost").first(); if (lPost != null) { String lTime = lPost.text(); Date newDate; lTime = lTime.replace("Last:", EMPTY_STRING); if (lTime.contains("AM") || lTime.contains("PM")) newDate = new SimpleDateFormat("MM'/'dd hh':'mmaa", Locale.US).parse(lTime); else newDate = new SimpleDateFormat("MM'/'dd'/'yyyy", Locale.US).parse(lTime); long newTime = newDate.getTime(); long oldTime = settings.getLong("notifsLastPost", 0); if (newTime > oldTime) { wtl("time is newer"); settings.edit().putLong("notifsLastPost", newTime).commit(); } } } for (Element row : tbody.children()) { // [board] [title] [msg] [last post] [your last post] Elements cells = row.children(); String board = cells.get(0).text(); Element titleLinkElem = cells.get(1).child(0); String title = titleLinkElem.text(); String link = titleLinkElem.attr("href"); String mCount = cells.get(2).textNodes().get(0).text().trim(); Element lPostLinkElem = cells.get(3).child(1); String lPost = lPostLinkElem.text(); String lPostLink = lPostLinkElem.attr("href"); String ylpLink = cells.get(4).child(1).attr("href"); adapterRows.add(new AMPRowData(title, board, lPost, mCount, link, lPostLink, ylpLink)); } } else { adapterRows.add(new HeaderRowData("You have no active messages at this time.")); } wtl("amp response block finished"); break; case TRACKED_TOPICS: headerTitle = Session.getUser() + "'s Tracked Topics"; updateHeaderNoJumper(headerTitle, desc); if (isDefaultAcc) NotifierService.dismissTTNotif(this); tbody = pRes.getElementsByTag("tbody").first(); if (tbody != null) { for (Element row : tbody.children()) { // [remove] [title] [board name] [msgs] [last [pst] Elements cells = row.children(); String removeLink = cells.get(0).child(0) .attr("href"); String topicLink = cells.get(1).child(0) .attr("href"); String topicText = cells.get(1).text(); String board = cells.get(2).text(); String msgs = cells.get(3).text(); String lPostLink = cells.get(4).child(0) .attr("href"); String lPostText = cells.get(4).text(); adapterRows.add(new TrackedTopicRowData(board, topicText, lPostText, msgs, topicLink, removeLink, lPostLink)); } } else { adapterRows.add(new HeaderRowData("You have no tracked topics at this time.")); } break; case BOARD: wtl("GRAIO hNR determined this is a board response"); wtl("setting board id"); boardID = parseBoardID(resUrl); boolean isSplitList = false; if (pRes.getElementsByTag("th").first() != null) { if (pRes.getElementsByTag("th").first().text().equals("Board Title")) { wtl("is actually a split board list"); updateHeaderNoJumper(pRes.select("h1.page-title").first().text(), NetDesc.BOARD); processBoards(pRes, false); isSplitList = true; } } if (!isSplitList) { String url = resUrl; String searchQuery = EMPTY_STRING; String searchPJAddition = EMPTY_STRING; if (url.contains("search=")) { wtl("board search url: " + url); searchQuery = url.substring(url.indexOf("search=") + 7); int i = searchQuery.indexOf('&'); if (i != -1) searchQuery.replace(searchQuery.substring(i), EMPTY_STRING); searchPJAddition = "&search=" + searchQuery; searchQuery = URLDecoder.decode(searchQuery); } Element headerElem = pRes.getElementsByClass("page-title").first(); if (headerElem != null) headerTitle = headerElem.text(); else headerTitle = "GFAQs Cache Error, Board Title Not Found"; if (searchQuery.length() > 0) headerTitle += " (search: " + searchQuery + ")"; if (pRes.select("ul.paginate").size() > 1) { pj = pRes.select("ul.paginate").get(1); if (pj != null && !pj.hasClass("user")) { int x = 0; String pjText = pj.child(x).text(); while (pjText.contains("First") || pjText.contains("Previous")) { x++; pjText = pj.child(x).text(); } // Page [dropdown] of 3 // Page 1 of 3 int ofIndex = pjText.indexOf(" of "); int currPageStart = 5; if (pj.getElementsByTag("select").isEmpty()) currPage = pjText.substring(currPageStart, ofIndex); else currPage = pj .select("option[selected=selected]") .first().text(); int pageCountEnd = pjText.length(); pageCount = pjText.substring(ofIndex + 4, pageCountEnd); int currPageNum = Integer.parseInt(currPage); int pageCountNum = Integer.parseInt(pageCount); if (currPageNum > 1) { firstPage = "boards/" + boardID + "?page=0" + searchPJAddition; prevPage = "boards/" + boardID + "?page=" + (currPageNum - 2) + searchPJAddition; } if (currPageNum != pageCountNum) { nextPage = "boards/" + boardID + "?page=" + currPageNum + searchPJAddition; lastPage = "boards/" + boardID + "?page=" + (pageCountNum - 1) + searchPJAddition; } } } updateHeader(headerTitle, firstPage, prevPage, currPage, pageCount, nextPage, lastPage, NetDesc.BOARD); searchIcon.setVisible(true); if (Session.isLoggedIn()) { String favtext = pRes.getElementsByClass("user").first().text().toLowerCase(Locale.US); if (favtext.contains("add to favorites")) { addFavIcon.setVisible(true); fMode = FavMode.ON_BOARD; } else if (favtext.contains("remove favorite")) { remFavIcon.setVisible(true); fMode = FavMode.ON_BOARD; } updatePostingRights(pRes, false); } Element splitList = pRes.select("p:contains(this is a split board)").first(); if (splitList != null) { String splitListLink = splitList.child(0).attr("href"); adapterRows.add(new BoardRowData("This is a Split Board.", "Click here to return to the Split List.", null, null, null, splitListLink, BoardType.SPLIT)); } Element table = pRes.select("table.board").first(); if (table != null) { table.getElementsByTag("col").get(2).remove(); table.getElementsByTag("th").get(2).remove(); table.getElementsByTag("col").get(0).remove(); table.getElementsByTag("th").get(0).remove(); wtl("board row parsing start"); boolean skipFirst = true; Set<String> hlUsers = hlDB.getHighlightedUsers().keySet(); for (Element row : table.getElementsByTag("tr")) { if (!skipFirst) { Elements cells = row.getElementsByTag("td"); // cells = [image] [title] [author] [post count] [last post] String tImg = cells.get(0).child(0).className(); Element titleLinkElem = cells.get(1).child(0); String title = titleLinkElem.text(); String tUrl = titleLinkElem.attr("href"); String tc = cells.get(2).text(); Element lPostLinkElem = cells.get(4).child(0); String lastPost = lPostLinkElem.text(); String lpUrl = lPostLinkElem.attr("href"); String mCount = cells.get(3).text(); TopicType type = TopicType.NORMAL; if (tImg.contains("poll")) type = TopicType.POLL; else if (tImg.contains("sticky")) type = TopicType.PINNED; else if (tImg.contains("closed")) type = TopicType.LOCKED; else if (tImg.contains("archived")) type = TopicType.ARCHIVED; wtl(tImg + ", " + type.name()); ReadStatus status = ReadStatus.UNREAD; if (tImg.endsWith("_read")) status = ReadStatus.READ; else if (tImg.endsWith("_unread")) status = ReadStatus.NEW_POST; int hlColor = 0; if (hlUsers.contains(tc.toLowerCase(Locale.US))) { HighlightedUser hUser = hlDB.getHighlightedUsers().get(tc.toLowerCase(Locale.US)); hlColor = hUser.getColor(); tc += " (" + hUser.getLabel() + ")"; } adapterRows.add(new TopicRowData(title, tc, lastPost, mCount, tUrl, lpUrl, type, status, hlColor)); } else skipFirst = false; } wtl("board row parsing end"); } else { adapterRows.add(new HeaderRowData("There are no topics at this time.")); } } wtl("board response block finished"); break; case TOPIC: boardID = parseBoardID(resUrl); topicID = parseTopicID(resUrl); tlUrl = "boards/" + boardID; wtl(tlUrl); topicListIcon.setVisible(true); Element headerElem = pRes.getElementsByClass("title").first(); if (headerElem != null) headerTitle = headerElem.text(); else headerTitle = "GFAQs Cache Error, Title Not Found"; if (headerTitle.equals("Log In to GameFAQs")) { headerElem = pRes.getElementsByClass("title").get(1); if (headerElem != null) headerTitle = headerElem.text(); } if (pRes.select("ul.paginate").size() > 1) { pj = pRes.select("ul.paginate").get(1); if (pj != null && !pj.hasClass("user")) { int x = 0; String pjText = pj.child(x).text(); while (pjText.contains("First") || pjText.contains("Previous")) { x++; pjText = pj.child(x).text(); } // Page [dropdown] of 3 // Page 1 of 3 int ofIndex = pjText.indexOf(" of "); int currPageStart = 5; if (pj.getElementsByTag("select").isEmpty()) currPage = pjText.substring(currPageStart, ofIndex); else currPage = pj .select("option[selected=selected]") .first().text(); int pageCountEnd = pjText.length(); pageCount = pjText.substring(ofIndex + 4, pageCountEnd); int currPageNum = Integer.parseInt(currPage); int pageCountNum = Integer.parseInt(pageCount); if (currPageNum > 1) { firstPage = "boards/" + boardID + "/" + topicID; prevPage = "boards/" + boardID + "/" + topicID + "?page=" + (currPageNum - 2); } if (currPageNum != pageCountNum) { nextPage = "boards/" + boardID + "/" + topicID + "?page=" + currPageNum; lastPage = "boards/" + boardID + "/" + topicID + "?page=" + (pageCountNum - 1); } } } updateHeader(headerTitle, firstPage, prevPage, currPage, pageCount, nextPage, lastPage, NetDesc.TOPIC); if (Session.isLoggedIn()) { String favtext = pRes.getElementsByClass("user").first().text().toLowerCase(Locale.US); if (favtext.contains("track topic")) { addFavIcon.setVisible(true); fMode = FavMode.ON_TOPIC; } else if (favtext.contains("stop tracking")) { remFavIcon.setVisible(true); fMode = FavMode.ON_TOPIC; } updatePostingRights(pRes, true); } String goToThisPost = null; if (goToUrlDefinedPost) { String url = res.url().toString(); goToThisPost = url.substring(url.indexOf('#') + 1); } Elements rows = pRes.select("table.board").first().getElementsByTag("tr"); int rowCount = rows.size(); int msgIndex = 0; Set<String> hlUsers = hlDB.getHighlightedUsers().keySet(); for (int x = 0; x < rowCount; x++) { Element row = rows.get(x); String user = null; String postNum = null; String mID = null; String userTitles = EMPTY_STRING; String postTimeText = EMPTY_STRING; String postTime = EMPTY_STRING; Element msgBody = null; if (row.hasClass("left")) { // message poster display set to left of message Elements authorData = row.getElementsByClass("author_data"); user = row.getElementsByTag("b").first().text(); postNum = row.getElementsByTag("a").first().attr("name"); for (int i = 1; i < authorData.size(); i++) { Element e = authorData.get(i); String t = e.text(); if (t.startsWith("(")) userTitles += " " + t; else if (e.hasClass("tag")) userTitles += " (tagged as " + t + ")"; else if (t.startsWith("Posted")) postTime = t; else if (t.equals("message detail")) mID = parseMessageID(e.child(0).attr("href")); } msgBody = row.child(1).child(0); } else { // message poster display set to above message List<TextNode> textNodes = row.child(0).child(0).textNodes(); Elements elements = row.child(0).child(0).children(); int textNodesSize = textNodes.size(); for (int y = 0; y < textNodesSize; y++) { String text = textNodes.get(y).text(); if (text.startsWith("Posted")) postTimeText = text; else if (text.contains("(")) { userTitles += " " + text.substring(text.indexOf('('), text.lastIndexOf(')') + 1); } } user = elements.get(0).text(); int anchorCount = row.getElementsByTag("a").size(); postNum = row.getElementsByTag("a").get((anchorCount > 1 ? 1 : 0)).attr("name"); int elementsSize = elements.size(); for (int y = 0; y < elementsSize; y++) { Element e = elements.get(y); if (e.hasClass("tag")) userTitles += " (tagged as " + e.text() + ")"; else if (e.text().equals("message detail")) mID = parseMessageID(e.attr("href")); } //Posted 11/15/2012 11:20:27&nbsp;AM | (edited) [if archived] if (postTimeText.contains("(edited)")) userTitles += " (edited)"; int endPoint = postTimeText.indexOf('|') - 1; if (endPoint < 0) endPoint = postTimeText.length(); postTime = postTimeText.substring(0, endPoint); x++; msgBody = rows.get(x).child(0).child(0); } int hlColor = 0; if (hlUsers.contains(user.toLowerCase(Locale.US))) { HighlightedUser hUser = hlDB .getHighlightedUsers().get( user.toLowerCase(Locale.US)); hlColor = hUser.getColor(); userTitles += " (" + hUser.getLabel() + ")"; } if (goToUrlDefinedPost) { if (postNum.equals(goToThisPost)) goToThisIndex = msgIndex; } wtl("creating messagerowdata object"); adapterRows.add(new MessageRowData(user, userTitles, postNum, postTime, msgBody, boardID, topicID, mID, hlColor)); msgIndex++; } break; case MESSAGE_DETAIL: updateHeaderNoJumper("Message Detail", NetDesc.MESSAGE_DETAIL); boardID = parseBoardID(resUrl); topicID = parseTopicID(resUrl); Elements msgDRows = pRes.getElementsByTag("tr"); String user = msgDRows.first().child(0).child(0).text(); adapterRows.add(new HeaderRowData("Current Version")); Element currRow, body; MessageRowData msg; String postTime; String mID = parseMessageID(resUrl); for (int x = 0; x < msgDRows.size(); x++) { if (x == 1) adapterRows.add(new HeaderRowData("Previous Version(s)")); else { currRow = msgDRows.get(x); if (currRow.child(0).textNodes().size() > 1) postTime = currRow.child(0).textNodes().get(1).text(); else postTime = currRow.child(0).textNodes().get(0).text(); body = currRow.child(1); msg = new MessageRowData(user, null, null, postTime, body, boardID, topicID, mID, 0); msg.disableTopClick(); adapterRows.add(msg); } } break; case USER_DETAIL: wtl("starting user detail processing"); tbody = pRes.select("table.board").first().getElementsByTag("tbody").first(); Log.d("udtb", tbody.outerHtml()); String name = null; String ID = null; String level = null; String creation = null; String lVisit = null; String sig = null; String karma = null; String AMP = null; for (Element row : tbody.children()) { String label = row.child(0).text().toLowerCase(Locale.US); wtl("user detail row label: " + label); if (label.equals("user name")) name = row.child(1).text(); else if (label.equals("user id")) ID = row.child(1).text(); else if (label.equals("board user level")) { level = row.child(1).html(); wtl("set level: " + level); } else if (label.equals("account created")) creation = row.child(1).text(); else if (label.equals("last visit")) lVisit = row.child(1).text(); else if (label.equals("signature")) sig = row.child(1).html(); else if (label.equals("karma")) karma = row.child(1).text(); else if (label.equals("active messages posted")) AMP = row.child(1).text(); } updateHeaderNoJumper(name + "'s Details", NetDesc.USER_DETAIL); adapterRows.add(new UserDetailRowData(name, ID, level, creation, lVisit, sig, karma, AMP)); break; case GAME_SEARCH: wtl("GRAIO hNR determined this is a game search response"); String url = resUrl; wtl("game search url: " + url); String searchQuery = url.substring(url.indexOf("game=") + 5); int i = searchQuery.indexOf("&"); if (i != -1) searchQuery = searchQuery.replace(searchQuery.substring(i), EMPTY_STRING); int pageIndex = url.indexOf("page="); if (pageIndex != -1) { currPage = url.substring(pageIndex + 5); i = currPage.indexOf("&"); if (i != -1) currPage = currPage.replace(currPage.substring(i), EMPTY_STRING); } else { currPage = "0"; } int currPageNum = Integer.parseInt(currPage); Element nextPageElem = null; if (!pRes.getElementsContainingOwnText("Next Page").isEmpty()) nextPageElem = pRes.getElementsContainingOwnText("Next Page").first(); pageCount = "???"; if (nextPageElem != null) { nextPage = "/search/index.html?game=" + searchQuery + "&page=" + (currPageNum + 1); } if (currPageNum > 0) { prevPage = "/search/index.html?game=" + searchQuery + "&page=" + (currPageNum - 1); firstPage = "/search/index.html?game=" + searchQuery + "&page=0"; } headerTitle = "Searching games: " + URLDecoder.decode(searchQuery) + EMPTY_STRING; updateHeader(headerTitle, firstPage, prevPage, Integer.toString(currPageNum + 1), pageCount, nextPage, lastPage, NetDesc.GAME_SEARCH); searchIcon.setVisible(true); Elements gameSearchTables = pRes.select("table.results"); int tCount = gameSearchTables.size(); int tCounter = 0; if (!gameSearchTables.isEmpty()) { for (Element table : gameSearchTables) { tCounter++; if (tCounter < tCount) adapterRows.add(new HeaderRowData("Best Matches")); else adapterRows.add(new HeaderRowData("Good Matches")); String prevPlatform = EMPTY_STRING; wtl("board row parsing start"); for (Element row : table.getElementsByTag("tr")) { Elements cells = row.getElementsByTag("td"); // cells = [platform] [title] [faqs] [codes] [saves] [revs] [mygames] [q&a] [pics] [vids] [board] String platform = cells.get(0).text(); String bName = cells.get(1).text(); String bUrl = cells.get(10).child(0).attr("href"); if (platform.codePointAt(0) == ('\u00A0')) { platform = prevPlatform; } else { prevPlatform = platform; } adapterRows.add(new GameSearchRowData(bName, platform, bUrl)); } wtl("board row parsing end"); } } else { adapterRows.add(new HeaderRowData("No results.")); } wtl("game search response block finished"); break; default: wtl("GRAIO hNR determined response type is unhandled"); title.setText("Page unhandled - " + resUrl); break; } try { ((ViewGroup) web.getParent()).removeView(web); } catch (Exception e1) {} adapterRows.add(new AdRowData(web)); contentList.post(loadAds); Element pmInboxLink = pRes.select("div.masthead_user").first().select("a[href=/pm/]").first(); if (pmInboxLink != null) { String text = pmInboxLink.text(); if (text.contains("(")) { int count = Integer.parseInt(text.substring(text.indexOf('(') + 1, text.indexOf(')'))); int prevCount = settings.getInt("unreadPMCount", 0); if (count > prevCount) { settings.edit().putInt("unreadPMCount", count).apply(); if (isDefaultAcc) settings.edit().putInt("notifsUnreadPMCount", count).apply(); if (count > 1) Crouton.showText(this, "You have " + count + " unread PMs", croutonStyle, ptrLayout); else Crouton.showText(this, "You have 1 unread PM", croutonStyle, ptrLayout); } } } Element trackedLink = pRes.select("div.masthead_user").first().select("a[href=/boards/tracked]").first(); if (trackedLink != null) { String text = trackedLink.text(); if (text.contains("(")) { int count = Integer.parseInt(text.substring(text.indexOf('(') + 1, text.indexOf(')'))); int prevCount = settings.getInt("unreadTTCount", 0); if (count > prevCount) { settings.edit().putInt("unreadTTCount", count).apply(); if (isDefaultAcc) settings.edit().putInt("notifsUnreadTTCount", count).apply(); if (count > 1) Crouton.showText(this, "You have " + count + " unread tracked topics", croutonStyle, ptrLayout); else Crouton.showText(this, "You have 1 unread tracked topic", croutonStyle, ptrLayout); } } } ptrLayout.setEnabled(settings.getBoolean("enablePTR", false)); } else { wtl("res is null"); adapterRows.add(new HeaderRowData("You broke it. Somehow processContent was called with a null response.")); } } catch (Exception e) { e.printStackTrace(); tryCaught(res.url().toString(), desc.toString(), ExceptionUtils.getStackTrace(e), res.body()); if (session.canGoBack()) session.goBack(false); } catch (StackOverflowError e) { e.printStackTrace(); tryCaught(res.url().toString(), desc.toString(), ExceptionUtils.getStackTrace(e), res.body()); if (session.canGoBack()) session.goBack(false); } if (!adapterSet) { contentList.setAdapter(viewAdapter); adapterSet = true; } else viewAdapter.notifyDataSetChanged(); if (consumeGoToUrlDefinedPost() && !Session.applySavedScroll) { contentList.post(new Runnable() { @Override public void run() { contentList.setSelection(goToThisIndex); } }); } else if (Session.applySavedScroll) { contentList.post(new Runnable() { @Override public void run() { contentList.setSelectionFromTop(Session.savedScrollVal[0], Session.savedScrollVal[1]); Session.applySavedScroll = false; } }); } else { contentList.post(new Runnable() { @Override public void run() { contentList.setSelectionAfterHeaderView(); } }); } if (ptrLayout.isRefreshing()) ptrLayout.setRefreshComplete(); wtl("GRAIO hNR finishing"); }
public void processContent(Response res, NetDesc desc, Document pRes, String resUrl) { wtl("GRAIO hNR fired, desc: " + desc.name()); ptrLayout.setEnabled(false); searchIcon.setVisible(false); searchIcon.collapseActionView(); postIcon.setVisible(false); addFavIcon.setVisible(false); remFavIcon.setVisible(false); topicListIcon.setVisible(false); adapterRows.clear(); boolean isDefaultAcc; if (Session.getUser() != null && Session.getUser().equals(settings.getString("defaultAccount", SettingsMain.NO_DEFAULT_ACCOUNT))) isDefaultAcc = true; else isDefaultAcc = false; try { if (res != null) { wtl("res is not null"); wtl("setting board, topic, message id to null"); boardID = null; topicID = null; messageIDForEditing = null; Element tbody; Element pj = null; String headerTitle; String firstPage = null; String prevPage = null; String currPage = "1"; String pageCount = "1"; String nextPage = null; String lastPage = null; String bgcolor; if (usingLightTheme) bgcolor = "#ffffff"; else bgcolor = "#000000"; adBuilder.setLength(0); adBuilder.append("<html>"); adBuilder.append(pRes.head().outerHtml()); adBuilder.append("<body bgcolor=\"" + bgcolor + "\">"); for (Element e : pRes.getElementsByClass("ad")) { adBuilder.append(e.outerHtml()); e.remove(); } for (Element e : pRes.getElementsByTag("script")) { adBuilder.append(e.outerHtml()); } adBuilder.append("</body></html>"); adBaseUrl = res.url().toString(); if (web == null) web = new WebView(this); web.getSettings().setJavaScriptEnabled(AllInOneV2.getSettingsPref().getBoolean("enableJS", true)); switch (desc) { case BOARD_JUMPER: case LOGIN_S2: updateHeaderNoJumper("Board Jumper", NetDesc.BOARD_JUMPER); adapterRows.add(new HeaderRowData("Announcements")); searchIcon.setVisible(true); processBoards(pRes, true); break; case BOARD_LIST: updateHeaderNoJumper(pRes.getElementsByTag("th").get(4).text(), NetDesc.BOARD_LIST); processBoards(pRes, true); break; case PM_INBOX: tbody = pRes.getElementsByTag("tbody").first(); headerTitle = Session.getUser() + "'s PM Inbox"; if (tbody != null) { pj = pRes.select("ul.paginate").first(); if (pj != null) { String pjText = pj.child(0).text(); if (pjText.contains("Previous")) pjText = pj.child(1).text(); //Page 1 of 5 int currPageStart = 5; int ofIndex = pjText.indexOf(" of "); currPage = pjText.substring(currPageStart, ofIndex); int pageCountEnd = pjText.length(); pageCount = pjText.substring(ofIndex + 4, pageCountEnd); int currPageNum = Integer.parseInt(currPage); int pageCountNum = Integer.parseInt(pageCount); if (currPageNum > 1) { firstPage = "/pm/"; prevPage = "/pm/?page=" + (currPageNum - 2); } if (currPageNum != pageCountNum) { nextPage = "/pm/?page=" + currPageNum; lastPage = "/pm/?page=" + (pageCountNum - 1); } } updateHeader(headerTitle, firstPage, prevPage, currPage, pageCount, nextPage, lastPage, NetDesc.PM_INBOX); if (isDefaultAcc) NotifierService.dismissPMNotif(this); for (Element row : tbody.getElementsByTag("tr")) { Elements cells = row.children(); // [icon] [sender] [subject] [time] [check] boolean isOld = true; if (cells.get(0).children().first().hasClass("icon-circle")) isOld = false; String sender = cells.get(1).text(); Element subjectLinkElem = cells.get(2).children().first(); String subject = subjectLinkElem.text(); String link = subjectLinkElem.attr("href"); String time = cells.get(3).text(); adapterRows.add(new PMRowData(subject, sender, time, link, isOld)); } } else { updateHeaderNoJumper(headerTitle, NetDesc.PM_INBOX); adapterRows.add(new HeaderRowData("You have no private messages at this time.")); } postIcon.setVisible(true); pMode = PostMode.NEW_PM; break; case PM_DETAIL: headerTitle = pRes.select("h2.title").first().text(); String pmTitle = headerTitle; if (!pmTitle.startsWith("Re: ")) pmTitle = "Re: " + pmTitle; String pmMessage = pRes.select("div.body").first().outerHtml(); Element foot = pRes.select("div.foot").first(); foot.child(1).remove(); String pmFoot = foot.outerHtml(); //Sent by: P4wn4g3 on 6/1/2013 2:15:55 PM String footText = foot.text(); String sender = footText.substring(9, footText.indexOf(" on ")); updateHeaderNoJumper(pmTitle, NetDesc.PM_DETAIL); adapterRows.add(new PMDetailRowData(sender, pmTitle, pmMessage + pmFoot)); break; case AMP_LIST: wtl("GRAIO hNR determined this is an amp response"); tbody = pRes.getElementsByTag("tbody").first(); headerTitle = Session.getUser() + "'s Active Messages"; if (pRes.select("ul.paginate").size() > 1) { pj = pRes.select("ul.paginate").get(1); if (pj != null && !pj.hasClass("user") && !pj.hasClass("tsort")) { int x = 0; String pjText = pj.child(x).text(); while (pjText.contains("First") || pjText.contains("Previous")) { x++; pjText = pj.child(x).text(); } // Page 2 of 3 int currPageStart = 5; int ofIndex = pjText.indexOf(" of "); currPage = pjText.substring(currPageStart, ofIndex); int pageCountEnd = pjText.length(); pageCount = pjText.substring(ofIndex + 4, pageCountEnd); int currPageNum = Integer.parseInt(currPage); int pageCountNum = Integer.parseInt(pageCount); String amp = buildAMPLink(); if (currPageNum > 1) { firstPage = amp; prevPage = amp + "&page=" + (currPageNum - 2); } if (currPageNum != pageCountNum) { nextPage = amp + "&page=" + currPageNum; lastPage = amp + "&page=" + (pageCountNum - 1); } } } updateHeader(headerTitle, firstPage, prevPage, currPage, pageCount, nextPage, lastPage, NetDesc.AMP_LIST); if (isDefaultAcc) NotifierService.dismissAMPNotif(this); if (!tbody.children().isEmpty()) { if (settings.getBoolean("notifsEnable", false) && isDefaultAcc) { Element lPost = pRes.select("td.lastpost").first(); if (lPost != null) { String lTime = lPost.text(); Date newDate; lTime = lTime.replace("Last:", EMPTY_STRING); if (lTime.contains("AM") || lTime.contains("PM")) newDate = new SimpleDateFormat("MM'/'dd hh':'mmaa", Locale.US).parse(lTime); else newDate = new SimpleDateFormat("MM'/'dd'/'yyyy", Locale.US).parse(lTime); long newTime = newDate.getTime(); long oldTime = settings.getLong("notifsLastPost", 0); if (newTime > oldTime) { wtl("time is newer"); settings.edit().putLong("notifsLastPost", newTime).commit(); } } } for (Element row : tbody.children()) { // [board] [title] [msg] [last post] [your last post] Elements cells = row.children(); String board = cells.get(0).text(); Element titleLinkElem = cells.get(1).child(0); String title = titleLinkElem.text(); String link = titleLinkElem.attr("href"); String mCount = cells.get(2).textNodes().get(0).text().trim(); Element lPostLinkElem = cells.get(3).child(1); String lPost = lPostLinkElem.text(); String lPostLink = lPostLinkElem.attr("href"); String ylpLink = cells.get(4).child(1).attr("href"); adapterRows.add(new AMPRowData(title, board, lPost, mCount, link, lPostLink, ylpLink)); } } else { adapterRows.add(new HeaderRowData("You have no active messages at this time.")); } wtl("amp response block finished"); break; case TRACKED_TOPICS: headerTitle = Session.getUser() + "'s Tracked Topics"; updateHeaderNoJumper(headerTitle, desc); if (isDefaultAcc) NotifierService.dismissTTNotif(this); tbody = pRes.getElementsByTag("tbody").first(); if (tbody != null) { for (Element row : tbody.children()) { // [remove] [title] [board name] [msgs] [last [pst] Elements cells = row.children(); String removeLink = cells.get(0).child(0) .attr("href"); String topicLink = cells.get(1).child(0) .attr("href"); String topicText = cells.get(1).text(); String board = cells.get(2).text(); String msgs = cells.get(3).text(); String lPostLink = cells.get(4).child(0) .attr("href"); String lPostText = cells.get(4).text(); adapterRows.add(new TrackedTopicRowData(board, topicText, lPostText, msgs, topicLink, removeLink, lPostLink)); } } else { adapterRows.add(new HeaderRowData("You have no tracked topics at this time.")); } break; case BOARD: wtl("GRAIO hNR determined this is a board response"); wtl("setting board id"); boardID = parseBoardID(resUrl); boolean isSplitList = false; if (pRes.getElementsByTag("th").first() != null) { if (pRes.getElementsByTag("th").first().text().equals("Board Title")) { wtl("is actually a split board list"); updateHeaderNoJumper(pRes.select("h1.page-title").first().text(), NetDesc.BOARD); processBoards(pRes, false); isSplitList = true; } } if (!isSplitList) { String url = resUrl; String searchQuery = EMPTY_STRING; String searchPJAddition = EMPTY_STRING; if (url.contains("search=")) { wtl("board search url: " + url); searchQuery = url.substring(url.indexOf("search=") + 7); int i = searchQuery.indexOf('&'); if (i != -1) searchQuery.replace(searchQuery.substring(i), EMPTY_STRING); searchPJAddition = "&search=" + searchQuery; searchQuery = URLDecoder.decode(searchQuery); } Element headerElem = pRes.getElementsByClass("page-title").first(); if (headerElem != null) headerTitle = headerElem.text(); else headerTitle = "GFAQs Cache Error, Board Title Not Found"; if (searchQuery.length() > 0) headerTitle += " (search: " + searchQuery + ")"; if (pRes.select("ul.paginate").size() > 1) { pj = pRes.select("ul.paginate").get(1); if (pj != null && !pj.hasClass("user")) { int x = 0; String pjText = pj.child(x).text(); while (pjText.contains("First") || pjText.contains("Previous")) { x++; pjText = pj.child(x).text(); } // Page [dropdown] of 3 // Page 1 of 3 int ofIndex = pjText.indexOf(" of "); int currPageStart = 5; if (pj.getElementsByTag("select").isEmpty()) currPage = pjText.substring(currPageStart, ofIndex); else currPage = pj .select("option[selected=selected]") .first().text(); int pageCountEnd = pjText.length(); pageCount = pjText.substring(ofIndex + 4, pageCountEnd); int currPageNum = Integer.parseInt(currPage); int pageCountNum = Integer.parseInt(pageCount); if (currPageNum > 1) { firstPage = "boards/" + boardID + "?page=0" + searchPJAddition; prevPage = "boards/" + boardID + "?page=" + (currPageNum - 2) + searchPJAddition; } if (currPageNum != pageCountNum) { nextPage = "boards/" + boardID + "?page=" + currPageNum + searchPJAddition; lastPage = "boards/" + boardID + "?page=" + (pageCountNum - 1) + searchPJAddition; } } } updateHeader(headerTitle, firstPage, prevPage, currPage, pageCount, nextPage, lastPage, NetDesc.BOARD); searchIcon.setVisible(true); if (Session.isLoggedIn()) { String favtext = pRes.getElementsByClass("user").first().text().toLowerCase(Locale.US); if (favtext.contains("add to favorites")) { addFavIcon.setVisible(true); fMode = FavMode.ON_BOARD; } else if (favtext.contains("remove favorite")) { remFavIcon.setVisible(true); fMode = FavMode.ON_BOARD; } updatePostingRights(pRes, false); } Element splitList = pRes.select("p:contains(this is a split board)").first(); if (splitList != null) { String splitListLink = splitList.child(0).attr("href"); adapterRows.add(new BoardRowData("This is a Split Board.", "Click here to return to the Split List.", null, null, null, splitListLink, BoardType.SPLIT)); } Element table = pRes.select("table.board").first(); if (table != null) { table.getElementsByTag("col").get(2).remove(); table.getElementsByTag("th").get(2).remove(); table.getElementsByTag("col").get(0).remove(); table.getElementsByTag("th").get(0).remove(); wtl("board row parsing start"); boolean skipFirst = true; Set<String> hlUsers = hlDB.getHighlightedUsers().keySet(); for (Element row : table.getElementsByTag("tr")) { if (!skipFirst) { Elements cells = row.getElementsByTag("td"); // cells = [image] [title] [author] [post count] [last post] String tImg = cells.get(0).child(0).className(); Element titleLinkElem = cells.get(1).child(0); String title = titleLinkElem.text(); String tUrl = titleLinkElem.attr("href"); String tc = cells.get(2).text(); Element lPostLinkElem = cells.get(4).child(0); String lastPost = lPostLinkElem.text(); String lpUrl = lPostLinkElem.attr("href"); String mCount = cells.get(3).text(); TopicType type = TopicType.NORMAL; if (tImg.contains("poll")) type = TopicType.POLL; else if (tImg.contains("sticky")) type = TopicType.PINNED; else if (tImg.contains("closed")) type = TopicType.LOCKED; else if (tImg.contains("archived")) type = TopicType.ARCHIVED; wtl(tImg + ", " + type.name()); ReadStatus status = ReadStatus.UNREAD; if (tImg.endsWith("_read")) status = ReadStatus.READ; else if (tImg.endsWith("_unread")) status = ReadStatus.NEW_POST; int hlColor = 0; if (hlUsers.contains(tc.toLowerCase(Locale.US))) { HighlightedUser hUser = hlDB.getHighlightedUsers().get(tc.toLowerCase(Locale.US)); hlColor = hUser.getColor(); tc += " (" + hUser.getLabel() + ")"; } adapterRows.add(new TopicRowData(title, tc, lastPost, mCount, tUrl, lpUrl, type, status, hlColor)); } else skipFirst = false; } wtl("board row parsing end"); } else { adapterRows.add(new HeaderRowData("There are no topics at this time.")); } } wtl("board response block finished"); break; case TOPIC: boardID = parseBoardID(resUrl); topicID = parseTopicID(resUrl); tlUrl = "boards/" + boardID; wtl(tlUrl); topicListIcon.setVisible(true); Element headerElem = pRes.getElementsByClass("title").first(); if (headerElem != null) headerTitle = headerElem.text(); else headerTitle = "GFAQs Cache Error, Title Not Found"; if (headerTitle.equals("Log In to GameFAQs")) { headerElem = pRes.getElementsByClass("title").get(1); if (headerElem != null) headerTitle = headerElem.text(); } if (pRes.select("ul.paginate").size() > 1) { pj = pRes.select("ul.paginate").get(1); if (pj != null && !pj.hasClass("user")) { int x = 0; String pjText = pj.child(x).text(); while (pjText.contains("First") || pjText.contains("Previous")) { x++; pjText = pj.child(x).text(); } // Page [dropdown] of 3 // Page 1 of 3 int ofIndex = pjText.indexOf(" of "); int currPageStart = 5; if (pj.getElementsByTag("select").isEmpty()) currPage = pjText.substring(currPageStart, ofIndex); else currPage = pj .select("option[selected=selected]") .first().text(); int pageCountEnd = pjText.length(); pageCount = pjText.substring(ofIndex + 4, pageCountEnd); int currPageNum = Integer.parseInt(currPage); int pageCountNum = Integer.parseInt(pageCount); if (currPageNum > 1) { firstPage = "boards/" + boardID + "/" + topicID; prevPage = "boards/" + boardID + "/" + topicID + "?page=" + (currPageNum - 2); } if (currPageNum != pageCountNum) { nextPage = "boards/" + boardID + "/" + topicID + "?page=" + currPageNum; lastPage = "boards/" + boardID + "/" + topicID + "?page=" + (pageCountNum - 1); } } } updateHeader(headerTitle, firstPage, prevPage, currPage, pageCount, nextPage, lastPage, NetDesc.TOPIC); if (Session.isLoggedIn()) { String favtext = pRes.getElementsByClass("user").first().text().toLowerCase(Locale.US); if (favtext.contains("track topic")) { addFavIcon.setVisible(true); fMode = FavMode.ON_TOPIC; } else if (favtext.contains("stop tracking")) { remFavIcon.setVisible(true); fMode = FavMode.ON_TOPIC; } updatePostingRights(pRes, true); } String goToThisPost = null; if (goToUrlDefinedPost) { String url = res.url().toString(); goToThisPost = url.substring(url.indexOf('#') + 1); } Elements rows = pRes.select("table.board").first().getElementsByTag("tr"); int rowCount = rows.size(); int msgIndex = 0; Set<String> hlUsers = hlDB.getHighlightedUsers().keySet(); for (int x = 0; x < rowCount; x++) { Element row = rows.get(x); String user = null; String postNum = null; String mID = null; String userTitles = EMPTY_STRING; String postTimeText = EMPTY_STRING; String postTime = EMPTY_STRING; Element msgBody = null; if (row.hasClass("left")) { // message poster display set to left of message Elements authorData = row.getElementsByClass("author_data"); user = row.getElementsByTag("b").first().text(); postNum = row.getElementsByTag("a").first().attr("name"); for (int i = 1; i < authorData.size(); i++) { Element e = authorData.get(i); String t = e.text(); if (t.startsWith("(")) userTitles += " " + t; else if (e.hasClass("tag")) userTitles += " (tagged as " + t + ")"; else if (t.startsWith("Posted")) postTime = t; else if (t.equals("message detail")) mID = parseMessageID(e.child(0).attr("href")); } msgBody = row.child(1).child(0); } else { // message poster display set to above message List<TextNode> textNodes = row.child(0).child(0).textNodes(); Elements elements = row.child(0).child(0).children(); int textNodesSize = textNodes.size(); for (int y = 0; y < textNodesSize; y++) { String text = textNodes.get(y).text(); if (text.startsWith("Posted")) postTimeText = text; else if (text.contains("(")) { userTitles += " " + text.substring(text.indexOf('('), text.lastIndexOf(')') + 1); } } user = elements.get(0).text(); int anchorCount = row.getElementsByTag("a").size(); postNum = row.getElementsByTag("a").get((anchorCount > 1 ? 1 : 0)).attr("name"); int elementsSize = elements.size(); for (int y = 0; y < elementsSize; y++) { Element e = elements.get(y); if (e.hasClass("tag")) userTitles += " (tagged as " + e.text() + ")"; else if (e.text().equals("message detail")) mID = parseMessageID(e.attr("href")); } //Posted 11/15/2012 11:20:27&nbsp;AM | (edited) [if archived] if (postTimeText.contains("(edited)")) userTitles += " (edited)"; int endPoint = postTimeText.indexOf('|') - 1; if (endPoint < 0) endPoint = postTimeText.length(); postTime = postTimeText.substring(0, endPoint); x++; msgBody = rows.get(x).child(0).child(0); } int hlColor = 0; if (hlUsers.contains(user.toLowerCase(Locale.US))) { HighlightedUser hUser = hlDB .getHighlightedUsers().get( user.toLowerCase(Locale.US)); hlColor = hUser.getColor(); userTitles += " (" + hUser.getLabel() + ")"; } if (goToUrlDefinedPost) { if (postNum.equals(goToThisPost)) goToThisIndex = msgIndex; } wtl("creating messagerowdata object"); adapterRows.add(new MessageRowData(user, userTitles, postNum, postTime, msgBody, boardID, topicID, mID, hlColor)); msgIndex++; } break; case MESSAGE_DETAIL: updateHeaderNoJumper("Message Detail", NetDesc.MESSAGE_DETAIL); boardID = parseBoardID(resUrl); topicID = parseTopicID(resUrl); Elements msgDRows = pRes.getElementsByTag("tr"); String user = msgDRows.first().child(0).child(0).text(); adapterRows.add(new HeaderRowData("Current Version")); Element currRow, body; MessageRowData msg; String postTime; String mID = parseMessageID(resUrl); for (int x = 0; x < msgDRows.size(); x++) { if (x == 1) adapterRows.add(new HeaderRowData("Previous Version(s)")); else { currRow = msgDRows.get(x); if (currRow.child(0).textNodes().size() > 1) postTime = currRow.child(0).textNodes().get(1).text(); else postTime = currRow.child(0).textNodes().get(0).text(); body = currRow.child(1); msg = new MessageRowData(user, null, null, postTime, body, boardID, topicID, mID, 0); msg.disableTopClick(); adapterRows.add(msg); } } break; case USER_DETAIL: wtl("starting user detail processing"); tbody = pRes.select("table.board").first().getElementsByTag("tbody").first(); Log.d("udtb", tbody.outerHtml()); String name = null; String ID = null; String level = null; String creation = null; String lVisit = null; String sig = null; String karma = null; String AMP = null; for (Element row : tbody.children()) { String label = row.child(0).text().toLowerCase(Locale.US); wtl("user detail row label: " + label); if (label.equals("user name")) name = row.child(1).text(); else if (label.equals("user id")) ID = row.child(1).text(); else if (label.equals("board user level")) { level = row.child(1).html(); wtl("set level: " + level); } else if (label.equals("account created")) creation = row.child(1).text(); else if (label.equals("last visit")) lVisit = row.child(1).text(); else if (label.equals("signature")) sig = row.child(1).html(); else if (label.equals("karma")) karma = row.child(1).text(); else if (label.equals("active messages posted")) AMP = row.child(1).text(); } updateHeaderNoJumper(name + "'s Details", NetDesc.USER_DETAIL); adapterRows.add(new UserDetailRowData(name, ID, level, creation, lVisit, sig, karma, AMP)); break; case GAME_SEARCH: wtl("GRAIO hNR determined this is a game search response"); String url = resUrl; wtl("game search url: " + url); String searchQuery = url.substring(url.indexOf("game=") + 5); int i = searchQuery.indexOf("&"); if (i != -1) searchQuery = searchQuery.replace(searchQuery.substring(i), EMPTY_STRING); int pageIndex = url.indexOf("page="); if (pageIndex != -1) { currPage = url.substring(pageIndex + 5); i = currPage.indexOf("&"); if (i != -1) currPage = currPage.replace(currPage.substring(i), EMPTY_STRING); } else { currPage = "0"; } int currPageNum = Integer.parseInt(currPage); Element nextPageElem = null; if (!pRes.getElementsContainingOwnText("Next Page").isEmpty()) nextPageElem = pRes.getElementsContainingOwnText("Next Page").first(); pageCount = "???"; if (nextPageElem != null) { nextPage = "/search/index.html?game=" + searchQuery + "&page=" + (currPageNum + 1); } if (currPageNum > 0) { prevPage = "/search/index.html?game=" + searchQuery + "&page=" + (currPageNum - 1); firstPage = "/search/index.html?game=" + searchQuery + "&page=0"; } headerTitle = "Searching games: " + URLDecoder.decode(searchQuery) + EMPTY_STRING; updateHeader(headerTitle, firstPage, prevPage, Integer.toString(currPageNum + 1), pageCount, nextPage, lastPage, NetDesc.GAME_SEARCH); searchIcon.setVisible(true); Elements gameSearchTables = pRes.select("table.results"); int tCount = gameSearchTables.size(); int tCounter = 0; if (!gameSearchTables.isEmpty()) { for (Element table : gameSearchTables) { tCounter++; if (tCounter < tCount) adapterRows.add(new HeaderRowData("Best Matches")); else adapterRows.add(new HeaderRowData("Good Matches")); String prevPlatform = EMPTY_STRING; wtl("board row parsing start"); for (Element row : table.getElementsByTag("tr")) { Elements cells = row.getElementsByTag("td"); // cells = [platform] [title] [faqs] [codes] [saves] [revs] [mygames] [q&a] [pics] [vids] [board] String platform = cells.get(0).text(); String bName = cells.get(1).text(); String bUrl = cells.get(9).child(0).attr("href"); if (platform.codePointAt(0) == ('\u00A0')) { platform = prevPlatform; } else { prevPlatform = platform; } adapterRows.add(new GameSearchRowData(bName, platform, bUrl)); } wtl("board row parsing end"); } } else { adapterRows.add(new HeaderRowData("No results.")); } wtl("game search response block finished"); break; default: wtl("GRAIO hNR determined response type is unhandled"); title.setText("Page unhandled - " + resUrl); break; } try { ((ViewGroup) web.getParent()).removeView(web); } catch (Exception e1) {} adapterRows.add(new AdRowData(web)); contentList.post(loadAds); Element pmInboxLink = pRes.select("div.masthead_user").first().select("a[href=/pm/]").first(); if (pmInboxLink != null) { String text = pmInboxLink.text(); if (text.contains("(")) { int count = Integer.parseInt(text.substring(text.indexOf('(') + 1, text.indexOf(')'))); int prevCount = settings.getInt("unreadPMCount", 0); if (count > prevCount) { settings.edit().putInt("unreadPMCount", count).apply(); if (isDefaultAcc) settings.edit().putInt("notifsUnreadPMCount", count).apply(); if (count > 1) Crouton.showText(this, "You have " + count + " unread PMs", croutonStyle, ptrLayout); else Crouton.showText(this, "You have 1 unread PM", croutonStyle, ptrLayout); } } } Element trackedLink = pRes.select("div.masthead_user").first().select("a[href=/boards/tracked]").first(); if (trackedLink != null) { String text = trackedLink.text(); if (text.contains("(")) { int count = Integer.parseInt(text.substring(text.indexOf('(') + 1, text.indexOf(')'))); int prevCount = settings.getInt("unreadTTCount", 0); if (count > prevCount) { settings.edit().putInt("unreadTTCount", count).apply(); if (isDefaultAcc) settings.edit().putInt("notifsUnreadTTCount", count).apply(); if (count > 1) Crouton.showText(this, "You have " + count + " unread tracked topics", croutonStyle, ptrLayout); else Crouton.showText(this, "You have 1 unread tracked topic", croutonStyle, ptrLayout); } } } ptrLayout.setEnabled(settings.getBoolean("enablePTR", false)); } else { wtl("res is null"); adapterRows.add(new HeaderRowData("You broke it. Somehow processContent was called with a null response.")); } } catch (Exception e) { e.printStackTrace(); tryCaught(res.url().toString(), desc.toString(), ExceptionUtils.getStackTrace(e), res.body()); if (session.canGoBack()) session.goBack(false); } catch (StackOverflowError e) { e.printStackTrace(); tryCaught(res.url().toString(), desc.toString(), ExceptionUtils.getStackTrace(e), res.body()); if (session.canGoBack()) session.goBack(false); } if (!adapterSet) { contentList.setAdapter(viewAdapter); adapterSet = true; } else viewAdapter.notifyDataSetChanged(); if (consumeGoToUrlDefinedPost() && !Session.applySavedScroll) { contentList.post(new Runnable() { @Override public void run() { contentList.setSelection(goToThisIndex); } }); } else if (Session.applySavedScroll) { contentList.post(new Runnable() { @Override public void run() { contentList.setSelectionFromTop(Session.savedScrollVal[0], Session.savedScrollVal[1]); Session.applySavedScroll = false; } }); } else { contentList.post(new Runnable() { @Override public void run() { contentList.setSelectionAfterHeaderView(); } }); } if (ptrLayout.isRefreshing()) ptrLayout.setRefreshComplete(); wtl("GRAIO hNR finishing"); }
diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/filters/WebappDaoFactorySDBPrep.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/filters/WebappDaoFactorySDBPrep.java index 57fde8332..f78d0b928 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/filters/WebappDaoFactorySDBPrep.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/filters/WebappDaoFactorySDBPrep.java @@ -1,138 +1,154 @@ /* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.filters; import java.io.IOException; import java.sql.SQLException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hp.hpl.jena.query.Dataset; import com.hp.hpl.jena.sdb.SDBFactory; import com.hp.hpl.jena.sdb.Store; import com.hp.hpl.jena.sdb.StoreDesc; import com.hp.hpl.jena.sdb.sql.SDBConnection; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelector; import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactorySDB; import edu.cornell.mannlib.vitro.webapp.servlet.setup.JenaDataSourceSetupBase; public class WebappDaoFactorySDBPrep implements Filter { private final static Log log = LogFactory.getLog(WebappDaoFactorySDBPrep.class); BasicDataSource _bds; StoreDesc _storeDesc; SDBConnection _conn; OntModelSelector _oms; String _defaultNamespace; /** * The filter will be applied to all incoming urls, this is a list of URI patterns to skip. These are matched against the requestURI sans query parameters, * e.g. * "/vitro/index.jsp" * "/vitro/themes/enhanced/css/edit.css" * * These patterns are from VitroRequestPrep.java */ Pattern[] skipPatterns = { Pattern.compile(".*\\.(gif|GIF|jpg|jpeg)$"), Pattern.compile(".*\\.css$"), Pattern.compile(".*\\.js$"), Pattern.compile("/.*/themes/.*/site_icons/.*"), Pattern.compile("/.*/images/.*") }; public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if ( (!(JenaDataSourceSetupBase.isSDBActive())) || (request.getAttribute( "WebappDaoFactorySDBPrep.setup") != null) ) { // don't run multiple times or if SDB is not active filterChain.doFilter(request, response); return; } for( Pattern skipPattern : skipPatterns){ Matcher match =skipPattern.matcher( ((HttpServletRequest)request).getRequestURI() ); if( match.matches() ){ log.debug("request matched a skipPattern, skipping VitroRequestPrep"); filterChain.doFilter(request, response); return; } } SDBConnection conn = null; + Store store = null; + Dataset dataset = null; try { if ( request instanceof HttpServletRequest && _bds != null && _storeDesc != null && _oms != null) { try { conn = new SDBConnection(_bds.getConnection()) ; } catch (SQLException sqe) { throw new RuntimeException("Unable to connect to database", sqe); } if (conn != null) { - Store store = SDBFactory.connectStore(conn, _storeDesc); - Dataset dataset = SDBFactory.connectDataset(store); + store = SDBFactory.connectStore(conn, _storeDesc); + dataset = SDBFactory.connectDataset(store); VitroRequest vreq = new VitroRequest((HttpServletRequest) request); WebappDaoFactory wadf = new WebappDaoFactorySDB(_oms, dataset, _defaultNamespace, null, null); vreq.setWebappDaoFactory(wadf); vreq.setFullWebappDaoFactory(wadf); vreq.setDataset(dataset); } } } catch (Throwable t) { log.error("Unable to filter request to set up SDB connection", t); } request.setAttribute("WebappDaoFactorySDBPrep.setup", 1); try { filterChain.doFilter(request, response); return; } finally { if (conn != null) { conn.close(); + conn = null; } + if (dataset != null) { + dataset.close(); + dataset = null; + } + if (store != null) { + store.close(); + store = null; + } + _bds = null; + _storeDesc = null; + _conn = null; + _oms = null; + _defaultNamespace = null; } } public void init(FilterConfig filterConfig) throws ServletException { try { ServletContext ctx = filterConfig.getServletContext(); _bds = JenaDataSourceSetupBase.getApplicationDataSource(ctx); _storeDesc = (StoreDesc) ctx.getAttribute("storeDesc"); _oms = (OntModelSelector) ctx.getAttribute("unionOntModelSelector"); _defaultNamespace = (String) ctx.getAttribute("defaultNamespace"); } catch (Throwable t) { log.error("Unable to set up SDB WebappDaoFactory for request", t); } } public void destroy() { // no destroy actions } }
false
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if ( (!(JenaDataSourceSetupBase.isSDBActive())) || (request.getAttribute( "WebappDaoFactorySDBPrep.setup") != null) ) { // don't run multiple times or if SDB is not active filterChain.doFilter(request, response); return; } for( Pattern skipPattern : skipPatterns){ Matcher match =skipPattern.matcher( ((HttpServletRequest)request).getRequestURI() ); if( match.matches() ){ log.debug("request matched a skipPattern, skipping VitroRequestPrep"); filterChain.doFilter(request, response); return; } } SDBConnection conn = null; try { if ( request instanceof HttpServletRequest && _bds != null && _storeDesc != null && _oms != null) { try { conn = new SDBConnection(_bds.getConnection()) ; } catch (SQLException sqe) { throw new RuntimeException("Unable to connect to database", sqe); } if (conn != null) { Store store = SDBFactory.connectStore(conn, _storeDesc); Dataset dataset = SDBFactory.connectDataset(store); VitroRequest vreq = new VitroRequest((HttpServletRequest) request); WebappDaoFactory wadf = new WebappDaoFactorySDB(_oms, dataset, _defaultNamespace, null, null); vreq.setWebappDaoFactory(wadf); vreq.setFullWebappDaoFactory(wadf); vreq.setDataset(dataset); } } } catch (Throwable t) { log.error("Unable to filter request to set up SDB connection", t); } request.setAttribute("WebappDaoFactorySDBPrep.setup", 1); try { filterChain.doFilter(request, response); return; } finally { if (conn != null) { conn.close(); } } }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if ( (!(JenaDataSourceSetupBase.isSDBActive())) || (request.getAttribute( "WebappDaoFactorySDBPrep.setup") != null) ) { // don't run multiple times or if SDB is not active filterChain.doFilter(request, response); return; } for( Pattern skipPattern : skipPatterns){ Matcher match =skipPattern.matcher( ((HttpServletRequest)request).getRequestURI() ); if( match.matches() ){ log.debug("request matched a skipPattern, skipping VitroRequestPrep"); filterChain.doFilter(request, response); return; } } SDBConnection conn = null; Store store = null; Dataset dataset = null; try { if ( request instanceof HttpServletRequest && _bds != null && _storeDesc != null && _oms != null) { try { conn = new SDBConnection(_bds.getConnection()) ; } catch (SQLException sqe) { throw new RuntimeException("Unable to connect to database", sqe); } if (conn != null) { store = SDBFactory.connectStore(conn, _storeDesc); dataset = SDBFactory.connectDataset(store); VitroRequest vreq = new VitroRequest((HttpServletRequest) request); WebappDaoFactory wadf = new WebappDaoFactorySDB(_oms, dataset, _defaultNamespace, null, null); vreq.setWebappDaoFactory(wadf); vreq.setFullWebappDaoFactory(wadf); vreq.setDataset(dataset); } } } catch (Throwable t) { log.error("Unable to filter request to set up SDB connection", t); } request.setAttribute("WebappDaoFactorySDBPrep.setup", 1); try { filterChain.doFilter(request, response); return; } finally { if (conn != null) { conn.close(); conn = null; } if (dataset != null) { dataset.close(); dataset = null; } if (store != null) { store.close(); store = null; } _bds = null; _storeDesc = null; _conn = null; _oms = null; _defaultNamespace = null; } }
diff --git a/src/main/java/org/elasticsearch/sorting/nativescript/script/ActivitySortScript.java b/src/main/java/org/elasticsearch/sorting/nativescript/script/ActivitySortScript.java index 7ae63bf..f01650a 100644 --- a/src/main/java/org/elasticsearch/sorting/nativescript/script/ActivitySortScript.java +++ b/src/main/java/org/elasticsearch/sorting/nativescript/script/ActivitySortScript.java @@ -1,57 +1,56 @@ package main.java.org.elasticsearch.sorting.nativescript.script; import java.util.Date; import java.util.Map; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.script.AbstractDoubleSearchScript; import org.elasticsearch.script.ExecutableScript; import org.elasticsearch.script.NativeScriptFactory; public class ActivitySortScript implements NativeScriptFactory { @Override public ExecutableScript newScript(@Nullable Map<String, Object> params) { return new SortScript(); } public static class SortScript extends AbstractDoubleSearchScript { private final ESLogger logger = Loggers.getLogger(ActivitySortScript.class); private final long one_hour = 3600000; private final Date to_day = new Date(); public SortScript() { } @Override public double runAsDouble() { long total = (Long.parseLong(getFieldValue("like")) * 5) + (Long.parseLong(getFieldValue("participate")) * 100) + Long.parseLong(getFieldValue("status")); Date start_time = BaseModule .parse_date(getFieldValue("start_time")); Date end_time = BaseModule.parse_date(getFieldValue("end_time")); double sum = 0; if (start_time.after(to_day)) { return total / ((start_time.getTime() - to_day.getTime()) / one_hour); } else if (start_time.before(to_day) && end_time.before(to_day)) { return total / ((to_day.getTime() - end_time.getTime()) / one_hour); } else { return (total + (end_time.getTime() - to_day.getTime())) / ((to_day.getTime() - start_time.getTime()) / one_hour); - } - return sum; + } } private String getFieldValue(String field) { return source().get(field).toString(); } } }
true
true
public double runAsDouble() { long total = (Long.parseLong(getFieldValue("like")) * 5) + (Long.parseLong(getFieldValue("participate")) * 100) + Long.parseLong(getFieldValue("status")); Date start_time = BaseModule .parse_date(getFieldValue("start_time")); Date end_time = BaseModule.parse_date(getFieldValue("end_time")); double sum = 0; if (start_time.after(to_day)) { return total / ((start_time.getTime() - to_day.getTime()) / one_hour); } else if (start_time.before(to_day) && end_time.before(to_day)) { return total / ((to_day.getTime() - end_time.getTime()) / one_hour); } else { return (total + (end_time.getTime() - to_day.getTime())) / ((to_day.getTime() - start_time.getTime()) / one_hour); } return sum; }
public double runAsDouble() { long total = (Long.parseLong(getFieldValue("like")) * 5) + (Long.parseLong(getFieldValue("participate")) * 100) + Long.parseLong(getFieldValue("status")); Date start_time = BaseModule .parse_date(getFieldValue("start_time")); Date end_time = BaseModule.parse_date(getFieldValue("end_time")); double sum = 0; if (start_time.after(to_day)) { return total / ((start_time.getTime() - to_day.getTime()) / one_hour); } else if (start_time.before(to_day) && end_time.before(to_day)) { return total / ((to_day.getTime() - end_time.getTime()) / one_hour); } else { return (total + (end_time.getTime() - to_day.getTime())) / ((to_day.getTime() - start_time.getTime()) / one_hour); } }
diff --git a/core/src/main/java/org/mule/galaxy/impl/link/LinkExtension.java b/core/src/main/java/org/mule/galaxy/impl/link/LinkExtension.java index 9a74fca4..d910d213 100644 --- a/core/src/main/java/org/mule/galaxy/impl/link/LinkExtension.java +++ b/core/src/main/java/org/mule/galaxy/impl/link/LinkExtension.java @@ -1,174 +1,174 @@ package org.mule.galaxy.impl.link; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import org.mule.galaxy.DuplicateItemException; import org.mule.galaxy.Item; import org.mule.galaxy.Link; import org.mule.galaxy.Links; import org.mule.galaxy.NotFoundException; import org.mule.galaxy.Registry; import org.mule.galaxy.impl.extension.IdentifiableExtension; import org.mule.galaxy.policy.PolicyException; import org.mule.galaxy.security.AccessException; import org.mule.galaxy.type.PropertyDescriptor; import org.mule.galaxy.type.TypeManager; import org.mule.galaxy.util.SecurityUtils; public class LinkExtension extends IdentifiableExtension<Link> { public static final String CONFLICTS = "conflicts"; public static final String INCLUDES = "includes"; public static final String SUPERCEDES = "supercedes"; public static final String DOCUMENTS = "documents"; public final static String DEPENDS = "depends"; private TypeManager typeManager; private List<String> configuration = new ArrayList<String>(); private Registry registry; public void initialize() throws Exception { setName("Link"); configuration.add("Reciprocal Name"); add(DEPENDS, "Depends On", "Depended On By"); add(DOCUMENTS, "Documents", "Documented By"); add(SUPERCEDES, "Supercedes", "Superceded By"); add(INCLUDES, "Includes", "Included By"); add(CONFLICTS, "Conflicts With", "Is Conflicted By"); } @Override public boolean isMultivalueSupported() { return false; } private void add(String property, String name, String inverse) { final PropertyDescriptor pd = new PropertyDescriptor(property, name, true, false); pd.setExtension(this); List<String> keys = getPropertyDescriptorConfigurationKeys(); HashMap<String, String> configuration = new HashMap<String, String>(); configuration.put(keys.get(0), inverse); pd.setConfiguration(configuration); SecurityUtils.doPriveleged(new Runnable() { public void run() { try { typeManager.savePropertyDescriptor(pd); } catch (DuplicateItemException e) { } catch (AccessException e) { } catch (NotFoundException e) { } } }); } @Override public void store(Item item, PropertyDescriptor pd, Object value) throws PolicyException { if (value instanceof Collection) { for (Object o : (Collection) value) { Link l = (Link) o; l.setProperty(pd.getProperty()); try { dao.save(l); } catch (DuplicateItemException e) { throw new RuntimeException(e); } catch (NotFoundException e) { throw new RuntimeException(e); } } } else if (value == null) { ((LinkDao) dao).deleteLinks(item, pd.getProperty()); } else { throw new UnsupportedOperationException(); } } @Override public Object get(final Item item, final PropertyDescriptor pd, boolean getWithNoData) { Links links = new Links() { private Collection<Link> links; private Collection<Link> reciprocal; public void addLinks(Link l) { if (!l.getItem().equals(item)) { throw new IllegalStateException("Item specified must be the item associated with this Links instance."); } try { l.setProperty(pd.getProperty()); dao.save(l); if (links != null) { links.add(l); } else { links = new ArrayList<Link>(); links.add(l); } } catch (DuplicateItemException e) { throw new RuntimeException(e); } catch (NotFoundException e) { throw new RuntimeException(e); } } public Collection<Link> getLinks() { if (links == null) { links = addRegistry(((LinkDao) dao).getLinks(item, pd.getProperty())); } return links; } public Collection<Link> getReciprocalLinks() { if (reciprocal == null) { reciprocal = addRegistry(((LinkDao) dao).getReciprocalLinks(item, pd.getProperty())); } return reciprocal; } public void removeLinks(Link... links) { for (Link l : links) { dao.delete(l.getId()); } reciprocal = null; - links = null; + this.links = null; } }; if (!getWithNoData && links.getReciprocalLinks().isEmpty() && links.getLinks().isEmpty()) { return null; } return links; } protected Collection<Link> addRegistry(Collection<Link> links) { for (Link l : links) { l.setRegistry(registry); } return links; } @Override public List<String> getPropertyDescriptorConfigurationKeys() { return configuration; } public void setTypeManager(TypeManager typeManager) { this.typeManager = typeManager; } public void setRegistry(Registry registry) { this.registry = registry; } }
true
true
public Object get(final Item item, final PropertyDescriptor pd, boolean getWithNoData) { Links links = new Links() { private Collection<Link> links; private Collection<Link> reciprocal; public void addLinks(Link l) { if (!l.getItem().equals(item)) { throw new IllegalStateException("Item specified must be the item associated with this Links instance."); } try { l.setProperty(pd.getProperty()); dao.save(l); if (links != null) { links.add(l); } else { links = new ArrayList<Link>(); links.add(l); } } catch (DuplicateItemException e) { throw new RuntimeException(e); } catch (NotFoundException e) { throw new RuntimeException(e); } } public Collection<Link> getLinks() { if (links == null) { links = addRegistry(((LinkDao) dao).getLinks(item, pd.getProperty())); } return links; } public Collection<Link> getReciprocalLinks() { if (reciprocal == null) { reciprocal = addRegistry(((LinkDao) dao).getReciprocalLinks(item, pd.getProperty())); } return reciprocal; } public void removeLinks(Link... links) { for (Link l : links) { dao.delete(l.getId()); } reciprocal = null; links = null; } }; if (!getWithNoData && links.getReciprocalLinks().isEmpty() && links.getLinks().isEmpty()) { return null; } return links; }
public Object get(final Item item, final PropertyDescriptor pd, boolean getWithNoData) { Links links = new Links() { private Collection<Link> links; private Collection<Link> reciprocal; public void addLinks(Link l) { if (!l.getItem().equals(item)) { throw new IllegalStateException("Item specified must be the item associated with this Links instance."); } try { l.setProperty(pd.getProperty()); dao.save(l); if (links != null) { links.add(l); } else { links = new ArrayList<Link>(); links.add(l); } } catch (DuplicateItemException e) { throw new RuntimeException(e); } catch (NotFoundException e) { throw new RuntimeException(e); } } public Collection<Link> getLinks() { if (links == null) { links = addRegistry(((LinkDao) dao).getLinks(item, pd.getProperty())); } return links; } public Collection<Link> getReciprocalLinks() { if (reciprocal == null) { reciprocal = addRegistry(((LinkDao) dao).getReciprocalLinks(item, pd.getProperty())); } return reciprocal; } public void removeLinks(Link... links) { for (Link l : links) { dao.delete(l.getId()); } reciprocal = null; this.links = null; } }; if (!getWithNoData && links.getReciprocalLinks().isEmpty() && links.getLinks().isEmpty()) { return null; } return links; }
diff --git a/src/org/mozilla/javascript/ScriptableObject.java b/src/org/mozilla/javascript/ScriptableObject.java index e011035d..8b8188a7 100644 --- a/src/org/mozilla/javascript/ScriptableObject.java +++ b/src/org/mozilla/javascript/ScriptableObject.java @@ -1,2501 +1,2499 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Daniel Gredler * Bob Jervis * Roger Lawrence * Steve Weiss * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; import java.lang.reflect.*; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.io.*; import org.mozilla.javascript.debug.DebuggableObject; /** * This is the default implementation of the Scriptable interface. This * class provides convenient default behavior that makes it easier to * define host objects. * <p> * Various properties and methods of JavaScript objects can be conveniently * defined using methods of ScriptableObject. * <p> * Classes extending ScriptableObject must define the getClassName method. * * @see org.mozilla.javascript.Scriptable * @author Norris Boyd */ public abstract class ScriptableObject implements Scriptable, Serializable, DebuggableObject, ConstProperties { /** * The empty property attribute. * * Used by getAttributes() and setAttributes(). * * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int EMPTY = 0x00; /** * Property attribute indicating assignment to this property is ignored. * * @see org.mozilla.javascript.ScriptableObject * #put(String, Scriptable, Object) * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int READONLY = 0x01; /** * Property attribute indicating property is not enumerated. * * Only enumerated properties will be returned by getIds(). * * @see org.mozilla.javascript.ScriptableObject#getIds() * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int DONTENUM = 0x02; /** * Property attribute indicating property cannot be deleted. * * @see org.mozilla.javascript.ScriptableObject#delete(String) * @see org.mozilla.javascript.ScriptableObject#getAttributes(String) * @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int) */ public static final int PERMANENT = 0x04; /** * Property attribute indicating that this is a const property that has not * been assigned yet. The first 'const' assignment to the property will * clear this bit. */ public static final int UNINITIALIZED_CONST = 0x08; public static final int CONST = PERMANENT|READONLY|UNINITIALIZED_CONST; /** * The prototype of this object. */ private Scriptable prototypeObject; /** * The parent scope of this object. */ private Scriptable parentScopeObject; private static final Slot REMOVED = new Slot(null, 0, READONLY); static { REMOVED.wasDeleted = true; } private transient Slot[] slots; // If count >= 0, it gives number of keys or if count < 0, // it indicates sealed object where ~count gives number of keys private int count; // gateways into the definition-order linked list of slots private transient Slot firstAdded; private transient Slot lastAdded; // cache; may be removed for smaller memory footprint private transient Slot lastAccess = REMOVED; // associated values are not serialized private transient volatile Map<Object,Object> associatedValues; private static final int SLOT_QUERY = 1; private static final int SLOT_MODIFY = 2; private static final int SLOT_REMOVE = 3; private static final int SLOT_MODIFY_GETTER_SETTER = 4; private static final int SLOT_MODIFY_CONST = 5; private static class Slot implements Serializable { private static final long serialVersionUID = -6090581677123995491L; String name; // This can change due to caching int indexOrHash; private volatile short attributes; transient volatile boolean wasDeleted; volatile Object value; transient volatile Slot next; // next in hash table bucket transient volatile Slot orderedNext; // next in linked list Slot(String name, int indexOrHash, int attributes) { this.name = name; this.indexOrHash = indexOrHash; this.attributes = (short)attributes; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (name != null) { indexOrHash = name.hashCode(); } } final int getAttributes() { return attributes; } final synchronized void setAttributes(int value) { checkValidAttributes(value); attributes = (short)value; } final void checkNotReadonly() { if ((attributes & READONLY) != 0) { String str = (name != null ? name : Integer.toString(indexOrHash)); throw Context.reportRuntimeError1("msg.modify.readonly", str); } } } private static final class GetterSlot extends Slot { static final long serialVersionUID = -4900574849788797588L; Object getter; Object setter; GetterSlot(String name, int indexOrHash, int attributes) { super(name, indexOrHash, attributes); } } static void checkValidAttributes(int attributes) { final int mask = READONLY | DONTENUM | PERMANENT | UNINITIALIZED_CONST; if ((attributes & ~mask) != 0) { throw new IllegalArgumentException(String.valueOf(attributes)); } } public ScriptableObject() { } public ScriptableObject(Scriptable scope, Scriptable prototype) { if (scope == null) throw new IllegalArgumentException(); parentScopeObject = scope; prototypeObject = prototype; } /** * Return the name of the class. * * This is typically the same name as the constructor. * Classes extending ScriptableObject must implement this abstract * method. */ public abstract String getClassName(); /** * Returns true if the named property is defined. * * @param name the name of the property * @param start the object in which the lookup began * @return true if and only if the property was found in the object */ public boolean has(String name, Scriptable start) { return null != getSlot(name, 0, SLOT_QUERY); } /** * Returns true if the property index is defined. * * @param index the numeric index for the property * @param start the object in which the lookup began * @return true if and only if the property was found in the object */ public boolean has(int index, Scriptable start) { return null != getSlot(null, index, SLOT_QUERY); } /** * Returns the value of the named property or NOT_FOUND. * * If the property was created using defineProperty, the * appropriate getter method is called. * * @param name the name of the property * @param start the object in which the lookup began * @return the value of the property (may be null), or NOT_FOUND */ public Object get(String name, Scriptable start) { return getImpl(name, 0, start); } /** * Returns the value of the indexed property or NOT_FOUND. * * @param index the numeric index for the property * @param start the object in which the lookup began * @return the value of the property (may be null), or NOT_FOUND */ public Object get(int index, Scriptable start) { return getImpl(null, index, start); } /** * Sets the value of the named property, creating it if need be. * * If the property was created using defineProperty, the * appropriate setter method is called. <p> * * If the property's attributes include READONLY, no action is * taken. * This method will actually set the property in the start * object. * * @param name the name of the property * @param start the object whose property is being set * @param value value to set the property to */ public void put(String name, Scriptable start, Object value) { if (putImpl(name, 0, start, value, EMPTY)) return; if (start == this) throw Kit.codeBug(); start.put(name, start, value); } /** * Sets the value of the indexed property, creating it if need be. * * @param index the numeric index for the property * @param start the object whose property is being set * @param value value to set the property to */ public void put(int index, Scriptable start, Object value) { if (putImpl(null, index, start, value, EMPTY)) return; if (start == this) throw Kit.codeBug(); start.put(index, start, value); } /** * Removes a named property from the object. * * If the property is not found, or it has the PERMANENT attribute, * no action is taken. * * @param name the name of the property */ public void delete(String name) { checkNotSealed(name, 0); accessSlot(name, 0, SLOT_REMOVE); } /** * Removes the indexed property from the object. * * If the property is not found, or it has the PERMANENT attribute, * no action is taken. * * @param index the numeric index for the property */ public void delete(int index) { checkNotSealed(null, index); accessSlot(null, index, SLOT_REMOVE); } /** * Sets the value of the named const property, creating it if need be. * * If the property was created using defineProperty, the * appropriate setter method is called. <p> * * If the property's attributes include READONLY, no action is * taken. * This method will actually set the property in the start * object. * * @param name the name of the property * @param start the object whose property is being set * @param value value to set the property to */ public void putConst(String name, Scriptable start, Object value) { if (putImpl(name, 0, start, value, READONLY)) return; if (start == this) throw Kit.codeBug(); if (start instanceof ConstProperties) ((ConstProperties)start).putConst(name, start, value); else start.put(name, start, value); } public void defineConst(String name, Scriptable start) { if (putImpl(name, 0, start, Undefined.instance, UNINITIALIZED_CONST)) return; if (start == this) throw Kit.codeBug(); if (start instanceof ConstProperties) ((ConstProperties)start).defineConst(name, start); } /** * Returns true if the named property is defined as a const on this object. * @param name * @return true if the named property is defined as a const, false * otherwise. */ public boolean isConst(String name) { Slot slot = getSlot(name, 0, SLOT_QUERY); if (slot == null) { return false; } return (slot.getAttributes() & (PERMANENT|READONLY)) == (PERMANENT|READONLY); } /** * @deprecated Use {@link #getAttributes(String name)}. The engine always * ignored the start argument. */ public final int getAttributes(String name, Scriptable start) { return getAttributes(name); } /** * @deprecated Use {@link #getAttributes(int index)}. The engine always * ignored the start argument. */ public final int getAttributes(int index, Scriptable start) { return getAttributes(index); } /** * @deprecated Use {@link #setAttributes(String name, int attributes)}. * The engine always ignored the start argument. */ public final void setAttributes(String name, Scriptable start, int attributes) { setAttributes(name, attributes); } /** * @deprecated Use {@link #setAttributes(int index, int attributes)}. * The engine always ignored the start argument. */ public void setAttributes(int index, Scriptable start, int attributes) { setAttributes(index, attributes); } /** * Get the attributes of a named property. * * The property is specified by <code>name</code> * as defined for <code>has</code>.<p> * * @param name the identifier for the property * @return the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public int getAttributes(String name) { return findAttributeSlot(name, 0, SLOT_QUERY).getAttributes(); } /** * Get the attributes of an indexed property. * * @param index the numeric index for the property * @exception EvaluatorException if the named property is not found * is not found * @return the bitset of attributes * @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public int getAttributes(int index) { return findAttributeSlot(null, index, SLOT_QUERY).getAttributes(); } /** * Set the attributes of a named property. * * The property is specified by <code>name</code> * as defined for <code>has</code>.<p> * * The possible attributes are READONLY, DONTENUM, * and PERMANENT. Combinations of attributes * are expressed by the bitwise OR of attributes. * EMPTY is the state of no attributes set. Any unused * bits are reserved for future use. * * @param name the name of the property * @param attributes the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.Scriptable#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public void setAttributes(String name, int attributes) { checkNotSealed(name, 0); findAttributeSlot(name, 0, SLOT_MODIFY).setAttributes(attributes); } /** * Set the attributes of an indexed property. * * @param index the numeric index for the property * @param attributes the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.Scriptable#has(String, Scriptable) * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public void setAttributes(int index, int attributes) { checkNotSealed(null, index); findAttributeSlot(null, index, SLOT_MODIFY).setAttributes(attributes); } /** * XXX: write docs. */ public void setGetterOrSetter(String name, int index, Callable getterOrSeter, boolean isSetter) { if (name != null && index != 0) throw new IllegalArgumentException(name); checkNotSealed(name, index); GetterSlot gslot = (GetterSlot)getSlot(name, index, SLOT_MODIFY_GETTER_SETTER); gslot.checkNotReadonly(); if (isSetter) { gslot.setter = getterOrSeter; } else { gslot.getter = getterOrSeter; } gslot.value = Undefined.instance; } /** * Get the getter or setter for a given property. Used by __lookupGetter__ * and __lookupSetter__. * * @param name Name of the object. If nonnull, index must be 0. * @param index Index of the object. If nonzero, name must be null. * @param isSetter If true, return the setter, otherwise return the getter. * @exception IllegalArgumentException if both name and index are nonnull * and nonzero respectively. * @return Null if the property does not exist. Otherwise returns either * the getter or the setter for the property, depending on * the value of isSetter (may be undefined if unset). */ public Object getGetterOrSetter(String name, int index, boolean isSetter) { if (name != null && index != 0) throw new IllegalArgumentException(name); Slot slot = getSlot(name, index, SLOT_QUERY); if (slot == null) return null; if (slot instanceof GetterSlot) { GetterSlot gslot = (GetterSlot)slot; Object result = isSetter ? gslot.setter : gslot.getter; return result != null ? result : Undefined.instance; } else return Undefined.instance; } /** * Returns whether a property is a getter or a setter * @param name property name * @param index property index * @param setter true to check for a setter, false for a getter * @return whether the property is a getter or a setter */ protected boolean isGetterOrSetter(String name, int index, boolean setter) { Slot slot = getSlot(name, index, SLOT_QUERY); if (slot instanceof GetterSlot) { if (setter && ((GetterSlot)slot).setter != null) return true; if (!setter && ((GetterSlot)slot).getter != null) return true; } return false; } void addLazilyInitializedValue(String name, int index, LazilyLoadedCtor init, int attributes) { if (name != null && index != 0) throw new IllegalArgumentException(name); checkNotSealed(name, index); GetterSlot gslot = (GetterSlot)getSlot(name, index, SLOT_MODIFY_GETTER_SETTER); gslot.setAttributes(attributes); gslot.getter = null; gslot.setter = null; gslot.value = init; } /** * Returns the prototype of the object. */ public Scriptable getPrototype() { return prototypeObject; } /** * Sets the prototype of the object. */ public void setPrototype(Scriptable m) { prototypeObject = m; } /** * Returns the parent (enclosing) scope of the object. */ public Scriptable getParentScope() { return parentScopeObject; } /** * Sets the parent (enclosing) scope of the object. */ public void setParentScope(Scriptable m) { parentScopeObject = m; } /** * Returns an array of ids for the properties of the object. * * <p>Any properties with the attribute DONTENUM are not listed. <p> * * @return an array of java.lang.Objects with an entry for every * listed property. Properties accessed via an integer index will * have a corresponding * Integer entry in the returned array. Properties accessed by * a String will have a String entry in the returned array. */ public Object[] getIds() { return getIds(false); } /** * Returns an array of ids for the properties of the object. * * <p>All properties, even those with attribute DONTENUM, are listed. <p> * * @return an array of java.lang.Objects with an entry for every * listed property. Properties accessed via an integer index will * have a corresponding * Integer entry in the returned array. Properties accessed by * a String will have a String entry in the returned array. */ public Object[] getAllIds() { return getIds(true); } /** * Implements the [[DefaultValue]] internal method. * * <p>Note that the toPrimitive conversion is a no-op for * every type other than Object, for which [[DefaultValue]] * is called. See ECMA 9.1.<p> * * A <code>hint</code> of null means "no hint". * * @param typeHint the type hint * @return the default value for the object * * See ECMA 8.6.2.6. */ public Object getDefaultValue(Class<?> typeHint) { return getDefaultValue(this, typeHint); } public static Object getDefaultValue(Scriptable object, Class<?> typeHint) { Context cx = null; for (int i=0; i < 2; i++) { boolean tryToString; if (typeHint == ScriptRuntime.StringClass) { tryToString = (i == 0); } else { tryToString = (i == 1); } String methodName; Object[] args; if (tryToString) { methodName = "toString"; args = ScriptRuntime.emptyArgs; } else { methodName = "valueOf"; args = new Object[1]; String hint; if (typeHint == null) { hint = "undefined"; } else if (typeHint == ScriptRuntime.StringClass) { hint = "string"; } else if (typeHint == ScriptRuntime.ScriptableClass) { hint = "object"; } else if (typeHint == ScriptRuntime.FunctionClass) { hint = "function"; } else if (typeHint == ScriptRuntime.BooleanClass || typeHint == Boolean.TYPE) { hint = "boolean"; } else if (typeHint == ScriptRuntime.NumberClass || typeHint == ScriptRuntime.ByteClass || typeHint == Byte.TYPE || typeHint == ScriptRuntime.ShortClass || typeHint == Short.TYPE || typeHint == ScriptRuntime.IntegerClass || typeHint == Integer.TYPE || typeHint == ScriptRuntime.FloatClass || typeHint == Float.TYPE || typeHint == ScriptRuntime.DoubleClass || typeHint == Double.TYPE) { hint = "number"; } else { throw Context.reportRuntimeError1( "msg.invalid.type", typeHint.toString()); } args[0] = hint; } Object v = getProperty(object, methodName); if (!(v instanceof Function)) continue; Function fun = (Function) v; if (cx == null) cx = Context.getContext(); v = fun.call(cx, fun.getParentScope(), object, args); if (v != null) { if (!(v instanceof Scriptable)) { return v; } if (typeHint == ScriptRuntime.ScriptableClass || typeHint == ScriptRuntime.FunctionClass) { return v; } if (tryToString && v instanceof Wrapper) { // Let a wrapped java.lang.String pass for a primitive // string. Object u = ((Wrapper)v).unwrap(); if (u instanceof String) return u; } } } // fall through to error String arg = (typeHint == null) ? "undefined" : typeHint.getName(); throw ScriptRuntime.typeError1("msg.default.value", arg); } /** * Implements the instanceof operator. * * <p>This operator has been proposed to ECMA. * * @param instance The value that appeared on the LHS of the instanceof * operator * @return true if "this" appears in value's prototype chain * */ public boolean hasInstance(Scriptable instance) { // Default for JS objects (other than Function) is to do prototype // chasing. This will be overridden in NativeFunction and non-JS // objects. return ScriptRuntime.jsDelegatesTo(instance, this); } /** * Emulate the SpiderMonkey (and Firefox) feature of allowing * custom objects to avoid detection by normal "object detection" * code patterns. This is used to implement document.all. * See https://bugzilla.mozilla.org/show_bug.cgi?id=412247. * This is an analog to JOF_DETECTING from SpiderMonkey; see * https://bugzilla.mozilla.org/show_bug.cgi?id=248549. * Other than this special case, embeddings should return false. * @return true if this object should avoid object detection * @since 1.7R1 */ public boolean avoidObjectDetection() { return false; } /** * Custom <tt>==</tt> operator. * Must return {@link Scriptable#NOT_FOUND} if this object does not * have custom equality operator for the given value, * <tt>Boolean.TRUE</tt> if this object is equivalent to <tt>value</tt>, * <tt>Boolean.FALSE</tt> if this object is not equivalent to * <tt>value</tt>. * <p> * The default implementation returns Boolean.TRUE * if <tt>this == value</tt> or {@link Scriptable#NOT_FOUND} otherwise. * It indicates that by default custom equality is available only if * <tt>value</tt> is <tt>this</tt> in which case true is returned. */ protected Object equivalentValues(Object value) { return (this == value) ? Boolean.TRUE : Scriptable.NOT_FOUND; } /** * Defines JavaScript objects from a Java class that implements Scriptable. * * If the given class has a method * <pre> * static void init(Context cx, Scriptable scope, boolean sealed);</pre> * * or its compatibility form * <pre> * static void init(Scriptable scope);</pre> * * then it is invoked and no further initialization is done.<p> * * However, if no such a method is found, then the class's constructors and * methods are used to initialize a class in the following manner.<p> * * First, the zero-parameter constructor of the class is called to * create the prototype. If no such constructor exists, * a {@link EvaluatorException} is thrown. <p> * * Next, all methods are scanned for special prefixes that indicate that they * have special meaning for defining JavaScript objects. * These special prefixes are * <ul> * <li><code>jsFunction_</code> for a JavaScript function * <li><code>jsStaticFunction_</code> for a JavaScript function that * is a property of the constructor * <li><code>jsGet_</code> for a getter of a JavaScript property * <li><code>jsSet_</code> for a setter of a JavaScript property * <li><code>jsConstructor</code> for a JavaScript function that * is the constructor * </ul><p> * * If the method's name begins with "jsFunction_", a JavaScript function * is created with a name formed from the rest of the Java method name * following "jsFunction_". So a Java method named "jsFunction_foo" will * define a JavaScript method "foo". Calling this JavaScript function * will cause the Java method to be called. The parameters of the method * must be of number and types as defined by the FunctionObject class. * The JavaScript function is then added as a property * of the prototype. <p> * * If the method's name begins with "jsStaticFunction_", it is handled * similarly except that the resulting JavaScript function is added as a * property of the constructor object. The Java method must be static. * * If the method's name begins with "jsGet_" or "jsSet_", the method is * considered to define a property. Accesses to the defined property * will result in calls to these getter and setter methods. If no * setter is defined, the property is defined as READONLY.<p> * * If the method's name is "jsConstructor", the method is * considered to define the body of the constructor. Only one * method of this name may be defined. * If no method is found that can serve as constructor, a Java * constructor will be selected to serve as the JavaScript * constructor in the following manner. If the class has only one * Java constructor, that constructor is used to define * the JavaScript constructor. If the the class has two constructors, * one must be the zero-argument constructor (otherwise an * {@link EvaluatorException} would have already been thrown * when the prototype was to be created). In this case * the Java constructor with one or more parameters will be used * to define the JavaScript constructor. If the class has three * or more constructors, an {@link EvaluatorException} * will be thrown.<p> * * Finally, if there is a method * <pre> * static void finishInit(Scriptable scope, FunctionObject constructor, * Scriptable prototype)</pre> * * it will be called to finish any initialization. The <code>scope</code> * argument will be passed, along with the newly created constructor and * the newly created prototype.<p> * * @param scope The scope in which to define the constructor. * @param clazz The Java class to use to define the JavaScript objects * and properties. * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @see org.mozilla.javascript.Function * @see org.mozilla.javascript.FunctionObject * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject * #defineProperty(String, Class, int) */ public static <T extends Scriptable> void defineClass( Scriptable scope, Class<T> clazz) throws IllegalAccessException, InstantiationException, InvocationTargetException { defineClass(scope, clazz, false, false); } /** * Defines JavaScript objects from a Java class, optionally * allowing sealing. * * Similar to <code>defineClass(Scriptable scope, Class clazz)</code> * except that sealing is allowed. An object that is sealed cannot have * properties added or removed. Note that sealing is not allowed in * the current ECMA/ISO language specification, but is likely for * the next version. * * @param scope The scope in which to define the constructor. * @param clazz The Java class to use to define the JavaScript objects * and properties. The class must implement Scriptable. * @param sealed Whether or not to create sealed standard objects that * cannot be modified. * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @since 1.4R3 */ public static <T extends Scriptable> void defineClass( Scriptable scope, Class<T> clazz, boolean sealed) throws IllegalAccessException, InstantiationException, InvocationTargetException { defineClass(scope, clazz, sealed, false); } /** * Defines JavaScript objects from a Java class, optionally * allowing sealing and mapping of Java inheritance to JavaScript * prototype-based inheritance. * * Similar to <code>defineClass(Scriptable scope, Class clazz)</code> * except that sealing and inheritance mapping are allowed. An object * that is sealed cannot have properties added or removed. Note that * sealing is not allowed in the current ECMA/ISO language specification, * but is likely for the next version. * * @param scope The scope in which to define the constructor. * @param clazz The Java class to use to define the JavaScript objects * and properties. The class must implement Scriptable. * @param sealed Whether or not to create sealed standard objects that * cannot be modified. * @param mapInheritance Whether or not to map Java inheritance to * JavaScript prototype-based inheritance. * @return the class name for the prototype of the specified class * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @since 1.6R2 */ public static <T extends Scriptable> String defineClass( Scriptable scope, Class<T> clazz, boolean sealed, boolean mapInheritance) throws IllegalAccessException, InstantiationException, InvocationTargetException { BaseFunction ctor = buildClassCtor(scope, clazz, sealed, mapInheritance); if (ctor == null) return null; String name = ctor.getClassPrototype().getClassName(); defineProperty(scope, name, ctor, ScriptableObject.DONTENUM); return name; } static <T extends Scriptable> BaseFunction buildClassCtor( Scriptable scope, Class<T> clazz, boolean sealed, boolean mapInheritance) throws IllegalAccessException, InstantiationException, InvocationTargetException { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < methods.length; i++) { Method method = methods[i]; if (!method.getName().equals("init")) continue; Class<?>[] parmTypes = method.getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ContextClass && parmTypes[1] == ScriptRuntime.ScriptableClass && parmTypes[2] == Boolean.TYPE && Modifier.isStatic(method.getModifiers())) { Object args[] = { Context.getContext(), scope, sealed ? Boolean.TRUE : Boolean.FALSE }; method.invoke(null, args); return null; } if (parmTypes.length == 1 && parmTypes[0] == ScriptRuntime.ScriptableClass && Modifier.isStatic(method.getModifiers())) { Object args[] = { scope }; method.invoke(null, args); return null; } } // If we got here, there isn't an "init" method with the right // parameter types. Constructor<?>[] ctors = clazz.getConstructors(); Constructor<?> protoCtor = null; for (int i=0; i < ctors.length; i++) { if (ctors[i].getParameterTypes().length == 0) { protoCtor = ctors[i]; break; } } if (protoCtor == null) { throw Context.reportRuntimeError1( "msg.zero.arg.ctor", clazz.getName()); } Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs); String className = proto.getClassName(); // Set the prototype's prototype, trying to map Java inheritance to JS // prototype-based inheritance if requested to do so. Scriptable superProto = null; if (mapInheritance) { Class<? super T> superClass = clazz.getSuperclass(); if (ScriptRuntime.ScriptableClass.isAssignableFrom(superClass) && !Modifier.isAbstract(superClass.getModifiers())) { Class<? extends Scriptable> superScriptable = extendsScriptable(superClass); String name = ScriptableObject.defineClass(scope, superScriptable, sealed, mapInheritance); if (name != null) { superProto = ScriptableObject.getClassPrototype(scope, name); } } } if (superProto == null) { superProto = ScriptableObject.getObjectPrototype(scope); } proto.setPrototype(superProto); // Find out whether there are any methods that begin with // "js". If so, then only methods that begin with special // prefixes will be defined as JavaScript entities. final String functionPrefix = "jsFunction_"; final String staticFunctionPrefix = "jsStaticFunction_"; final String getterPrefix = "jsGet_"; final String setterPrefix = "jsSet_"; final String ctorName = "jsConstructor"; Member ctorMember = FunctionObject.findSingleMethod(methods, ctorName); if (ctorMember == null) { if (ctors.length == 1) { ctorMember = ctors[0]; } else if (ctors.length == 2) { if (ctors[0].getParameterTypes().length == 0) ctorMember = ctors[1]; else if (ctors[1].getParameterTypes().length == 0) ctorMember = ctors[0]; } if (ctorMember == null) { throw Context.reportRuntimeError1( "msg.ctor.multiple.parms", clazz.getName()); } } FunctionObject ctor = new FunctionObject(className, ctorMember, scope); if (ctor.isVarArgsMethod()) { throw Context.reportRuntimeError1 ("msg.varargs.ctor", ctorMember.getName()); } ctor.initAsConstructor(scope, proto); Method finishInit = null; HashSet<String> names = new HashSet<String>(methods.length); for (int i=0; i < methods.length; i++) { if (methods[i] == ctorMember) { continue; } String name = methods[i].getName(); if (name.equals("finishInit")) { Class<?>[] parmTypes = methods[i].getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ScriptableClass && parmTypes[1] == FunctionObject.class && parmTypes[2] == ScriptRuntime.ScriptableClass && Modifier.isStatic(methods[i].getModifiers())) { finishInit = methods[i]; continue; } } // ignore any compiler generated methods. if (name.indexOf('$') != -1) continue; if (name.equals(ctorName)) continue; String prefix = null; if (name.startsWith(functionPrefix)) { prefix = functionPrefix; } else if (name.startsWith(staticFunctionPrefix)) { prefix = staticFunctionPrefix; if (!Modifier.isStatic(methods[i].getModifiers())) { throw Context.reportRuntimeError( "jsStaticFunction must be used with static method."); } } else if (name.startsWith(getterPrefix)) { prefix = getterPrefix; - } else if (name.startsWith(setterPrefix)) { - prefix = setterPrefix; } else { + // note that setterPrefix is among the unhandled names here - + // we deal with that when we see the getter continue; } String propName = name.substring(prefix.length()); if (names.contains(propName)) { throw Context.reportRuntimeError2("duplicate.defineClass.name", name, propName); } names.add(propName); name = name.substring(prefix.length()); - if (prefix == setterPrefix) - continue; // deal with set when we see get if (prefix == getterPrefix) { if (!(proto instanceof ScriptableObject)) { throw Context.reportRuntimeError2( "msg.extend.scriptable", proto.getClass().toString(), name); } Method setter = FunctionObject.findSingleMethod( methods, setterPrefix + name); int attr = ScriptableObject.PERMANENT | ScriptableObject.DONTENUM | (setter != null ? 0 : ScriptableObject.READONLY); ((ScriptableObject) proto).defineProperty(name, null, methods[i], setter, attr); continue; } FunctionObject f = new FunctionObject(name, methods[i], proto); if (f.isVarArgsConstructor()) { throw Context.reportRuntimeError1 ("msg.varargs.fun", ctorMember.getName()); } Scriptable dest = prefix == staticFunctionPrefix ? ctor : proto; defineProperty(dest, name, f, DONTENUM); if (sealed) { f.sealObject(); } } // Call user code to complete initialization if necessary. if (finishInit != null) { Object[] finishArgs = { scope, ctor, proto }; finishInit.invoke(null, finishArgs); } // Seal the object if necessary. if (sealed) { ctor.sealObject(); if (proto instanceof ScriptableObject) { ((ScriptableObject) proto).sealObject(); } } return ctor; } @SuppressWarnings({"unchecked"}) private static <T extends Scriptable> Class<T> extendsScriptable(Class<?> c) { if (ScriptRuntime.ScriptableClass.isAssignableFrom(c)) return (Class<T>) c; return null; } /** * Define a JavaScript property. * * Creates the property with an initial value and sets its attributes. * * @param propertyName the name of the property to define. * @param value the initial value of the property * @param attributes the attributes of the JavaScript property * @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object) */ public void defineProperty(String propertyName, Object value, int attributes) { checkNotSealed(propertyName, 0); put(propertyName, this, value); setAttributes(propertyName, attributes); } /** * Utility method to add properties to arbitrary Scriptable object. * If destination is instance of ScriptableObject, calls * defineProperty there, otherwise calls put in destination * ignoring attributes */ public static void defineProperty(Scriptable destination, String propertyName, Object value, int attributes) { if (!(destination instanceof ScriptableObject)) { destination.put(propertyName, destination, value); return; } ScriptableObject so = (ScriptableObject)destination; so.defineProperty(propertyName, value, attributes); } /** * Utility method to add properties to arbitrary Scriptable object. * If destination is instance of ScriptableObject, calls * defineProperty there, otherwise calls put in destination * ignoring attributes */ public static void defineConstProperty(Scriptable destination, String propertyName) { if (destination instanceof ConstProperties) { ConstProperties cp = (ConstProperties)destination; cp.defineConst(propertyName, destination); } else defineProperty(destination, propertyName, Undefined.instance, CONST); } /** * Define a JavaScript property with getter and setter side effects. * * If the setter is not found, the attribute READONLY is added to * the given attributes. <p> * * The getter must be a method with zero parameters, and the setter, if * found, must be a method with one parameter.<p> * * @param propertyName the name of the property to define. This name * also affects the name of the setter and getter * to search for. If the propertyId is "foo", then * <code>clazz</code> will be searched for "getFoo" * and "setFoo" methods. * @param clazz the Java class to search for the getter and setter * @param attributes the attributes of the JavaScript property * @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object) */ public void defineProperty(String propertyName, Class<?> clazz, int attributes) { int length = propertyName.length(); if (length == 0) throw new IllegalArgumentException(); char[] buf = new char[3 + length]; propertyName.getChars(0, length, buf, 3); buf[3] = Character.toUpperCase(buf[3]); buf[0] = 'g'; buf[1] = 'e'; buf[2] = 't'; String getterName = new String(buf); buf[0] = 's'; String setterName = new String(buf); Method[] methods = FunctionObject.getMethodList(clazz); Method getter = FunctionObject.findSingleMethod(methods, getterName); Method setter = FunctionObject.findSingleMethod(methods, setterName); if (setter == null) attributes |= ScriptableObject.READONLY; defineProperty(propertyName, null, getter, setter == null ? null : setter, attributes); } /** * Define a JavaScript property. * * Use this method only if you wish to define getters and setters for * a given property in a ScriptableObject. To create a property without * special getter or setter side effects, use * <code>defineProperty(String,int)</code>. * * If <code>setter</code> is null, the attribute READONLY is added to * the given attributes.<p> * * Several forms of getters or setters are allowed. In all cases the * type of the value parameter can be any one of the following types: * Object, String, boolean, Scriptable, byte, short, int, long, float, * or double. The runtime will perform appropriate conversions based * upon the type of the parameter (see description in FunctionObject). * The first forms are nonstatic methods of the class referred to * by 'this': * <pre> * Object getFoo(); * void setFoo(SomeType value);</pre> * Next are static methods that may be of any class; the object whose * property is being accessed is passed in as an extra argument: * <pre> * static Object getFoo(Scriptable obj); * static void setFoo(Scriptable obj, SomeType value);</pre> * Finally, it is possible to delegate to another object entirely using * the <code>delegateTo</code> parameter. In this case the methods are * nonstatic methods of the class delegated to, and the object whose * property is being accessed is passed in as an extra argument: * <pre> * Object getFoo(Scriptable obj); * void setFoo(Scriptable obj, SomeType value);</pre> * * @param propertyName the name of the property to define. * @param delegateTo an object to call the getter and setter methods on, * or null, depending on the form used above. * @param getter the method to invoke to get the value of the property * @param setter the method to invoke to set the value of the property * @param attributes the attributes of the JavaScript property */ public void defineProperty(String propertyName, Object delegateTo, Method getter, Method setter, int attributes) { MemberBox getterBox = null; if (getter != null) { getterBox = new MemberBox(getter); boolean delegatedForm; if (!Modifier.isStatic(getter.getModifiers())) { delegatedForm = (delegateTo != null); getterBox.delegateTo = delegateTo; } else { delegatedForm = true; // Ignore delegateTo for static getter but store // non-null delegateTo indicator. getterBox.delegateTo = Void.TYPE; } String errorId = null; Class<?>[] parmTypes = getter.getParameterTypes(); if (parmTypes.length == 0) { if (delegatedForm) { errorId = "msg.obj.getter.parms"; } } else if (parmTypes.length == 1) { Object argType = parmTypes[0]; // Allow ScriptableObject for compatibility if (!(argType == ScriptRuntime.ScriptableClass || argType == ScriptRuntime.ScriptableObjectClass)) { errorId = "msg.bad.getter.parms"; } else if (!delegatedForm) { errorId = "msg.bad.getter.parms"; } } else { errorId = "msg.bad.getter.parms"; } if (errorId != null) { throw Context.reportRuntimeError1(errorId, getter.toString()); } } MemberBox setterBox = null; if (setter != null) { if (setter.getReturnType() != Void.TYPE) throw Context.reportRuntimeError1("msg.setter.return", setter.toString()); setterBox = new MemberBox(setter); boolean delegatedForm; if (!Modifier.isStatic(setter.getModifiers())) { delegatedForm = (delegateTo != null); setterBox.delegateTo = delegateTo; } else { delegatedForm = true; // Ignore delegateTo for static setter but store // non-null delegateTo indicator. setterBox.delegateTo = Void.TYPE; } String errorId = null; Class<?>[] parmTypes = setter.getParameterTypes(); if (parmTypes.length == 1) { if (delegatedForm) { errorId = "msg.setter2.expected"; } } else if (parmTypes.length == 2) { Object argType = parmTypes[0]; // Allow ScriptableObject for compatibility if (!(argType == ScriptRuntime.ScriptableClass || argType == ScriptRuntime.ScriptableObjectClass)) { errorId = "msg.setter2.parms"; } else if (!delegatedForm) { errorId = "msg.setter1.parms"; } } else { errorId = "msg.setter.parms"; } if (errorId != null) { throw Context.reportRuntimeError1(errorId, setter.toString()); } } GetterSlot gslot = (GetterSlot)getSlot(propertyName, 0, SLOT_MODIFY_GETTER_SETTER); gslot.setAttributes(attributes); gslot.getter = getterBox; gslot.setter = setterBox; } /** * Search for names in a class, adding the resulting methods * as properties. * * <p> Uses reflection to find the methods of the given names. Then * FunctionObjects are constructed from the methods found, and * are added to this object as properties with the given names. * * @param names the names of the Methods to add as function properties * @param clazz the class to search for the Methods * @param attributes the attributes of the new properties * @see org.mozilla.javascript.FunctionObject */ public void defineFunctionProperties(String[] names, Class<?> clazz, int attributes) { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < names.length; i++) { String name = names[i]; Method m = FunctionObject.findSingleMethod(methods, name); if (m == null) { throw Context.reportRuntimeError2( "msg.method.not.found", name, clazz.getName()); } FunctionObject f = new FunctionObject(name, m, this); defineProperty(name, f, attributes); } } /** * Get the Object.prototype property. * See ECMA 15.2.4. */ public static Scriptable getObjectPrototype(Scriptable scope) { return getClassPrototype(scope, "Object"); } /** * Get the Function.prototype property. * See ECMA 15.3.4. */ public static Scriptable getFunctionPrototype(Scriptable scope) { return getClassPrototype(scope, "Function"); } /** * Get the prototype for the named class. * * For example, <code>getClassPrototype(s, "Date")</code> will first * walk up the parent chain to find the outermost scope, then will * search that scope for the Date constructor, and then will * return Date.prototype. If any of the lookups fail, or * the prototype is not a JavaScript object, then null will * be returned. * * @param scope an object in the scope chain * @param className the name of the constructor * @return the prototype for the named class, or null if it * cannot be found. */ public static Scriptable getClassPrototype(Scriptable scope, String className) { scope = getTopLevelScope(scope); Object ctor = getProperty(scope, className); Object proto; if (ctor instanceof BaseFunction) { proto = ((BaseFunction)ctor).getPrototypeProperty(); } else if (ctor instanceof Scriptable) { Scriptable ctorObj = (Scriptable)ctor; proto = ctorObj.get("prototype", ctorObj); } else { return null; } if (proto instanceof Scriptable) { return (Scriptable)proto; } return null; } /** * Get the global scope. * * <p>Walks the parent scope chain to find an object with a null * parent scope (the global object). * * @param obj a JavaScript object * @return the corresponding global scope */ public static Scriptable getTopLevelScope(Scriptable obj) { for (;;) { Scriptable parent = obj.getParentScope(); if (parent == null) { return obj; } obj = parent; } } /** * Seal this object. * * A sealed object may not have properties added or removed. Once * an object is sealed it may not be unsealed. * * @since 1.4R3 */ public synchronized void sealObject() { if (count >= 0) { count = ~count; } } /** * Return true if this object is sealed. * * It is an error to attempt to add or remove properties to * a sealed object. * * @return true if sealed, false otherwise. * @since 1.4R3 */ public final boolean isSealed() { return count < 0; } private void checkNotSealed(String name, int index) { if (!isSealed()) return; String str = (name != null) ? name : Integer.toString(index); throw Context.reportRuntimeError1("msg.modify.sealed", str); } /** * Gets a named property from an object or any object in its prototype chain. * <p> * Searches the prototype chain for a property named <code>name</code>. * <p> * @param obj a JavaScript object * @param name a property name * @return the value of a property with name <code>name</code> found in * <code>obj</code> or any object in its prototype chain, or * <code>Scriptable.NOT_FOUND</code> if not found * @since 1.5R2 */ public static Object getProperty(Scriptable obj, String name) { Scriptable start = obj; Object result; do { result = obj.get(name, start); if (result != Scriptable.NOT_FOUND) break; obj = obj.getPrototype(); } while (obj != null); return result; } /** * Gets an indexed property from an object or any object in its prototype chain. * <p> * Searches the prototype chain for a property with integral index * <code>index</code>. Note that if you wish to look for properties with numerical * but non-integral indicies, you should use getProperty(Scriptable,String) with * the string value of the index. * <p> * @param obj a JavaScript object * @param index an integral index * @return the value of a property with index <code>index</code> found in * <code>obj</code> or any object in its prototype chain, or * <code>Scriptable.NOT_FOUND</code> if not found * @since 1.5R2 */ public static Object getProperty(Scriptable obj, int index) { Scriptable start = obj; Object result; do { result = obj.get(index, start); if (result != Scriptable.NOT_FOUND) break; obj = obj.getPrototype(); } while (obj != null); return result; } /** * Returns whether a named property is defined in an object or any object * in its prototype chain. * <p> * Searches the prototype chain for a property named <code>name</code>. * <p> * @param obj a JavaScript object * @param name a property name * @return the true if property was found * @since 1.5R2 */ public static boolean hasProperty(Scriptable obj, String name) { return null != getBase(obj, name); } /** * If hasProperty(obj, name) would return true, then if the property that * was found is compatible with the new property, this method just returns. * If the property is not compatible, then an exception is thrown. * * A property redefinition is incompatible if the first definition was a * const declaration or if this one is. They are compatible only if neither * was const. */ public static void redefineProperty(Scriptable obj, String name, boolean isConst) { Scriptable base = getBase(obj, name); if (base == null) return; if (base instanceof ConstProperties) { ConstProperties cp = (ConstProperties)base; if (cp.isConst(name)) throw Context.reportRuntimeError1("msg.const.redecl", name); } if (isConst) throw Context.reportRuntimeError1("msg.var.redecl", name); } /** * Returns whether an indexed property is defined in an object or any object * in its prototype chain. * <p> * Searches the prototype chain for a property with index <code>index</code>. * <p> * @param obj a JavaScript object * @param index a property index * @return the true if property was found * @since 1.5R2 */ public static boolean hasProperty(Scriptable obj, int index) { return null != getBase(obj, index); } /** * Puts a named property in an object or in an object in its prototype chain. * <p> * Searches for the named property in the prototype chain. If it is found, * the value of the property in <code>obj</code> is changed through a call * to {@link Scriptable#put(String, Scriptable, Object)} on the * prototype passing <code>obj</code> as the <code>start</code> argument. * This allows the prototype to veto the property setting in case the * prototype defines the property with [[ReadOnly]] attribute. If the * property is not found, it is added in <code>obj</code>. * @param obj a JavaScript object * @param name a property name * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putProperty(Scriptable obj, String name, Object value) { Scriptable base = getBase(obj, name); if (base == null) base = obj; base.put(name, obj, value); } /** * Puts a named property in an object or in an object in its prototype chain. * <p> * Searches for the named property in the prototype chain. If it is found, * the value of the property in <code>obj</code> is changed through a call * to {@link Scriptable#put(String, Scriptable, Object)} on the * prototype passing <code>obj</code> as the <code>start</code> argument. * This allows the prototype to veto the property setting in case the * prototype defines the property with [[ReadOnly]] attribute. If the * property is not found, it is added in <code>obj</code>. * @param obj a JavaScript object * @param name a property name * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putConstProperty(Scriptable obj, String name, Object value) { Scriptable base = getBase(obj, name); if (base == null) base = obj; if (base instanceof ConstProperties) ((ConstProperties)base).putConst(name, obj, value); } /** * Puts an indexed property in an object or in an object in its prototype chain. * <p> * Searches for the indexed property in the prototype chain. If it is found, * the value of the property in <code>obj</code> is changed through a call * to {@link Scriptable#put(int, Scriptable, Object)} on the prototype * passing <code>obj</code> as the <code>start</code> argument. This allows * the prototype to veto the property setting in case the prototype defines * the property with [[ReadOnly]] attribute. If the property is not found, * it is added in <code>obj</code>. * @param obj a JavaScript object * @param index a property index * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putProperty(Scriptable obj, int index, Object value) { Scriptable base = getBase(obj, index); if (base == null) base = obj; base.put(index, obj, value); } /** * Removes the property from an object or its prototype chain. * <p> * Searches for a property with <code>name</code> in obj or * its prototype chain. If it is found, the object's delete * method is called. * @param obj a JavaScript object * @param name a property name * @return true if the property doesn't exist or was successfully removed * @since 1.5R2 */ public static boolean deleteProperty(Scriptable obj, String name) { Scriptable base = getBase(obj, name); if (base == null) return true; base.delete(name); return !base.has(name, obj); } /** * Removes the property from an object or its prototype chain. * <p> * Searches for a property with <code>index</code> in obj or * its prototype chain. If it is found, the object's delete * method is called. * @param obj a JavaScript object * @param index a property index * @return true if the property doesn't exist or was successfully removed * @since 1.5R2 */ public static boolean deleteProperty(Scriptable obj, int index) { Scriptable base = getBase(obj, index); if (base == null) return true; base.delete(index); return !base.has(index, obj); } /** * Returns an array of all ids from an object and its prototypes. * <p> * @param obj a JavaScript object * @return an array of all ids from all object in the prototype chain. * If a given id occurs multiple times in the prototype chain, * it will occur only once in this list. * @since 1.5R2 */ public static Object[] getPropertyIds(Scriptable obj) { if (obj == null) { return ScriptRuntime.emptyArgs; } Object[] result = obj.getIds(); ObjToIntMap map = null; for (;;) { obj = obj.getPrototype(); if (obj == null) { break; } Object[] ids = obj.getIds(); if (ids.length == 0) { continue; } if (map == null) { if (result.length == 0) { result = ids; continue; } map = new ObjToIntMap(result.length + ids.length); for (int i = 0; i != result.length; ++i) { map.intern(result[i]); } result = null; // Allow to GC the result } for (int i = 0; i != ids.length; ++i) { map.intern(ids[i]); } } if (map != null) { result = map.getKeys(); } return result; } /** * Call a method of an object. * @param obj the JavaScript object * @param methodName the name of the function property * @param args the arguments for the call * * @see Context#getCurrentContext() */ public static Object callMethod(Scriptable obj, String methodName, Object[] args) { return callMethod(null, obj, methodName, args); } /** * Call a method of an object. * @param cx the Context object associated with the current thread. * @param obj the JavaScript object * @param methodName the name of the function property * @param args the arguments for the call */ public static Object callMethod(Context cx, Scriptable obj, String methodName, Object[] args) { Object funObj = getProperty(obj, methodName); if (!(funObj instanceof Function)) { throw ScriptRuntime.notFunctionError(obj, methodName); } Function fun = (Function)funObj; // XXX: What should be the scope when calling funObj? // The following favor scope stored in the object on the assumption // that is more useful especially under dynamic scope setup. // An alternative is to check for dynamic scope flag // and use ScriptableObject.getTopLevelScope(fun) if the flag is not // set. But that require access to Context and messy code // so for now it is not checked. Scriptable scope = ScriptableObject.getTopLevelScope(obj); if (cx != null) { return fun.call(cx, scope, obj, args); } else { return Context.call(null, fun, scope, obj, args); } } private static Scriptable getBase(Scriptable obj, String name) { do { if (obj.has(name, obj)) break; obj = obj.getPrototype(); } while(obj != null); return obj; } private static Scriptable getBase(Scriptable obj, int index) { do { if (obj.has(index, obj)) break; obj = obj.getPrototype(); } while(obj != null); return obj; } /** * Get arbitrary application-specific value associated with this object. * @param key key object to select particular value. * @see #associateValue(Object key, Object value) */ public final Object getAssociatedValue(Object key) { Map<Object,Object> h = associatedValues; if (h == null) return null; return h.get(key); } /** * Get arbitrary application-specific value associated with the top scope * of the given scope. * The method first calls {@link #getTopLevelScope(Scriptable scope)} * and then searches the prototype chain of the top scope for the first * object containing the associated value with the given key. * * @param scope the starting scope. * @param key key object to select particular value. * @see #getAssociatedValue(Object key) */ public static Object getTopScopeValue(Scriptable scope, Object key) { scope = ScriptableObject.getTopLevelScope(scope); for (;;) { if (scope instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject)scope; Object value = so.getAssociatedValue(key); if (value != null) { return value; } } scope = scope.getPrototype(); if (scope == null) { return null; } } } /** * Associate arbitrary application-specific value with this object. * Value can only be associated with the given object and key only once. * The method ignores any subsequent attempts to change the already * associated value. * <p> The associated values are not serialized. * @param key key object to select particular value. * @param value the value to associate * @return the passed value if the method is called first time for the * given key or old value for any subsequent calls. * @see #getAssociatedValue(Object key) */ public synchronized final Object associateValue(Object key, Object value) { if (value == null) throw new IllegalArgumentException(); Map<Object,Object> h = associatedValues; if (h == null) { h = associatedValues; if (h == null) { h = new HashMap<Object,Object>(); associatedValues = h; } } return Kit.initHash(h, key, value); } private Object getImpl(String name, int index, Scriptable start) { Slot slot = getSlot(name, index, SLOT_QUERY); if (slot == null) { return Scriptable.NOT_FOUND; } if (!(slot instanceof GetterSlot)) { return slot.value; } Object getterObj = ((GetterSlot)slot).getter; if (getterObj != null) { if (getterObj instanceof MemberBox) { MemberBox nativeGetter = (MemberBox)getterObj; Object getterThis; Object[] args; if (nativeGetter.delegateTo == null) { getterThis = start; args = ScriptRuntime.emptyArgs; } else { getterThis = nativeGetter.delegateTo; args = new Object[] { start }; } return nativeGetter.invoke(getterThis, args); } else { Function f = (Function)getterObj; Context cx = Context.getContext(); return f.call(cx, f.getParentScope(), start, ScriptRuntime.emptyArgs); } } Object value = slot.value; if (value instanceof LazilyLoadedCtor) { LazilyLoadedCtor initializer = (LazilyLoadedCtor)value; try { initializer.init(); } finally { value = initializer.getValue(); slot.value = value; } } return value; } /** * * @param name * @param index * @param start * @param value * @param constFlag EMPTY means normal put. UNINITIALIZED_CONST means * defineConstProperty. READONLY means const initialization expression. * @return false if this != start and no slot was found. true if this == start * or this != start and a READONLY slot was found. */ private boolean putImpl(String name, int index, Scriptable start, Object value, int constFlag) { Slot slot; if (this != start) { slot = getSlot(name, index, SLOT_QUERY); if (slot == null) { return false; } } else { checkNotSealed(name, index); // either const hoisted declaration or initialization if (constFlag != EMPTY) { slot = getSlot(name, index, SLOT_MODIFY_CONST); int attr = slot.getAttributes(); if ((attr & READONLY) == 0) throw Context.reportRuntimeError1("msg.var.redecl", name); if ((attr & UNINITIALIZED_CONST) != 0) { slot.value = value; // clear the bit on const initialization if (constFlag != UNINITIALIZED_CONST) slot.setAttributes(attr & ~UNINITIALIZED_CONST); } return true; } slot = getSlot(name, index, SLOT_MODIFY); } if ((slot.getAttributes() & READONLY) != 0) return true; if (slot instanceof GetterSlot) { Object setterObj = ((GetterSlot)slot).setter; if (setterObj == null) { // Odd case: Assignment to a property with only a getter // defined. The assignment cancels out the getter. ((GetterSlot)slot).getter = null; } else { Context cx = Context.getContext(); if (setterObj instanceof MemberBox) { MemberBox nativeSetter = (MemberBox)setterObj; Class<?> pTypes[] = nativeSetter.argTypes; // XXX: cache tag since it is already calculated in // defineProperty ? Class<?> valueType = pTypes[pTypes.length - 1]; int tag = FunctionObject.getTypeTag(valueType); Object actualArg = FunctionObject.convertArg(cx, start, value, tag); Object setterThis; Object[] args; if (nativeSetter.delegateTo == null) { setterThis = start; args = new Object[] { actualArg }; } else { setterThis = nativeSetter.delegateTo; args = new Object[] { start, actualArg }; } nativeSetter.invoke(setterThis, args); } else { Function f = (Function)setterObj; f.call(cx, f.getParentScope(), start, new Object[] { value }); } return true; } } if (this == start) { slot.value = value; return true; } else { return false; } } private Slot findAttributeSlot(String name, int index, int accessType) { Slot slot = getSlot(name, index, accessType); if (slot == null) { String str = (name != null ? name : Integer.toString(index)); throw Context.reportRuntimeError1("msg.prop.not.found", str); } return slot; } /** * Locate the slot with given name or index. * * @param name property name or null if slot holds spare array index. * @param index index or 0 if slot holds property name. */ private Slot getSlot(String name, int index, int accessType) { Slot slot; // Query last access cache and check that it was not deleted. lastAccessCheck: { slot = lastAccess; if (name != null) { if (name != slot.name) break lastAccessCheck; // No String.equals here as successful slot search update // name object with fresh reference of the same string. } else { if (slot.name != null || index != slot.indexOrHash) break lastAccessCheck; } if (slot.wasDeleted) break lastAccessCheck; if (accessType == SLOT_MODIFY_GETTER_SETTER && !(slot instanceof GetterSlot)) break lastAccessCheck; return slot; } slot = accessSlot(name, index, accessType); if (slot != null) { // Update the cache lastAccess = slot; } return slot; } private Slot accessSlot(String name, int index, int accessType) { int indexOrHash = (name != null ? name.hashCode() : index); if (accessType == SLOT_QUERY || accessType == SLOT_MODIFY || accessType == SLOT_MODIFY_CONST || accessType == SLOT_MODIFY_GETTER_SETTER) { // Check the hashtable without using synchronization Slot[] slotsLocalRef = slots; // Get stable local reference if (slotsLocalRef == null) { if (accessType == SLOT_QUERY) return null; } else { int tableSize = slotsLocalRef.length; int slotIndex = getSlotIndex(tableSize, indexOrHash); Slot slot = slotsLocalRef[slotIndex]; while (slot != null) { String sname = slot.name; if (sname != null) { if (sname == name) break; if (name != null && indexOrHash == slot.indexOrHash) { if (name.equals(sname)) { // This will avoid calling String.equals when // slot is accessed with same string object // next time. slot.name = name; break; } } } else if (name == null && indexOrHash == slot.indexOrHash) { break; } slot = slot.next; } if (accessType == SLOT_QUERY) { return slot; } else if (accessType == SLOT_MODIFY) { if (slot != null) return slot; } else if (accessType == SLOT_MODIFY_GETTER_SETTER) { if (slot instanceof GetterSlot) return slot; } else if (accessType == SLOT_MODIFY_CONST) { if (slot != null) return slot; } } // A new slot has to be inserted or the old has to be replaced // by GetterSlot. Time to synchronize. synchronized (this) { // Refresh local ref if another thread triggered grow slotsLocalRef = slots; int insertPos; if (count == 0) { // Always throw away old slots if any on empty insert slotsLocalRef = new Slot[5]; slots = slotsLocalRef; insertPos = getSlotIndex(slotsLocalRef.length, indexOrHash); } else { int tableSize = slotsLocalRef.length; insertPos = getSlotIndex(tableSize, indexOrHash); Slot prev = slotsLocalRef[insertPos]; Slot slot = prev; while (slot != null) { if (slot.indexOrHash == indexOrHash && (slot.name == name || (name != null && name.equals(slot.name)))) { break; } prev = slot; slot = slot.next; } if (slot != null) { // Another thread just added a slot with same // name/index before this one entered synchronized // block. This is a race in application code and // probably indicates bug there. But for the hashtable // implementation it is harmless with the only // complication is the need to replace the added slot // if we need GetterSlot and the old one is not. if (accessType == SLOT_MODIFY_GETTER_SETTER && !(slot instanceof GetterSlot)) { GetterSlot newSlot = new GetterSlot(name, indexOrHash, slot.getAttributes()); newSlot.value = slot.value; newSlot.next = slot.next; // add new slot to linked list if (lastAdded != null) lastAdded.orderedNext = newSlot; if (firstAdded == null) firstAdded = newSlot; lastAdded = newSlot; // add new slot to hash table if (prev == slot) { slotsLocalRef[insertPos] = newSlot; } else { prev.next = newSlot; } // other housekeeping slot.wasDeleted = true; slot.value = null; slot.name = null; if (slot == lastAccess) { lastAccess = REMOVED; } slot = newSlot; } else if (accessType == SLOT_MODIFY_CONST) { return null; } return slot; } // Check if the table is not too full before inserting. if (4 * (count + 1) > 3 * slotsLocalRef.length) { slotsLocalRef = new Slot[slotsLocalRef.length * 2 + 1]; copyTable(slots, slotsLocalRef, count); slots = slotsLocalRef; insertPos = getSlotIndex(slotsLocalRef.length, indexOrHash); } } Slot newSlot = (accessType == SLOT_MODIFY_GETTER_SETTER ? new GetterSlot(name, indexOrHash, 0) : new Slot(name, indexOrHash, 0)); if (accessType == SLOT_MODIFY_CONST) newSlot.setAttributes(CONST); ++count; // add new slot to linked list if (lastAdded != null) lastAdded.orderedNext = newSlot; if (firstAdded == null) firstAdded = newSlot; lastAdded = newSlot; // add new slot to hash table, return it addKnownAbsentSlot(slotsLocalRef, newSlot, insertPos); return newSlot; } } else if (accessType == SLOT_REMOVE) { synchronized (this) { Slot[] slotsLocalRef = slots; if (count != 0) { int tableSize = slots.length; int slotIndex = getSlotIndex(tableSize, indexOrHash); Slot prev = slotsLocalRef[slotIndex]; Slot slot = prev; while (slot != null) { if (slot.indexOrHash == indexOrHash && (slot.name == name || (name != null && name.equals(slot.name)))) { break; } prev = slot; slot = slot.next; } if (slot != null && (slot.getAttributes() & PERMANENT) == 0) { count--; // remove slot from hash table if (prev == slot) { slotsLocalRef[slotIndex] = slot.next; } else { prev.next = slot.next; } // Mark the slot as removed. It is still referenced // from the order-added linked list, but will be // cleaned up later slot.wasDeleted = true; slot.value = null; slot.name = null; if (slot == lastAccess) { lastAccess = REMOVED; } } } } return null; } else { throw Kit.codeBug(); } } private static int getSlotIndex(int tableSize, int indexOrHash) { return (indexOrHash & 0x7fffffff) % tableSize; } // Must be inside synchronized (this) private static void copyTable(Slot[] slots, Slot[] newSlots, int count) { if (count == 0) throw Kit.codeBug(); int tableSize = newSlots.length; int i = slots.length; for (;;) { --i; Slot slot = slots[i]; while (slot != null) { int insertPos = getSlotIndex(tableSize, slot.indexOrHash); Slot next = slot.next; addKnownAbsentSlot(newSlots, slot, insertPos); slot.next = null; slot = next; if (--count == 0) return; } } } /** * Add slot with keys that are known to absent from the table. * This is an optimization to use when inserting into empty table, * after table growth or during deserialization. */ private static void addKnownAbsentSlot(Slot[] slots, Slot slot, int insertPos) { if (slots[insertPos] == null) { slots[insertPos] = slot; } else { Slot prev = slots[insertPos]; while (prev.next != null) { prev = prev.next; } prev.next = slot; } } Object[] getIds(boolean getAll) { Slot[] s = slots; Object[] a = ScriptRuntime.emptyArgs; if (s == null) return a; int c = 0; Slot slot = firstAdded; while (slot != null && slot.wasDeleted) { // as long as we're traversing the order-added linked list, // remove deleted slots slot = slot.orderedNext; } firstAdded = slot; while (slot != null) { if (getAll || (slot.getAttributes() & DONTENUM) == 0) { if (c == 0) a = new Object[s.length]; a[c++] = slot.name != null ? (Object) slot.name : new Integer(slot.indexOrHash); } Slot next = slot.orderedNext; while (next != null && next.wasDeleted) { // remove deleted slots next = next.orderedNext; } slot.orderedNext = next; slot = next; } if (c == a.length) return a; Object[] result = new Object[c]; System.arraycopy(a, 0, result, 0, c); return result; } private synchronized void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); int objectsCount = count; if (objectsCount < 0) { // "this" was sealed objectsCount = ~objectsCount; } if (objectsCount == 0) { out.writeInt(0); } else { out.writeInt(slots.length); Slot slot = firstAdded; while (slot != null && slot.wasDeleted) { // as long as we're traversing the order-added linked list, // remove deleted slots slot = slot.orderedNext; } firstAdded = slot; while (slot != null) { out.writeObject(slot); Slot next = slot.orderedNext; while (next != null && next.wasDeleted) { // remove deleted slots next = next.orderedNext; } slot.orderedNext = next; slot = next; } } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); lastAccess = REMOVED; int tableSize = in.readInt(); if (tableSize != 0) { slots = new Slot[tableSize]; int objectsCount = count; if (objectsCount < 0) { // "this" was sealed objectsCount = ~objectsCount; } Slot prev = null; for (int i=0; i != objectsCount; ++i) { lastAdded = (Slot)in.readObject(); if (i==0) { firstAdded = lastAdded; } else { prev.orderedNext = lastAdded; } int slotIndex = getSlotIndex(tableSize, lastAdded.indexOrHash); addKnownAbsentSlot(slots, lastAdded, slotIndex); prev = lastAdded; } } } }
false
true
static <T extends Scriptable> BaseFunction buildClassCtor( Scriptable scope, Class<T> clazz, boolean sealed, boolean mapInheritance) throws IllegalAccessException, InstantiationException, InvocationTargetException { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < methods.length; i++) { Method method = methods[i]; if (!method.getName().equals("init")) continue; Class<?>[] parmTypes = method.getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ContextClass && parmTypes[1] == ScriptRuntime.ScriptableClass && parmTypes[2] == Boolean.TYPE && Modifier.isStatic(method.getModifiers())) { Object args[] = { Context.getContext(), scope, sealed ? Boolean.TRUE : Boolean.FALSE }; method.invoke(null, args); return null; } if (parmTypes.length == 1 && parmTypes[0] == ScriptRuntime.ScriptableClass && Modifier.isStatic(method.getModifiers())) { Object args[] = { scope }; method.invoke(null, args); return null; } } // If we got here, there isn't an "init" method with the right // parameter types. Constructor<?>[] ctors = clazz.getConstructors(); Constructor<?> protoCtor = null; for (int i=0; i < ctors.length; i++) { if (ctors[i].getParameterTypes().length == 0) { protoCtor = ctors[i]; break; } } if (protoCtor == null) { throw Context.reportRuntimeError1( "msg.zero.arg.ctor", clazz.getName()); } Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs); String className = proto.getClassName(); // Set the prototype's prototype, trying to map Java inheritance to JS // prototype-based inheritance if requested to do so. Scriptable superProto = null; if (mapInheritance) { Class<? super T> superClass = clazz.getSuperclass(); if (ScriptRuntime.ScriptableClass.isAssignableFrom(superClass) && !Modifier.isAbstract(superClass.getModifiers())) { Class<? extends Scriptable> superScriptable = extendsScriptable(superClass); String name = ScriptableObject.defineClass(scope, superScriptable, sealed, mapInheritance); if (name != null) { superProto = ScriptableObject.getClassPrototype(scope, name); } } } if (superProto == null) { superProto = ScriptableObject.getObjectPrototype(scope); } proto.setPrototype(superProto); // Find out whether there are any methods that begin with // "js". If so, then only methods that begin with special // prefixes will be defined as JavaScript entities. final String functionPrefix = "jsFunction_"; final String staticFunctionPrefix = "jsStaticFunction_"; final String getterPrefix = "jsGet_"; final String setterPrefix = "jsSet_"; final String ctorName = "jsConstructor"; Member ctorMember = FunctionObject.findSingleMethod(methods, ctorName); if (ctorMember == null) { if (ctors.length == 1) { ctorMember = ctors[0]; } else if (ctors.length == 2) { if (ctors[0].getParameterTypes().length == 0) ctorMember = ctors[1]; else if (ctors[1].getParameterTypes().length == 0) ctorMember = ctors[0]; } if (ctorMember == null) { throw Context.reportRuntimeError1( "msg.ctor.multiple.parms", clazz.getName()); } } FunctionObject ctor = new FunctionObject(className, ctorMember, scope); if (ctor.isVarArgsMethod()) { throw Context.reportRuntimeError1 ("msg.varargs.ctor", ctorMember.getName()); } ctor.initAsConstructor(scope, proto); Method finishInit = null; HashSet<String> names = new HashSet<String>(methods.length); for (int i=0; i < methods.length; i++) { if (methods[i] == ctorMember) { continue; } String name = methods[i].getName(); if (name.equals("finishInit")) { Class<?>[] parmTypes = methods[i].getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ScriptableClass && parmTypes[1] == FunctionObject.class && parmTypes[2] == ScriptRuntime.ScriptableClass && Modifier.isStatic(methods[i].getModifiers())) { finishInit = methods[i]; continue; } } // ignore any compiler generated methods. if (name.indexOf('$') != -1) continue; if (name.equals(ctorName)) continue; String prefix = null; if (name.startsWith(functionPrefix)) { prefix = functionPrefix; } else if (name.startsWith(staticFunctionPrefix)) { prefix = staticFunctionPrefix; if (!Modifier.isStatic(methods[i].getModifiers())) { throw Context.reportRuntimeError( "jsStaticFunction must be used with static method."); } } else if (name.startsWith(getterPrefix)) { prefix = getterPrefix; } else if (name.startsWith(setterPrefix)) { prefix = setterPrefix; } else { continue; } String propName = name.substring(prefix.length()); if (names.contains(propName)) { throw Context.reportRuntimeError2("duplicate.defineClass.name", name, propName); } names.add(propName); name = name.substring(prefix.length()); if (prefix == setterPrefix) continue; // deal with set when we see get if (prefix == getterPrefix) { if (!(proto instanceof ScriptableObject)) { throw Context.reportRuntimeError2( "msg.extend.scriptable", proto.getClass().toString(), name); } Method setter = FunctionObject.findSingleMethod( methods, setterPrefix + name); int attr = ScriptableObject.PERMANENT | ScriptableObject.DONTENUM | (setter != null ? 0 : ScriptableObject.READONLY); ((ScriptableObject) proto).defineProperty(name, null, methods[i], setter, attr); continue; } FunctionObject f = new FunctionObject(name, methods[i], proto); if (f.isVarArgsConstructor()) { throw Context.reportRuntimeError1 ("msg.varargs.fun", ctorMember.getName()); } Scriptable dest = prefix == staticFunctionPrefix ? ctor : proto; defineProperty(dest, name, f, DONTENUM); if (sealed) { f.sealObject(); } } // Call user code to complete initialization if necessary. if (finishInit != null) { Object[] finishArgs = { scope, ctor, proto }; finishInit.invoke(null, finishArgs); } // Seal the object if necessary. if (sealed) { ctor.sealObject(); if (proto instanceof ScriptableObject) { ((ScriptableObject) proto).sealObject(); } } return ctor; }
static <T extends Scriptable> BaseFunction buildClassCtor( Scriptable scope, Class<T> clazz, boolean sealed, boolean mapInheritance) throws IllegalAccessException, InstantiationException, InvocationTargetException { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < methods.length; i++) { Method method = methods[i]; if (!method.getName().equals("init")) continue; Class<?>[] parmTypes = method.getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ContextClass && parmTypes[1] == ScriptRuntime.ScriptableClass && parmTypes[2] == Boolean.TYPE && Modifier.isStatic(method.getModifiers())) { Object args[] = { Context.getContext(), scope, sealed ? Boolean.TRUE : Boolean.FALSE }; method.invoke(null, args); return null; } if (parmTypes.length == 1 && parmTypes[0] == ScriptRuntime.ScriptableClass && Modifier.isStatic(method.getModifiers())) { Object args[] = { scope }; method.invoke(null, args); return null; } } // If we got here, there isn't an "init" method with the right // parameter types. Constructor<?>[] ctors = clazz.getConstructors(); Constructor<?> protoCtor = null; for (int i=0; i < ctors.length; i++) { if (ctors[i].getParameterTypes().length == 0) { protoCtor = ctors[i]; break; } } if (protoCtor == null) { throw Context.reportRuntimeError1( "msg.zero.arg.ctor", clazz.getName()); } Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs); String className = proto.getClassName(); // Set the prototype's prototype, trying to map Java inheritance to JS // prototype-based inheritance if requested to do so. Scriptable superProto = null; if (mapInheritance) { Class<? super T> superClass = clazz.getSuperclass(); if (ScriptRuntime.ScriptableClass.isAssignableFrom(superClass) && !Modifier.isAbstract(superClass.getModifiers())) { Class<? extends Scriptable> superScriptable = extendsScriptable(superClass); String name = ScriptableObject.defineClass(scope, superScriptable, sealed, mapInheritance); if (name != null) { superProto = ScriptableObject.getClassPrototype(scope, name); } } } if (superProto == null) { superProto = ScriptableObject.getObjectPrototype(scope); } proto.setPrototype(superProto); // Find out whether there are any methods that begin with // "js". If so, then only methods that begin with special // prefixes will be defined as JavaScript entities. final String functionPrefix = "jsFunction_"; final String staticFunctionPrefix = "jsStaticFunction_"; final String getterPrefix = "jsGet_"; final String setterPrefix = "jsSet_"; final String ctorName = "jsConstructor"; Member ctorMember = FunctionObject.findSingleMethod(methods, ctorName); if (ctorMember == null) { if (ctors.length == 1) { ctorMember = ctors[0]; } else if (ctors.length == 2) { if (ctors[0].getParameterTypes().length == 0) ctorMember = ctors[1]; else if (ctors[1].getParameterTypes().length == 0) ctorMember = ctors[0]; } if (ctorMember == null) { throw Context.reportRuntimeError1( "msg.ctor.multiple.parms", clazz.getName()); } } FunctionObject ctor = new FunctionObject(className, ctorMember, scope); if (ctor.isVarArgsMethod()) { throw Context.reportRuntimeError1 ("msg.varargs.ctor", ctorMember.getName()); } ctor.initAsConstructor(scope, proto); Method finishInit = null; HashSet<String> names = new HashSet<String>(methods.length); for (int i=0; i < methods.length; i++) { if (methods[i] == ctorMember) { continue; } String name = methods[i].getName(); if (name.equals("finishInit")) { Class<?>[] parmTypes = methods[i].getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ScriptableClass && parmTypes[1] == FunctionObject.class && parmTypes[2] == ScriptRuntime.ScriptableClass && Modifier.isStatic(methods[i].getModifiers())) { finishInit = methods[i]; continue; } } // ignore any compiler generated methods. if (name.indexOf('$') != -1) continue; if (name.equals(ctorName)) continue; String prefix = null; if (name.startsWith(functionPrefix)) { prefix = functionPrefix; } else if (name.startsWith(staticFunctionPrefix)) { prefix = staticFunctionPrefix; if (!Modifier.isStatic(methods[i].getModifiers())) { throw Context.reportRuntimeError( "jsStaticFunction must be used with static method."); } } else if (name.startsWith(getterPrefix)) { prefix = getterPrefix; } else { // note that setterPrefix is among the unhandled names here - // we deal with that when we see the getter continue; } String propName = name.substring(prefix.length()); if (names.contains(propName)) { throw Context.reportRuntimeError2("duplicate.defineClass.name", name, propName); } names.add(propName); name = name.substring(prefix.length()); if (prefix == getterPrefix) { if (!(proto instanceof ScriptableObject)) { throw Context.reportRuntimeError2( "msg.extend.scriptable", proto.getClass().toString(), name); } Method setter = FunctionObject.findSingleMethod( methods, setterPrefix + name); int attr = ScriptableObject.PERMANENT | ScriptableObject.DONTENUM | (setter != null ? 0 : ScriptableObject.READONLY); ((ScriptableObject) proto).defineProperty(name, null, methods[i], setter, attr); continue; } FunctionObject f = new FunctionObject(name, methods[i], proto); if (f.isVarArgsConstructor()) { throw Context.reportRuntimeError1 ("msg.varargs.fun", ctorMember.getName()); } Scriptable dest = prefix == staticFunctionPrefix ? ctor : proto; defineProperty(dest, name, f, DONTENUM); if (sealed) { f.sealObject(); } } // Call user code to complete initialization if necessary. if (finishInit != null) { Object[] finishArgs = { scope, ctor, proto }; finishInit.invoke(null, finishArgs); } // Seal the object if necessary. if (sealed) { ctor.sealObject(); if (proto instanceof ScriptableObject) { ((ScriptableObject) proto).sealObject(); } } return ctor; }
diff --git a/src/reporting_tool/sqa_report.java b/src/reporting_tool/sqa_report.java index a148d27..6e1f0cc 100755 --- a/src/reporting_tool/sqa_report.java +++ b/src/reporting_tool/sqa_report.java @@ -1,563 +1,563 @@ package reporting_tool; import java.util.ArrayList; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import func_analyzer.*; import size_analyzer.*; import cycle_analyzer.*; import info_analyzer.*; import fail_analyzer.*; public class sqa_report { public static int warn_level = 1; public static boolean core_only, ext_only; public static boolean Debug_on; public static boolean Cruise_Control; public static boolean Hudson; public static TestSession current_test_session; public static Discriminent current_parse_discriminent; static boolean obj_size = true; static boolean bin_size = true; static boolean func_size = true; static boolean cycle = true; static boolean compare_options = true; static boolean generate_output_info = true; static boolean new_mode = true; private static int nb_tst=0; private static String output_file_name=null; static String ref_file=null,key_name=null; static Sections section_for_summary=Sections.TEXT; static ArrayList<String> test_names = new ArrayList<String>(); static RootDataClass rootdata= new RootDataClass(); static ArrayList<Sections> sizes_for_computation = new ArrayList<Sections>(); public static Summary summary = new Summary(); private static Xls_Output output_xls; /** * Help function * @param * @author thomas deruyter */ static void man() { System.out.println("Syntax is:\n\treport [Options] <log directory>+"); System.out.println("Options are: "); System.out.println("\t-h | -help | --help : print this help message"); System.out.println("\t-o <file> : redirect output to <file>"); System.out.println("\t-i <option> : option to ignore"); System.out.println("\t-noccopt : ignore all compiler options"); System.out.println("\t-noobj : do not generate size sheet on object"); System.out.println("\t-nobin : do not generate size sheet on binaries"); System.out.println("\t-nocycles : do not generate size sheet on cycles"); System.out.println("\t-noext : do not generate sheet on extensions"); System.out.println("\t-nocore : do not generate sheet on core"); System.out.println("\t-s <section> : size on this section, valid section are:"); System.out.println("\t\ttext/data/rodata/bss/symtab/strtab/dbg/stxp70/total"); System.out.println("\t\ttext_rodata : to combine text+rodata"); System.out.println("\t-ref <fichier> : list of references directory to parse:"); System.out.println("\t-key <name> : directory name to consider under referenced directory from ref option"); System.exit(0); } static void decode_section(String string) { if (string.contentEquals("text")) { sizes_for_computation.add(Sections.TEXT); return; } if (string.contentEquals("data")) { sizes_for_computation.add(Sections.DATA); return; } if (string.contentEquals("rodata")) { sizes_for_computation.add(Sections.RODATA); return; } if (string.contentEquals("bss")) { sizes_for_computation.add(Sections.BSS); return; } if (string.contentEquals("symtab")) { sizes_for_computation.add(Sections.SYMTAB); return; } if (string.contentEquals("strtab")) { sizes_for_computation.add(Sections.STRTAB); return; } if (string.contentEquals("dbg")) { sizes_for_computation.add(Sections.DBG_SECTION); return; } if (string.contentEquals("rela_text")) { sizes_for_computation.add(Sections.RELA_TEXT); return; } if (string.contentEquals("rela_data")) { sizes_for_computation.add(Sections.RELA_DATA); return; } if (string.contentEquals("rela_rodata")) { sizes_for_computation.add(Sections.RELA_RODATA); return; } if (string.contentEquals("rela_dbg")) { sizes_for_computation.add(Sections.RELA_DBG_FRAME); return; } if (string.contentEquals("stxp70")) { sizes_for_computation.add(Sections.STXP70_EXTRECONF_INFO); return; } if (string.contentEquals("total")) { sizes_for_computation.add(Sections.TOTAL);; return; } if (string.contentEquals("text_rodata")) { sizes_for_computation.add(Sections.RODATA_PLUS_TEXT);; return; } System.err.println("ERROR, This size section/combination is not allowed\n"); System.exit(1); } static void parse_arguments(String[] args) { int i=0; while(i < args.length) { if(args[i].contentEquals("-o")) { if (i+1 < args.length) { i++; output_file_name = args[i]; } } else if (args[i].contentEquals("-h") || args[i].contentEquals("-help") || args[i].contentEquals("--help")) { man(); System.exit(0); } else if (args[i].contentEquals("-i")) { if (i+1 < args.length) { i++; rootdata.add_ignored_flags(args[i]); } } else if (args[i].contentEquals("-s")) { if (i+1 < args.length) { i++; decode_section(args[i]); } } else if (args[i].contentEquals("-ref")) { if (i+1 < args.length) { i++; ref_file=args[i]; } } else if (args[i].contentEquals("-key")) { if (i+1 < args.length) { i++; key_name=args[i]; } } else if (args[i].contentEquals("-Woff")) { warn_level=0; } else if (args[i].contentEquals("-noobj")) { obj_size=false; } else if (args[i].contentEquals("-nobin")) { bin_size=false; } else if (args[i].contentEquals("-nofunc")) { func_size=false; } else if (args[i].contentEquals("-nocycles")) { cycle=false; } else if (args[i].contentEquals("-noccopt")) { compare_options=false; } else if (args[i].contentEquals("-noext")) { core_only=true; } else if (args[i].contentEquals("-nocore")) { ext_only=true; } else if (args[i].contentEquals("-dbg")) { Debug_on=true; } else if (args[i].contentEquals("-old_style")) { new_mode=false; } else if (args[i].contentEquals("-hudson")) { Hudson=true; warn_level=0; compare_options=false; sizes_for_computation.add(Sections.TEXT); } else if (args[i].contentEquals("-cruisec")) { Cruise_Control=true; warn_level=0; compare_options=false; sizes_for_computation.add(Sections.TEXT); } else if (args[i].contentEquals("-monitor")) { //Monitoring=true; generate_output_info=false; warn_level=0; compare_options=false; sizes_for_computation.add(Sections.RODATA_PLUS_TEXT); ref_file = "References.txt"; obj_size=false; bin_size=false; cycle=false; System.out.println("Warning option -monitor not yet implemented"); System.exit(0); } else if (args[i].contentEquals("-default")) { warn_level=0; compare_options=false; sizes_for_computation.add(Sections.TEXT); ref_file="References.txt"; } else if (args[i].contentEquals("-nightly")) { warn_level=0; compare_options=false; sizes_for_computation.add(Sections.RODATA_PLUS_TEXT); section_for_summary=Sections.RODATA_PLUS_TEXT; ref_file="References.txt"; } else { test_names.add(args[i]); nb_tst++; } i++; } } static void treat_ref_file() { if (key_name == null && nb_tst > 1) { System.err.println("ERROR, When ref file and several command line tests dirs, a key is needed\n"); System.exit(1); } if (key_name == null) key_name = test_names.get(0); try { BufferedReader input = new BufferedReader(new FileReader(ref_file)); try { String line = null; //not declared within while loop while (( line = input.readLine()) != null){ String session_name=line; if(line.endsWith("/")) { System.out.println("Line contains / at end :" + line); line = line.substring(0, line.length()-1); } if (line.lastIndexOf("/") > 0) { session_name = line.substring(line.lastIndexOf("/")+1,line.length()); } line = line + "/" + key_name; if (Cruise_Control || Hudson) { try { FileReader myfile = new FileReader(line + "/BANNER"); rootdata.add_session(line, session_name); myfile.close(); } catch (FileNotFoundException e) { } } else { try { FileReader myfile = new FileReader(line + "/INFO"); rootdata.add_session(line, session_name); myfile.close(); } catch (FileNotFoundException e) { System.err.println("WARNING: Directory " + line + " does not contain any INFO"); } } } } finally { input.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } static void parse_session(TestSession current_session){ String file_to_parse = current_session.path + "/BANNER"; current_test_session=current_session; Info_Lexer iscanner = null; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); iscanner = new Info_Lexer( new FileReader(file_to_parse)); try { Info_Parser p = new Info_Parser(iscanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { file_to_parse = current_session.path + "/INFO"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); iscanner = new Info_Lexer( new FileReader(file_to_parse)); try { Info_Parser p = new Info_Parser(iscanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException er) { - System.out.println("Unable to find" + file_to_parse); + if(!Cruise_Control && !Hudson) System.out.println("Unable to find " + file_to_parse); } catch (IOException er) { e.printStackTrace(); } catch (Exception er) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } file_to_parse = current_session.path + "/FAILED"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Fail_Lexer scanner = new Fail_Lexer( new FileReader(file_to_parse)); try { Fail_Parser p = new Fail_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } if(obj_size) { current_parse_discriminent = Discriminent.SIZE_OBJ; file_to_parse = current_session.path + "/codeSize.txt"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Size_Lexer scanner = new Size_Lexer( new FileReader(file_to_parse)); try { Size_Parser p = new Size_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { if(!Cruise_Control && !Hudson) System.out.println("Unable to find" + file_to_parse); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } if(bin_size) { current_parse_discriminent = Discriminent.SIZE_BIN; file_to_parse = current_session.path + "/BinaryCodeSize.txt"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Size_Lexer scanner = new Size_Lexer( new FileReader(file_to_parse)); try { Size_Parser p = new Size_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { - if(!Cruise_Control && Hudson) System.out.println("Unable to find" + file_to_parse); + if(!Cruise_Control && !Hudson) System.out.println("Unable to find" + file_to_parse); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } if(func_size) { file_to_parse = current_session.path + "/BinaryFuncSize.txt"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Func_Lexer scanner = new Func_Lexer( new FileReader(file_to_parse)); try { Func_Parser p = new Func_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { if(!Cruise_Control && !Hudson) System.out.println("Unable to find" + file_to_parse); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } if(cycle) { file_to_parse = current_session.path + "/cyclesCount.txt"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Cycle_Lexer scanner = new Cycle_Lexer( new FileReader(file_to_parse)); try { Cycle_Parser p = new Cycle_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { if(!Cruise_Control && !Hudson) System.out.println("Unable to find" + file_to_parse); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } static void generate_text_summary() { if (Debug_on) System.out.println("generate_text_summary #1"); if (obj_size) { rootdata.compute_data(Discriminent.SIZE_OBJ); for (int i=0;i<rootdata.get_disc().size();i++) { for (int j=0;j<rootdata.get_nb_sessions();j++) { summary.add_summary_value(rootdata.get_session(j).path,rootdata.get_session(j).name,rootdata.get_disc().get(i).get_test(),Discriminent.SIZE_OBJ,rootdata.get_session(j).get_size(rootdata.get_disc().get(i),section_for_summary,Discriminent.SIZE_OBJ,false)); } } } if (Debug_on) System.out.println("generate_text_summary #2"); if (bin_size) { rootdata.compute_data(Discriminent.SIZE_BIN); for (int i=0;i<rootdata.get_disc().size();i++) { for (int j=0;j<rootdata.get_nb_sessions();j++) { summary.add_summary_value(rootdata.get_session(j).path,rootdata.get_session(j).name,rootdata.get_disc().get(i).get_test(),Discriminent.SIZE_BIN,rootdata.get_session(j).get_size(rootdata.get_disc().get(i),section_for_summary,Discriminent.SIZE_BIN,false)); } } } if (Debug_on) System.out.println("generate_text_summary #3"); if (func_size) { rootdata.compute_data(Discriminent.SIZE_FUNC); for (int i=0;i<rootdata.get_disc().size();i++) { for (int j=0;j<rootdata.get_nb_sessions();j++) { summary.add_summary_value(rootdata.get_session(j).path,rootdata.get_session(j).name,rootdata.get_disc().get(i).get_test(),Discriminent.SIZE_FUNC,rootdata.get_session(j).get_size(rootdata.get_disc().get(i),section_for_summary,Discriminent.SIZE_FUNC,false)); } } } if (Debug_on) System.out.println("generate_text_summary #4"); if (cycle) { if (Debug_on) System.out.println("generate_text_summary #4.1"); rootdata.compute_data(Discriminent.SPEED); if (Debug_on) System.out.println("generate_text_summary #4.2"); for (int i=0;i<rootdata.get_disc().size();i++) { for (int j=0;j<rootdata.get_nb_sessions();j++) { summary.add_summary_value(rootdata.get_session(j).path,rootdata.get_session(j).name,rootdata.get_disc().get(i).get_test(),Discriminent.SPEED,rootdata.get_session(j).get_cycle(rootdata.get_disc().get(i))); } } if (Debug_on) System.out.println("generate_text_summary #4.3"); } if (Debug_on) System.out.println("generate_text_summary #5"); } /** * Main entry point * @param args : Command line Argument * @author thomas deruyter */ public static void main(String[] args) { int i; /*Useless flag to ignore*/ rootdata.add_ignored_flags("-keep"); rootdata.add_ignored_flags("-Mkeepasm"); rootdata.add_ignored_flags("-fno-verbose-asm"); Debug_on=false; if (args.length == 0) { man(); System.exit(0); } parse_arguments(args); /*Ref treatment*/ if (ref_file != null) treat_ref_file(); for (i=0; i<test_names.size();i++) { rootdata.add_session(test_names.get(i), test_names.get(i)); } /*Parsing phase*/ for(i=0; i<rootdata.get_nb_sessions();i++) { parse_session(rootdata.get_session(i)); } /*End Parsing Phase*/ if (Debug_on) System.out.println("Parsing phase done"); /*Start Processing phase*/ if (output_file_name == null) output_xls = new Xls_Output("default_output.xls"); else output_xls = new Xls_Output(output_file_name); output_xls.generate_header(); output_xls.create_summary(rootdata); if (Debug_on) System.out.println("Summary phase done"); rootdata.remove_ignored_flags(compare_options); if (sizes_for_computation.isEmpty()) { sizes_for_computation.add(Sections.TEXT); } for(i=rootdata.get_nb_sessions()-1; i>=0;i--) { rootdata.get_session(i); summary.add_session(rootdata.get_session(i).path, rootdata.get_session(i).name); } if (Debug_on) System.out.println("Compute1 phase done"); /* Generate summary */ generate_text_summary(); if (Debug_on) System.out.println("Summary text phase done"); /*Size sheet generation*/ if (obj_size) { rootdata.compute_data(Discriminent.SIZE_OBJ); for (i=0; i< sizes_for_computation.size(); i++) { if (!new_mode) output_xls.create_page(rootdata, Discriminent.SIZE_OBJ, sizes_for_computation.get(i)); if (new_mode) output_xls.create_new_page(rootdata, Discriminent.SIZE_OBJ, sizes_for_computation.get(i)); } } if (Debug_on) System.out.println("Obj phase done"); if (bin_size) { rootdata.compute_data(Discriminent.SIZE_BIN); for (i=0; i< sizes_for_computation.size(); i++) { if (!new_mode) output_xls.create_page(rootdata, Discriminent.SIZE_BIN, sizes_for_computation.get(i)); if (new_mode) output_xls.create_new_page(rootdata, Discriminent.SIZE_BIN, sizes_for_computation.get(i)); } } if (Debug_on) System.out.println("Bin phase done"); if (func_size) { rootdata.compute_data(Discriminent.SIZE_FUNC); for (i=0; i< sizes_for_computation.size(); i++) { if (!new_mode) output_xls.create_page(rootdata, Discriminent.SIZE_FUNC, sizes_for_computation.get(i)); if (new_mode) output_xls.create_new_page(rootdata, Discriminent.SIZE_FUNC, sizes_for_computation.get(i)); } rootdata.compute_data(Discriminent.SIZE_APPLI); for (i=0; i< sizes_for_computation.size(); i++) { if (!new_mode) output_xls.create_page(rootdata, Discriminent.SIZE_APPLI, sizes_for_computation.get(i)); if (new_mode) output_xls.create_new_page(rootdata, Discriminent.SIZE_APPLI, sizes_for_computation.get(i)); } } if (Debug_on) System.out.println("Func phase done"); /*Speed sheet generation*/ if (cycle) { if (Debug_on) System.out.println("generate cycle #1"); rootdata.compute_data(Discriminent.SPEED); if (Debug_on) System.out.println("generate cycle #2"); if (!new_mode) output_xls.create_page(rootdata, Discriminent.SPEED, Sections.LAST_SECTION); if (new_mode) output_xls.create_new_page(rootdata, Discriminent.SPEED, Sections.LAST_SECTION); } if (Debug_on) System.out.println("Cycles phase done"); output_xls.excel_terminate(); if (generate_output_info) { if(Cruise_Control) { if(ref_file.contains("branch")) summary.dump_summary(true,"branch"); else summary.dump_summary(true,"ref"); } else if (Hudson) { if(ref_file.contains("branch")) summary.dump_hudson_summary("branch",output_file_name); else summary.dump_hudson_summary("ref",output_file_name); } else summary.dump_summary(false,""); } } }
false
true
static void parse_session(TestSession current_session){ String file_to_parse = current_session.path + "/BANNER"; current_test_session=current_session; Info_Lexer iscanner = null; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); iscanner = new Info_Lexer( new FileReader(file_to_parse)); try { Info_Parser p = new Info_Parser(iscanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { file_to_parse = current_session.path + "/INFO"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); iscanner = new Info_Lexer( new FileReader(file_to_parse)); try { Info_Parser p = new Info_Parser(iscanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException er) { System.out.println("Unable to find" + file_to_parse); } catch (IOException er) { e.printStackTrace(); } catch (Exception er) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } file_to_parse = current_session.path + "/FAILED"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Fail_Lexer scanner = new Fail_Lexer( new FileReader(file_to_parse)); try { Fail_Parser p = new Fail_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } if(obj_size) { current_parse_discriminent = Discriminent.SIZE_OBJ; file_to_parse = current_session.path + "/codeSize.txt"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Size_Lexer scanner = new Size_Lexer( new FileReader(file_to_parse)); try { Size_Parser p = new Size_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { if(!Cruise_Control && !Hudson) System.out.println("Unable to find" + file_to_parse); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } if(bin_size) { current_parse_discriminent = Discriminent.SIZE_BIN; file_to_parse = current_session.path + "/BinaryCodeSize.txt"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Size_Lexer scanner = new Size_Lexer( new FileReader(file_to_parse)); try { Size_Parser p = new Size_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { if(!Cruise_Control && Hudson) System.out.println("Unable to find" + file_to_parse); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } if(func_size) { file_to_parse = current_session.path + "/BinaryFuncSize.txt"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Func_Lexer scanner = new Func_Lexer( new FileReader(file_to_parse)); try { Func_Parser p = new Func_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { if(!Cruise_Control && !Hudson) System.out.println("Unable to find" + file_to_parse); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } if(cycle) { file_to_parse = current_session.path + "/cyclesCount.txt"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Cycle_Lexer scanner = new Cycle_Lexer( new FileReader(file_to_parse)); try { Cycle_Parser p = new Cycle_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { if(!Cruise_Control && !Hudson) System.out.println("Unable to find" + file_to_parse); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
static void parse_session(TestSession current_session){ String file_to_parse = current_session.path + "/BANNER"; current_test_session=current_session; Info_Lexer iscanner = null; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); iscanner = new Info_Lexer( new FileReader(file_to_parse)); try { Info_Parser p = new Info_Parser(iscanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { file_to_parse = current_session.path + "/INFO"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); iscanner = new Info_Lexer( new FileReader(file_to_parse)); try { Info_Parser p = new Info_Parser(iscanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException er) { if(!Cruise_Control && !Hudson) System.out.println("Unable to find " + file_to_parse); } catch (IOException er) { e.printStackTrace(); } catch (Exception er) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } file_to_parse = current_session.path + "/FAILED"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Fail_Lexer scanner = new Fail_Lexer( new FileReader(file_to_parse)); try { Fail_Parser p = new Fail_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } if(obj_size) { current_parse_discriminent = Discriminent.SIZE_OBJ; file_to_parse = current_session.path + "/codeSize.txt"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Size_Lexer scanner = new Size_Lexer( new FileReader(file_to_parse)); try { Size_Parser p = new Size_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { if(!Cruise_Control && !Hudson) System.out.println("Unable to find" + file_to_parse); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } if(bin_size) { current_parse_discriminent = Discriminent.SIZE_BIN; file_to_parse = current_session.path + "/BinaryCodeSize.txt"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Size_Lexer scanner = new Size_Lexer( new FileReader(file_to_parse)); try { Size_Parser p = new Size_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { if(!Cruise_Control && !Hudson) System.out.println("Unable to find" + file_to_parse); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } if(func_size) { file_to_parse = current_session.path + "/BinaryFuncSize.txt"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Func_Lexer scanner = new Func_Lexer( new FileReader(file_to_parse)); try { Func_Parser p = new Func_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { if(!Cruise_Control && !Hudson) System.out.println("Unable to find" + file_to_parse); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } if(cycle) { file_to_parse = current_session.path + "/cyclesCount.txt"; try { if (Debug_on) System.out.println("Parse File : " + file_to_parse); Cycle_Lexer scanner = new Cycle_Lexer( new FileReader(file_to_parse)); try { Cycle_Parser p = new Cycle_Parser(scanner); p.parse(); } catch (IOException er) { System.out.println("An I/O error occured while parsing : \n" + er); System.exit(1); } } catch (FileNotFoundException e) { if(!Cruise_Control && !Hudson) System.out.println("Unable to find" + file_to_parse); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
diff --git a/org.rubypeople.rdt.core/src/org/rubypeople/rdt/internal/core/parser/RubyElement.java b/org.rubypeople.rdt.core/src/org/rubypeople/rdt/internal/core/parser/RubyElement.java index 0c46e1dd..740a8062 100644 --- a/org.rubypeople.rdt.core/src/org/rubypeople/rdt/internal/core/parser/RubyElement.java +++ b/org.rubypeople.rdt.core/src/org/rubypeople/rdt/internal/core/parser/RubyElement.java @@ -1,192 +1,192 @@ /* * Author: C.Williams * * Copyright (c) 2004 RubyPeople. * * This file is part of the Ruby Development Tools (RDT) plugin for eclipse. * You can get copy of the GPL along with further information about RubyPeople * and third party software bundled with RDT in the file * org.rubypeople.rdt.core_0.4.0/RDT.license or otherwise at * http://www.rubypeople.org/RDT.license. * * RDT is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * RDT is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with RDT; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.rubypeople.rdt.internal.core.parser; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * @author Chris * * To change the template for this generated type comment go to Window - * Preferences - Java - Code Generation - Code and Comments */ public class RubyElement implements IRubyElement { protected String access; protected String name; protected Position start; protected Position end; protected Set elements = new HashSet(); public static final String PUBLIC = "public"; public static final String PRIVATE = "private"; public static final String READ = "read"; public static final String WRITE = "write"; protected RubyElement(String name, Position start) { this.start = start; this.name = name; } /** * @return */ public String getName() { return name; } /** * @return */ public Position getStart() { return start; } /** * @return */ public Position getEnd() { return end; } /** * @return */ public String getAccess() { return access; } public void setAccess(String newAccess) { access = newAccess; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ public int hashCode() { return name.hashCode(); } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object arg0) { if (arg0 instanceof RubyElement) { RubyElement element = (RubyElement) arg0; return element.name.equals(this.name); } return false; } /** * @param end */ public void setEnd(Position end) { this.end = end; } /** * @return */ public int getElementCount() { return elements.size(); } /** * @param method */ public void addElement(RubyElement method) { elements.add(method); } /** * @param element * @return */ public boolean contains(RubyElement element) { return elements.contains(element); } public RubyElement getElement(String name) { for (Iterator iter = elements.iterator(); iter.hasNext();) { RubyElement element = (RubyElement) iter.next(); if (element.getName().equals(name)) { return element; } } return null; } public boolean isOutlineElement() { return true; } /* * (non-Javadoc) * * @see org.rubypeople.rdt.internal.core.parser.IRubyElement#getElements() */ public Object[] getElements() { Set outlineElements = new HashSet(); for (Iterator iter = elements.iterator(); iter.hasNext();) { RubyElement element = (RubyElement) iter.next(); if (element.isOutlineElement()) outlineElements.add(element); else { Object[] elements = element.getElements(); if (elements.length > 0) { - outlineElements.add(Arrays.asList(elements)); + outlineElements.addAll(Arrays.asList(elements)); } else { continue; } } } return outlineElements.toArray(); } /* * (non-Javadoc) * * @see org.rubypeople.rdt.internal.core.parser.IRubyElement#hasElements() */ public boolean hasElements() { return getElements().length > 0; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ public String toString() { return getClass().getName() + ": " + getName() + ", [" + getStart() + "," + getEnd() + "]"; } }
true
true
public Object[] getElements() { Set outlineElements = new HashSet(); for (Iterator iter = elements.iterator(); iter.hasNext();) { RubyElement element = (RubyElement) iter.next(); if (element.isOutlineElement()) outlineElements.add(element); else { Object[] elements = element.getElements(); if (elements.length > 0) { outlineElements.add(Arrays.asList(elements)); } else { continue; } } } return outlineElements.toArray(); }
public Object[] getElements() { Set outlineElements = new HashSet(); for (Iterator iter = elements.iterator(); iter.hasNext();) { RubyElement element = (RubyElement) iter.next(); if (element.isOutlineElement()) outlineElements.add(element); else { Object[] elements = element.getElements(); if (elements.length > 0) { outlineElements.addAll(Arrays.asList(elements)); } else { continue; } } } return outlineElements.toArray(); }
diff --git a/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/SynopticMsgcntrManagerImpl.java b/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/SynopticMsgcntrManagerImpl.java index 0cc6c67b..3af9482e 100644 --- a/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/SynopticMsgcntrManagerImpl.java +++ b/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/SynopticMsgcntrManagerImpl.java @@ -1,1161 +1,1161 @@ package org.sakaiproject.component.app.messageforums; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.sakaiproject.api.app.messageforums.Area; import org.sakaiproject.api.app.messageforums.DiscussionForumService; import org.sakaiproject.api.app.messageforums.MessageForumsMessageManager; import org.sakaiproject.api.app.messageforums.MessageForumsTypeManager; import org.sakaiproject.api.app.messageforums.SynopticMsgcntrItem; import org.sakaiproject.api.app.messageforums.SynopticMsgcntrManager; import org.sakaiproject.api.app.messageforums.ui.DiscussionForumManager; import org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager; import org.sakaiproject.api.app.messageforums.ui.UIPermissionsManager; import org.sakaiproject.authz.api.Member; import org.sakaiproject.authz.cover.SecurityService; import org.sakaiproject.component.app.messageforums.dao.hibernate.SynopticMsgcntrItemImpl; import org.sakaiproject.db.cover.SqlService; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.cover.SiteService; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class SynopticMsgcntrManagerImpl extends HibernateDaoSupport implements SynopticMsgcntrManager { private static final Log LOG = LogFactory.getLog(SynopticMsgcntrManagerImpl.class); private static final String QUERY_WORKSPACE_SYNOPTIC_ITEMS = "findWorkspaceSynopticMsgcntrItems"; private static final String QUERY_SITE_SYNOPTIC_ITEMS = "findSiteSynopticMsgcntrItems"; private static final String QUERY_UPDATE_ALL_SITE_TITLES = "updateSiteTitles"; private HashMap mfPageInSiteMap, sitesMap; // transient variable for when on home page of site private transient DecoratedCompiledMessageStats siteContents; private MessageForumsMessageManager messageManager; private UIPermissionsManager uiPermissionsManager; private PrivateMessageManager pvtMessageManager; private MessageForumsTypeManager typeManager; private DiscussionForumManager forumManager; public SynopticMsgcntrManagerImpl() {} public void init() { LOG.info("init()"); } public List<SynopticMsgcntrItem> getWorkspaceSynopticMsgcntrItems(final String userId) { HibernateCallback hcb = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = session.getNamedQuery(QUERY_WORKSPACE_SYNOPTIC_ITEMS); q.setParameter("userId", userId, Hibernate.STRING); return q.list(); } }; return (List<SynopticMsgcntrItem>) getHibernateTemplate().execute(hcb); } public SynopticMsgcntrItem getSiteSynopticMsgcntrItem(final String userId, final String siteId) { HibernateCallback hcb = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = session.getNamedQuery(QUERY_SITE_SYNOPTIC_ITEMS); q.setParameter("userId", userId, Hibernate.STRING); q.setParameter("siteId", siteId, Hibernate.STRING); return q.uniqueResult(); } }; return (SynopticMsgcntrItem) getHibernateTemplate().execute(hcb); } public SynopticMsgcntrItem createSynopticMsgcntrItem(String userId, String siteId, String siteTitle){ return new SynopticMsgcntrItemImpl(userId, siteId, siteTitle); } public void saveSynopticMsgcntrItem(SynopticMsgcntrItem item){ getHibernateTemplate().saveOrUpdate(item); } public void deleteSynopticMsgcntrItem(SynopticMsgcntrItem item){ getHibernateTemplate().delete(item); } public void incrementMessagesSynopticToolInfo(String userId, String siteId){ incrementSynopticToolInfo(userId, siteId, true); } public void incrementForumSynopticToolInfo(String userId, String siteId){ incrementSynopticToolInfo(userId, siteId, false); } private void incrementSynopticToolInfo(String userId, String siteId, boolean messages){ SynopticMsgcntrItem item = getSiteSynopticMsgcntrItem(userId, siteId); if(item == null){ //item does not exist, call the reset function to set the //actually number of unread messages instead of incrementing resetMessagesAndForumSynopticInfo(userId, siteId); }else{ if(messages) item.incrementNewMessagesCount(); else item.incrementNewForumCount(); saveSynopticMsgcntrItem(item); } } public void decrementMessagesSynopticToolInfo(String userId, String siteId){ decrementSynopticToolInfo(userId, siteId, true); } public void decrementForumSynopticToolInfo(String userId, String siteId){ decrementSynopticToolInfo(userId, siteId, false); } private void decrementSynopticToolInfo(String userId, String siteId, boolean messages){ SynopticMsgcntrItem item = getSiteSynopticMsgcntrItem(userId, siteId); if(item == null){ //item does not exist, call the reset function to set the //actually number of unread messages instead of decrementing resetMessagesAndForumSynopticInfo(userId, siteId); }else{ if(messages) item.decrementNewMessagesCount(); else item.decrementNewForumCount(); saveSynopticMsgcntrItem(item); } } public void resetMessagesAndForumSynopticInfo(String userId, String siteId) { DecoratedCompiledMessageStats dcmStats = this.getSiteInfo(siteId, userId); SynopticMsgcntrItem item = getSiteSynopticMsgcntrItem(userId, siteId); if (item == null) { SynopticMsgcntrItem synopticMsgcntrItem = createSynopticMsgcntrItem( userId, siteId, dcmStats.getSiteName()); synopticMsgcntrItem.setNewMessagesCount(dcmStats .getUnreadPrivateAmt()); synopticMsgcntrItem.setNewForumCount(dcmStats.getUnreadForumsAmt()); saveSynopticMsgcntrItem(synopticMsgcntrItem); } else { item.setNewMessagesCount(dcmStats.getUnreadPrivateAmt()); item.setMessagesLastVisitToCurrentDt(); item.setNewForumCount(dcmStats.getUnreadForumsAmt()); item.setForumLastVisitToCurrentDt(); saveSynopticMsgcntrItem(item); } } public void setMessagesSynopticInfoHelper(String userId, String siteId, int newMessageCount){ setSynopticInfoHelper(userId, siteId, true, newMessageCount); } public void setForumSynopticInfoHelper(String userId, String siteId, int newMessageCount){ setSynopticInfoHelper(userId, siteId, false, newMessageCount); } private void setSynopticInfoHelper(String userId, String siteId, boolean messages, int newMessageCount){ //this could be an anon access if (userId == null && forumManager.getAnonRole()) { return; } SynopticMsgcntrItem item = getSiteSynopticMsgcntrItem(userId, siteId); if(item == null){ //item does not exist, call the reset function to set the //actually number of unread messages instead of decrementing resetMessagesAndForumSynopticInfo(userId, siteId); }else{ if(messages){ item.setNewMessagesCount(newMessageCount); item.setMessagesLastVisitToCurrentDt(); }else{ item.setNewForumCount(newMessageCount); item.setForumLastVisitToCurrentDt(); } saveSynopticMsgcntrItem(item); } } /* * Update Difference will get the existing count and add the difference (if negative, then its a subtract mathamatically) */ public void updateDifferenceMessagesSynopticInfoHelper(String userId, String siteId, int differenceCount){ updateDifferenceSynopticInfoHelper(userId, siteId, true, differenceCount); } public void updateDifferenceForumSynopticInfoHelper(String userId, String siteId, int differenceCount){ updateDifferenceSynopticInfoHelper(userId, siteId, false, differenceCount); } private void updateDifferenceSynopticInfoHelper(String userId, String siteId, boolean messages, int differenceCount){ SynopticMsgcntrItem item = getSiteSynopticMsgcntrItem(userId, siteId); if(item == null){ //item does not exist, call the reset function to set the //actually number of unread messages instead of decrementing resetMessagesAndForumSynopticInfo(userId, siteId); }else{ if(messages){ int newCount = item.getNewMessagesCount() + differenceCount; if(newCount < 0){ newCount = 0; } item.setNewMessagesCount(newCount); item.setMessagesLastVisitToCurrentDt(); }else{ int newCount = item.getNewForumCount() + differenceCount; if(newCount < 0){ newCount = 0; } item.setNewForumCount(newCount); item.setForumLastVisitToCurrentDt(); } saveSynopticMsgcntrItem(item); } } public void createOrUpdateSynopticToolInfo(String userId, String siteId, String siteTitle, int unreadMessageCount, int unreadForumCount){ SynopticMsgcntrItem item = getSiteSynopticMsgcntrItem(userId, siteId); if(item == null){ SynopticMsgcntrItem synopticMsgcntrItem = createSynopticMsgcntrItem(userId, siteId, siteTitle); synopticMsgcntrItem.setNewMessagesCount(unreadMessageCount); synopticMsgcntrItem.setNewForumCount(unreadForumCount); saveSynopticMsgcntrItem(synopticMsgcntrItem); }else{ item.setNewMessagesCount(unreadMessageCount); item.setMessagesLastVisitToCurrentDt(); item.setNewForumCount(unreadForumCount); item.setForumLastVisitToCurrentDt(); saveSynopticMsgcntrItem(item); if(item.getSiteTitle() == null || (item.getSiteTitle() != null && !item.getSiteTitle().equals(siteTitle))){ updateAllSiteTitles(siteId, siteTitle); } } } /** * @return * DecoratedCompiledMessageStats for a single site */ public DecoratedCompiledMessageStats getSiteInfo(String siteId, String userId) { return getSiteContents(siteId, userId); } public int findAllUnreadMessages(List aggregateList){ int unreadCount = 0; for (Iterator i = aggregateList.iterator(); i.hasNext();){ Object[] element = (Object[]) i.next(); /** filter on type and read status*/ if (Boolean.TRUE.equals(element[0])){ continue; } else{ unreadCount += ((Integer) element[2]).intValue(); } } return unreadCount; } public void resetAllUsersSynopticInfoInSite(String siteId){ List<String> users = new ArrayList<String>(); Site site; try { site = getSite(siteId); for (Iterator iterator = site.getMembers().iterator(); iterator.hasNext();) { Member member = (Member) iterator.next(); String userId = member.getUserId(); users.add(userId); } resetAllUsersSynopticInfoInSite(siteId, users); } catch (IdUnusedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void resetAllUsersSynopticInfoInSite(String siteId, List<String> users){ String NEW_MESSAGE_COUNT_FOR_ALL_USERS_SQL = "SELECT USER_ID, count(*) unread_messages " + "FROM MFR_PVT_MSG_USR_T message " + "where READ_STATUS = 0 and CONTEXT_ID = ? " + "Group By USER_ID"; String RETURN_ALL_FORUMS_AND_TOPICS_SQL = "select forum.ID as FORUM_ID, topic.ID as TOPIC_ID, forum.DRAFT as isForumDraft, topic.DRAFT as isTopicDraft, topic.MODERATED as isTopicModerated, forum.LOCKED as isForumLocked, topic.LOCKED as isTopicLocked, forum.CREATED_BY as forumCreatedBy, topic.CREATED_BY as topicCreatedBy, forum.AVAILABILITY as forumAvailability, topic.AVAILABILITY as topicAvailability " + "from MFR_AREA_T area, MFR_OPEN_FORUM_T forum, MFR_TOPIC_T topic " + "Where area.ID = forum.surrogateKey and forum.ID = topic.of_surrogateKey " + "and area.CONTEXT_ID = ?"; Connection clConnection = null; //Statement statement = null; PreparedStatement newMessageCountForAllUsers = null; PreparedStatement returnAllForumsAndTopics = null; ResultSet forumsAndTopicsRS = null; ResultSet newMessagesCountRS = null; try { Site site = getSite(siteId); clConnection = SqlService.borrowConnection(); //setup prepared statements: newMessageCountForAllUsers = clConnection.prepareStatement(NEW_MESSAGE_COUNT_FOR_ALL_USERS_SQL); newMessageCountForAllUsers.setString(1, siteId); returnAllForumsAndTopics = clConnection.prepareStatement(RETURN_ALL_FORUMS_AND_TOPICS_SQL); returnAllForumsAndTopics.setString(1, siteId); forumsAndTopicsRS = returnAllForumsAndTopics.executeQuery(); HashMap<Long, DecoratedForumInfo> dfHM = getDecoratedForumsAndTopics(forumsAndTopicsRS); newMessagesCountRS = newMessageCountForAllUsers.executeQuery(); HashMap<String, Integer> unreadMessagesHM = getUnreadMessagesHM(newMessagesCountRS); for (Iterator iterator = users.iterator(); iterator.hasNext();) { String userId = (String) iterator.next(); DecoratedCompiledMessageStats dcms = getDMessageStats(userId, siteId, site, dfHM, unreadMessagesHM); createOrUpdateSynopticToolInfo(userId, siteId, dcms.getSiteName(), dcms.getUnreadPrivateAmt(), dcms.getUnreadForumsAmt()); } } catch (IdUnusedException e) { LOG.error(e); } catch (SQLException e) { LOG.error(e); } finally{ try { if(forumsAndTopicsRS != null) forumsAndTopicsRS.close(); } catch (Exception e) { LOG.warn(e); } try { if(newMessagesCountRS != null) newMessagesCountRS.close(); } catch (Exception e) { LOG.warn(e); } try { if(newMessageCountForAllUsers != null) newMessageCountForAllUsers.close(); } catch (Exception e) { LOG.warn(e); } try { if(returnAllForumsAndTopics != null) returnAllForumsAndTopics.close(); } catch (Exception e) { LOG.warn(e); } SqlService.returnConnection(clConnection); } } /** * This method is used to get live information regarding the new message count per user for a forum ID * * This information can be used to compare against a later current information set after an event takes place * (ie. after saving a forum) By only looking at the one forum that was updated, we can compare the two results * and update the synoptic data based on the difference while avoiding calling unneeded forums, which can slow * down this process significantly * * @param siteId * @param forumId * @return */ public HashMap<String, Integer> getUserToNewMessagesForForumMap(String siteId, Long forumId, Long topicId){ HashMap<String, Integer> returnHM = new HashMap<String, Integer>(); String RETURN_ALL_TOPICS_FOR_FORUM_SQL = "select forum.ID as FORUM_ID, topic.ID as TOPIC_ID, forum.DRAFT as isForumDraft, topic.DRAFT as isTopicDraft, topic.MODERATED as isTopicModerated, forum.LOCKED as isForumLocked, topic.LOCKED as isTopicLocked, forum.CREATED_BY as forumCreatedBy, topic.CREATED_BY as topicCreatedBy, forum.AVAILABILITY as forumAvailability, topic.AVAILABILITY as topicAvailability " + "from MFR_AREA_T area, MFR_OPEN_FORUM_T forum, MFR_TOPIC_T topic " + "Where area.ID = forum.surrogateKey and forum.ID = topic.of_surrogateKey " + "and area.CONTEXT_ID = ? and forum.ID = ?"; if(topicId != null){ RETURN_ALL_TOPICS_FOR_FORUM_SQL = RETURN_ALL_TOPICS_FOR_FORUM_SQL + " and topic.ID = ?"; } List<String> users = new ArrayList<String>(); Site site; Connection clConnection = null; PreparedStatement returnAllTopicsForForum = null; ResultSet forumsAndTopicsRS = null; try { site = getSite(siteId); //get the list of users in the site: for (Iterator iterator = site.getMembers().iterator(); iterator.hasNext();) { Member member = (Member) iterator.next(); String userId = member.getUserId(); users.add(userId); } clConnection = SqlService.borrowConnection(); returnAllTopicsForForum = clConnection.prepareStatement(RETURN_ALL_TOPICS_FOR_FORUM_SQL); returnAllTopicsForForum.setString(1, siteId); returnAllTopicsForForum.setString(2, "" +forumId); if(topicId != null) returnAllTopicsForForum.setString(3, "" +topicId); forumsAndTopicsRS = returnAllTopicsForForum.executeQuery(); HashMap<Long, DecoratedForumInfo> dfHM = getDecoratedForumsAndTopics(forumsAndTopicsRS); for (Iterator iterator = users.iterator(); iterator.hasNext();) { String userId = (String) iterator.next(); //by passing a null, we can ignore all message tool calls (speeding up the process) DecoratedCompiledMessageStats dcms = getDMessageStats(userId, siteId, site, dfHM, null); returnHM.put(userId, Integer.valueOf(dcms.getUnreadForumsAmt())); } } catch (IdUnusedException e) { LOG.error(e); } catch (SQLException e) { LOG.error(e); } finally{ try { if(forumsAndTopicsRS != null) forumsAndTopicsRS.close(); } catch (Exception e) { LOG.warn(e); } try { if(returnAllTopicsForForum != null) returnAllTopicsForForum.close(); } catch (Exception e) { LOG.warn(e); } SqlService.returnConnection(clConnection); } return returnHM; } public void updateSynopticMessagesForForumComparingOldMessagesCount(String siteId, Long forumId, Long topicId, HashMap<String, Integer> previousCountHM){ if(previousCountHM != null){ // get new count Hash Map for comparison HashMap<String, Integer> newCountHM = getUserToNewMessagesForForumMap(siteId, forumId, topicId); if(newCountHM != null){ //loop through new count HM and compare: Set<String> users = newCountHM.keySet(); int oldForumCount = 0; int newForumCount = 0; int forumCountDiff = 0; for (Iterator iterator = users.iterator(); iterator.hasNext();) { String userId = (String) iterator.next(); oldForumCount = 0; newForumCount = 0; forumCountDiff = 0; Integer oldForumCountInt = previousCountHM.get(userId); if(oldForumCountInt != null){ oldForumCount = oldForumCountInt.intValue(); } Integer newForumCountInt = newCountHM.get(userId); if(newForumCountInt != null){ newForumCount = newForumCountInt.intValue(); } forumCountDiff = newForumCount - oldForumCount; this.updateDifferenceForumSynopticInfoHelper(userId, siteId, forumCountDiff); } } } } private DecoratedCompiledMessageStats getDMessageStats(String userId, String siteId, Site site, HashMap<Long, DecoratedForumInfo> dfHM, HashMap<String, Integer> unreadMessagesHM){ final DecoratedCompiledMessageStats dcms = new DecoratedCompiledMessageStats(); // Check if tool within site // if so, get stats for just this site boolean isMessageForumsPageInSite = isMessageForumsPageInSite(site); dcms.setSiteName(site.getTitle()); dcms.setSiteId(siteId); - //MSGCNTR-430 if this is the anon user we can't actualy do anything more -DH + //MSGCNTR-430 if this is the anon user we can't actually do anything more -DH if (userId == null) { return dcms; } if (isMessageForumsPageInSite || isMessagesPageInSite(site)) { if(unreadMessagesHM != null){ // Get private message area so we can get the private message forum so we can get the // List of topics so we can get the Received topic to finally determine number of unread messages // only check if Messages & Forums in site, just Messages is on by default boolean isEnabled; if (isMessageForumsPageInSite) { final Area area = pvtMessageManager.getPrivateMessageArea(siteId); isEnabled = area.getEnabled().booleanValue(); } else { isEnabled = true; } if (isEnabled) { Integer newMessageCount = unreadMessagesHM.get(userId); if(newMessageCount != null){ dcms.setUnreadPrivateAmt(newMessageCount.intValue()); } } } } if (isMessageForumsPageInSite || isForumsPageInSite(site)) { Set<Long> dfKeySet = null; int unreadForum = 0; if(dfHM != null){ boolean isSuperUser = SecurityService.isSuperUser(userId); //site has forums added to the tool dfKeySet = dfHM.keySet(); boolean isInstructor = getForumManager().isInstructor(userId, "/site/" + siteId); boolean hasOverridingPermission = false; if(isInstructor || isSuperUser){ hasOverridingPermission = true; } boolean isAreaAvailable = true; if(!hasOverridingPermission){ //need to check that the area hasn't been disabled: Area area = forumManager.getDiscussionForumArea(siteId); if(area != null){ isAreaAvailable = area.getAvailability(); } } if(isAreaAvailable){ for (Iterator iterator = dfKeySet.iterator(); iterator.hasNext();) { Long dfId = (Long) iterator.next(); DecoratedForumInfo dForum = dfHM.get(dfId); // Only count unread messages for forums the user can view: if ((dForum.getIsDraft().equals(Boolean.FALSE) && dForum.getAvailability()) || hasOverridingPermission || forumManager.isForumOwner(dfId, dForum.getCreator(), userId, "/site/" + siteId)) { final Iterator<DecoratedTopicsInfo> topicIter = dForum.getTopics().iterator(); while (topicIter.hasNext()) { DecoratedTopicsInfo topic = (DecoratedTopicsInfo) topicIter.next(); Long topicId = topic.getTopicId(); Boolean isTopicDraft = topic.getIsDraft(); Boolean isTopicModerated = topic.getIsModerated(); Boolean isTopicLocked = topic.getIsLocked(); String topicOwner = topic.getCreator(); //Only count unread messages for topics the user can view: if ((isTopicDraft.equals(Boolean.FALSE) && topic.getAvailability()) || isInstructor || isSuperUser ||forumManager.isTopicOwner(topicId, topicOwner, userId, "/site/" + siteId)){ if (getUiPermissionsManager().isRead(topicId, isTopicDraft, dForum.getIsDraft(), userId, siteId)) { if (!isTopicModerated.booleanValue() || (isTopicModerated.booleanValue() && getUiPermissionsManager().isModeratePostings(topicId, dForum.getIsLocked(), dForum.getIsDraft(), isTopicLocked, isTopicDraft, userId, siteId))) { unreadForum += getMessageManager().findUnreadMessageCountByTopicIdByUserId(topicId, userId); } else { // b/c topic is moderated and user does not have mod perm, user may only // see approved msgs or pending/denied msgs authored by user unreadForum += getMessageManager().findUnreadViewableMessageCountByTopicIdByUserId(topicId, userId); } } } } } } } } dcms.setUnreadForumsAmt(unreadForum); } return dcms; } /** * Returns List to populate page if on Home page of a site * * @return * List of DecoratedCompiledMessageStats for a particular site */ private DecoratedCompiledMessageStats getSiteContents(String siteId, String userId) { String NEW_MESSAGE_COUNT_SQL = "SELECT USER_ID, count(*) unread_messages " + "FROM MFR_PVT_MSG_USR_T message " + "where READ_STATUS = 0 and USER_ID = ? and CONTEXT_ID = ? " + "Group By USER_ID"; String RETURN_ALL_FORUMS_AND_TOPICS_SQL = "select forum.ID as FORUM_ID, topic.ID as TOPIC_ID, forum.DRAFT as isForumDraft, topic.DRAFT as isTopicDraft, topic.MODERATED as isTopicModerated, forum.LOCKED as isForumLocked, topic.LOCKED as isTopicLocked, forum.CREATED_BY as forumCreatedBy, topic.CREATED_BY as topicCreatedBy, forum.AVAILABILITY as forumAvailability, topic.AVAILABILITY as topicAvailability " + "from MFR_AREA_T area, MFR_OPEN_FORUM_T forum, MFR_TOPIC_T topic " + "Where area.ID = forum.surrogateKey and forum.ID = topic.of_surrogateKey " + "and area.CONTEXT_ID = ?"; Connection clConnection = null; PreparedStatement newMessageCount = null; PreparedStatement returnAllForumsAndTopics = null; ResultSet forumsAndTopicsRS = null; ResultSet newMessagesCountRS = null; final DecoratedCompiledMessageStats dcms = new DecoratedCompiledMessageStats(); try{ clConnection = SqlService.borrowConnection(); newMessageCount = clConnection.prepareStatement(NEW_MESSAGE_COUNT_SQL); newMessageCount.setString(1, userId); newMessageCount.setString(2, siteId); returnAllForumsAndTopics = clConnection.prepareStatement(RETURN_ALL_FORUMS_AND_TOPICS_SQL); returnAllForumsAndTopics.setString(1, siteId); Site site = getSite(siteId); forumsAndTopicsRS = returnAllForumsAndTopics.executeQuery(); HashMap<Long, DecoratedForumInfo> dfHM = getDecoratedForumsAndTopics(forumsAndTopicsRS); newMessagesCountRS = newMessageCount.executeQuery(); HashMap<String, Integer> unreadMessagesHM = getUnreadMessagesHM(newMessagesCountRS); return getDMessageStats(userId, siteId, site, dfHM, unreadMessagesHM); }catch(IdUnusedException e) { LOG.error("IdUnusedException while trying to check if site has MF tool."); } catch (SQLException e) { LOG.error(e); } finally{ try { if(forumsAndTopicsRS != null) forumsAndTopicsRS.close(); } catch (Exception e) { LOG.warn(e); } try { if(newMessagesCountRS != null) newMessagesCountRS.close(); } catch (Exception e) { LOG.warn(e); } try { if(returnAllForumsAndTopics != null) returnAllForumsAndTopics.close(); } catch (Exception e) { LOG.warn(e); } try { if(newMessageCount != null) newMessageCount.close(); } catch (Exception e) { LOG.warn(e); } SqlService.returnConnection(clConnection); } return dcms; } private HashMap<Long, DecoratedForumInfo> getDecoratedForumsAndTopics(ResultSet rs){ HashMap<Long, DecoratedForumInfo> returnHM = new HashMap<Long, DecoratedForumInfo>(); try { String FORUM_CREATED_BY, TOPIC_CREATED_BY; Long FORUM_ID, TOPIC_ID; Boolean IS_TOPIC_DRAFT, IS_FORUM_DRAFT, IS_TOPIC_MODERATED, IS_FORUM_LOCKED, IS_TOPIC_LOCKED, FORUM_AVAILABILITY, TOPIC_AVAILABILITY; while(rs.next()){ FORUM_ID = rs.getLong("FORUM_ID"); TOPIC_ID = rs.getLong("TOPIC_ID"); IS_TOPIC_DRAFT = rs.getBoolean("isTopicDraft"); IS_FORUM_DRAFT = rs.getBoolean("isForumDraft"); IS_TOPIC_MODERATED = rs.getBoolean("isTopicModerated"); IS_FORUM_LOCKED = rs.getBoolean("isForumLocked"); IS_TOPIC_LOCKED = rs.getBoolean("isTopicLocked"); FORUM_CREATED_BY = rs.getString("forumCreatedBy"); TOPIC_CREATED_BY = rs.getString("topicCreatedBy"); FORUM_AVAILABILITY = rs.getBoolean("forumAvailability"); TOPIC_AVAILABILITY = rs.getBoolean("topicAvailability"); //hashmap already has this site id, now look for forum id: if(returnHM.containsKey(FORUM_ID)){ DecoratedTopicsInfo dTopic = new DecoratedTopicsInfo(TOPIC_ID, IS_TOPIC_LOCKED, IS_TOPIC_DRAFT, TOPIC_AVAILABILITY, IS_TOPIC_MODERATED, TOPIC_CREATED_BY); returnHM.get(FORUM_ID).addTopic(dTopic); }else{ //this is a new forum, so add it to the list DecoratedTopicsInfo dTopic = new DecoratedTopicsInfo(TOPIC_ID, IS_TOPIC_LOCKED, IS_TOPIC_DRAFT, TOPIC_AVAILABILITY, IS_TOPIC_MODERATED, TOPIC_CREATED_BY); DecoratedForumInfo dForum = new DecoratedForumInfo(FORUM_ID, IS_FORUM_LOCKED, IS_FORUM_DRAFT, FORUM_AVAILABILITY, FORUM_CREATED_BY); dForum.addTopic(dTopic); returnHM.put(FORUM_ID, dForum); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return returnHM; } public HashMap<String, Integer> getUnreadMessagesHM(ResultSet rs){ HashMap<String, Integer> returnHM = new HashMap<String, Integer>(); if(rs != null){ try{ String userId; Integer messageCount; while(rs.next()){ userId = rs.getString("USER_ID"); messageCount = Integer.valueOf(rs.getInt("unread_messages")); returnHM.put(userId, messageCount); } }catch(Exception e){ LOG.error(e); } } return returnHM; } /** * @return TRUE if Messages & Forums (Message Center) exists in this site, * FALSE otherwise */ private boolean isMessageForumsPageInSite(Site thisSite) { if (mfPageInSiteMap == null) { mfPageInSiteMap = new HashMap(); } Boolean isMFPageInSite; if ((isMFPageInSite = (Boolean) mfPageInSiteMap.get(thisSite)) == null) { isMFPageInSite = isToolInSite(thisSite, DiscussionForumService.MESSAGE_CENTER_ID); mfPageInSiteMap.put(thisSite, isMFPageInSite); } return isMFPageInSite; } /** * Return TRUE if tool with id passed in exists in site passed in * FALSE otherwise. * * @param thisSite * Site object to check * @param toolId * Tool id to be checked * * @return */ private boolean isToolInSite(Site thisSite, String toolId) { final Collection toolsInSite = thisSite.getTools(toolId); return ! toolsInSite.isEmpty(); } /** * Returns the Site object for this id, if it exists. * If not, returns IdUnusedException * * @param siteId * The site id to check * * @return * Site object for this id */ private Site getSite(String siteId) throws IdUnusedException { if (sitesMap == null) { sitesMap = new HashMap(); } if (sitesMap.get(siteId) == null) { Site site = SiteService.getSite(siteId); sitesMap.put(site.getId(), site); return site; } else { return (Site) sitesMap.get(siteId); } } /** * @return TRUE if Messages tool exists in this site, * FALSE otherwise */ private boolean isMessagesPageInSite(Site thisSite) { return isToolInSite(thisSite, DiscussionForumService.MESSAGES_TOOL_ID); } /** * @return TRUE if Forums tool exists in this site, * FALSE otherwise */ private boolean isForumsPageInSite(Site thisSite) { return isToolInSite(thisSite, DiscussionForumService.FORUMS_TOOL_ID); } public MessageForumsMessageManager getMessageManager() { return messageManager; } public void setMessageManager(MessageForumsMessageManager messageManager) { this.messageManager = messageManager; } public UIPermissionsManager getUiPermissionsManager() { return uiPermissionsManager; } public void setUiPermissionsManager(UIPermissionsManager uiPermissionsManager) { this.uiPermissionsManager = uiPermissionsManager; } public PrivateMessageManager getPvtMessageManager() { return pvtMessageManager; } public void setPvtMessageManager(PrivateMessageManager pvtMessageManager) { this.pvtMessageManager = pvtMessageManager; } public MessageForumsTypeManager getTypeManager() { return typeManager; } public void setTypeManager(MessageForumsTypeManager typeManager) { this.typeManager = typeManager; } public DiscussionForumManager getForumManager() { return forumManager; } public void setForumManager(DiscussionForumManager forumManager) { this.forumManager = forumManager; } /** * Used to store synoptic information for a users unread messages. * Whether on the Home page of a site or in MyWorkspace determines * what properties are filled. * <p> * If in MyWorkspace, each object contains the number of unread * Private Messages and number of unread Discussion Forum messages. * </p> * <p> * If in the Home page of a site, each object contains either the * number of unread Private Messages or number of unread Discussion * Forum messages.</p> * * @author josephrodriguez * */ public class DecoratedCompiledMessageStats { private String siteName; private String siteId; /** MyWorkspace information */ private int unreadPrivateAmt = 0; private int unreadForumsAmt = 0; private String mcPageURL; private String privateMessagesUrl; private boolean messagesandForums; private boolean messages; private boolean forums; public String getSiteName() { return siteName; } public void setSiteName(String siteName) { this.siteName = siteName; } public int getUnreadPrivateAmt() { return unreadPrivateAmt; } public void setUnreadPrivateAmt(int unreadPrivateAmt) { this.unreadPrivateAmt = unreadPrivateAmt; } public int getUnreadForumsAmt() { return unreadForumsAmt; } public void setUnreadForumsAmt(int unreadForumsAmt) { this.unreadForumsAmt = unreadForumsAmt; } public String getMcPageURL() { return mcPageURL; } public void setMcPageURL(String mcPageURL) { this.mcPageURL = mcPageURL; } public String getSiteId() { return siteId; } public void setSiteId(String siteId) { this.siteId = siteId; } public String getPrivateMessagesUrl() { return privateMessagesUrl; } public void setPrivateMessagesUrl(String privateMessagesUrl) { this.privateMessagesUrl = privateMessagesUrl; } public boolean isMessagesandForums() { return messagesandForums; } public void setMessagesandForums(boolean messagesandForums) { this.messagesandForums = messagesandForums; } public boolean isMessages() { return messages; } public void setMessages(boolean messages) { this.messages = messages; } public boolean isForums() { return forums; } public void setForums(boolean forums) { this.forums = forums; } } public class DecoratedForumInfo{ private Long forumId; private Boolean isLocked, isDraft, availability; private String creator; private ArrayList<DecoratedTopicsInfo> topics = new ArrayList<DecoratedTopicsInfo>(); public DecoratedForumInfo(Long forumId, Boolean isLocked, Boolean isDraft, Boolean availability, String creator){ this.forumId = forumId; this.isLocked = isLocked; this.isDraft = isDraft; this.creator = creator; this.availability = availability; } public Long getForumId() { return forumId; } public void setForumId(Long forumId) { this.forumId = forumId; } public Boolean getIsLocked() { return isLocked; } public void setIsLocked(Boolean isLocked) { this.isLocked = isLocked; } public Boolean getIsDraft() { return isDraft; } public void setIsDraft(Boolean isDraft) { this.isDraft = isDraft; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public void addTopic(DecoratedTopicsInfo dTopics){ topics.add(dTopics); } public ArrayList<DecoratedTopicsInfo> getTopics(){ return topics; } public Boolean getAvailability() { return availability; } public void setAvailability(Boolean availability) { this.availability = availability; } } public class DecoratedTopicsInfo{ private Long topicId; private Boolean isLocked, isDraft, isModerated, availability; private String creator; public DecoratedTopicsInfo(Long topicId, Boolean isLocked, Boolean isDraft, Boolean availability, Boolean isModerated, String creator){ this.topicId = topicId; this.isLocked = isLocked; this.isDraft = isDraft; this.isModerated = isModerated; this.creator = creator; this.availability = availability; } public Long getTopicId() { return topicId; } public void setTopicId(Long topicId) { this.topicId = topicId; } public Boolean getIsLocked() { return isLocked; } public void setIsLocked(Boolean isLocked) { this.isLocked = isLocked; } public Boolean getIsDraft() { return isDraft; } public void setIsDraft(Boolean isDraft) { this.isDraft = isDraft; } public Boolean getIsModerated() { return isModerated; } public void setIsModerated(Boolean isModerated) { this.isModerated = isModerated; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Boolean getAvailability() { return availability; } public void setAvailability(Boolean availability) { this.availability = availability; } } public void updateAllSiteTitles(final String siteId, final String siteTitle) { HibernateCallback hcb = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = session.getNamedQuery(QUERY_UPDATE_ALL_SITE_TITLES); q.setParameter("siteTitle", siteTitle, Hibernate.STRING); q.setParameter("siteId", siteId, Hibernate.STRING); return q.executeUpdate(); } }; getHibernateTemplate().execute(hcb); } }
true
true
private DecoratedCompiledMessageStats getDMessageStats(String userId, String siteId, Site site, HashMap<Long, DecoratedForumInfo> dfHM, HashMap<String, Integer> unreadMessagesHM){ final DecoratedCompiledMessageStats dcms = new DecoratedCompiledMessageStats(); // Check if tool within site // if so, get stats for just this site boolean isMessageForumsPageInSite = isMessageForumsPageInSite(site); dcms.setSiteName(site.getTitle()); dcms.setSiteId(siteId); //MSGCNTR-430 if this is the anon user we can't actualy do anything more -DH if (userId == null) { return dcms; } if (isMessageForumsPageInSite || isMessagesPageInSite(site)) { if(unreadMessagesHM != null){ // Get private message area so we can get the private message forum so we can get the // List of topics so we can get the Received topic to finally determine number of unread messages // only check if Messages & Forums in site, just Messages is on by default boolean isEnabled; if (isMessageForumsPageInSite) { final Area area = pvtMessageManager.getPrivateMessageArea(siteId); isEnabled = area.getEnabled().booleanValue(); } else { isEnabled = true; } if (isEnabled) { Integer newMessageCount = unreadMessagesHM.get(userId); if(newMessageCount != null){ dcms.setUnreadPrivateAmt(newMessageCount.intValue()); } } } } if (isMessageForumsPageInSite || isForumsPageInSite(site)) { Set<Long> dfKeySet = null; int unreadForum = 0; if(dfHM != null){ boolean isSuperUser = SecurityService.isSuperUser(userId); //site has forums added to the tool dfKeySet = dfHM.keySet(); boolean isInstructor = getForumManager().isInstructor(userId, "/site/" + siteId); boolean hasOverridingPermission = false; if(isInstructor || isSuperUser){ hasOverridingPermission = true; } boolean isAreaAvailable = true; if(!hasOverridingPermission){ //need to check that the area hasn't been disabled: Area area = forumManager.getDiscussionForumArea(siteId); if(area != null){ isAreaAvailable = area.getAvailability(); } } if(isAreaAvailable){ for (Iterator iterator = dfKeySet.iterator(); iterator.hasNext();) { Long dfId = (Long) iterator.next(); DecoratedForumInfo dForum = dfHM.get(dfId); // Only count unread messages for forums the user can view: if ((dForum.getIsDraft().equals(Boolean.FALSE) && dForum.getAvailability()) || hasOverridingPermission || forumManager.isForumOwner(dfId, dForum.getCreator(), userId, "/site/" + siteId)) { final Iterator<DecoratedTopicsInfo> topicIter = dForum.getTopics().iterator(); while (topicIter.hasNext()) { DecoratedTopicsInfo topic = (DecoratedTopicsInfo) topicIter.next(); Long topicId = topic.getTopicId(); Boolean isTopicDraft = topic.getIsDraft(); Boolean isTopicModerated = topic.getIsModerated(); Boolean isTopicLocked = topic.getIsLocked(); String topicOwner = topic.getCreator(); //Only count unread messages for topics the user can view: if ((isTopicDraft.equals(Boolean.FALSE) && topic.getAvailability()) || isInstructor || isSuperUser ||forumManager.isTopicOwner(topicId, topicOwner, userId, "/site/" + siteId)){ if (getUiPermissionsManager().isRead(topicId, isTopicDraft, dForum.getIsDraft(), userId, siteId)) { if (!isTopicModerated.booleanValue() || (isTopicModerated.booleanValue() && getUiPermissionsManager().isModeratePostings(topicId, dForum.getIsLocked(), dForum.getIsDraft(), isTopicLocked, isTopicDraft, userId, siteId))) { unreadForum += getMessageManager().findUnreadMessageCountByTopicIdByUserId(topicId, userId); } else { // b/c topic is moderated and user does not have mod perm, user may only // see approved msgs or pending/denied msgs authored by user unreadForum += getMessageManager().findUnreadViewableMessageCountByTopicIdByUserId(topicId, userId); } } } } } } } } dcms.setUnreadForumsAmt(unreadForum); } return dcms; }
private DecoratedCompiledMessageStats getDMessageStats(String userId, String siteId, Site site, HashMap<Long, DecoratedForumInfo> dfHM, HashMap<String, Integer> unreadMessagesHM){ final DecoratedCompiledMessageStats dcms = new DecoratedCompiledMessageStats(); // Check if tool within site // if so, get stats for just this site boolean isMessageForumsPageInSite = isMessageForumsPageInSite(site); dcms.setSiteName(site.getTitle()); dcms.setSiteId(siteId); //MSGCNTR-430 if this is the anon user we can't actually do anything more -DH if (userId == null) { return dcms; } if (isMessageForumsPageInSite || isMessagesPageInSite(site)) { if(unreadMessagesHM != null){ // Get private message area so we can get the private message forum so we can get the // List of topics so we can get the Received topic to finally determine number of unread messages // only check if Messages & Forums in site, just Messages is on by default boolean isEnabled; if (isMessageForumsPageInSite) { final Area area = pvtMessageManager.getPrivateMessageArea(siteId); isEnabled = area.getEnabled().booleanValue(); } else { isEnabled = true; } if (isEnabled) { Integer newMessageCount = unreadMessagesHM.get(userId); if(newMessageCount != null){ dcms.setUnreadPrivateAmt(newMessageCount.intValue()); } } } } if (isMessageForumsPageInSite || isForumsPageInSite(site)) { Set<Long> dfKeySet = null; int unreadForum = 0; if(dfHM != null){ boolean isSuperUser = SecurityService.isSuperUser(userId); //site has forums added to the tool dfKeySet = dfHM.keySet(); boolean isInstructor = getForumManager().isInstructor(userId, "/site/" + siteId); boolean hasOverridingPermission = false; if(isInstructor || isSuperUser){ hasOverridingPermission = true; } boolean isAreaAvailable = true; if(!hasOverridingPermission){ //need to check that the area hasn't been disabled: Area area = forumManager.getDiscussionForumArea(siteId); if(area != null){ isAreaAvailable = area.getAvailability(); } } if(isAreaAvailable){ for (Iterator iterator = dfKeySet.iterator(); iterator.hasNext();) { Long dfId = (Long) iterator.next(); DecoratedForumInfo dForum = dfHM.get(dfId); // Only count unread messages for forums the user can view: if ((dForum.getIsDraft().equals(Boolean.FALSE) && dForum.getAvailability()) || hasOverridingPermission || forumManager.isForumOwner(dfId, dForum.getCreator(), userId, "/site/" + siteId)) { final Iterator<DecoratedTopicsInfo> topicIter = dForum.getTopics().iterator(); while (topicIter.hasNext()) { DecoratedTopicsInfo topic = (DecoratedTopicsInfo) topicIter.next(); Long topicId = topic.getTopicId(); Boolean isTopicDraft = topic.getIsDraft(); Boolean isTopicModerated = topic.getIsModerated(); Boolean isTopicLocked = topic.getIsLocked(); String topicOwner = topic.getCreator(); //Only count unread messages for topics the user can view: if ((isTopicDraft.equals(Boolean.FALSE) && topic.getAvailability()) || isInstructor || isSuperUser ||forumManager.isTopicOwner(topicId, topicOwner, userId, "/site/" + siteId)){ if (getUiPermissionsManager().isRead(topicId, isTopicDraft, dForum.getIsDraft(), userId, siteId)) { if (!isTopicModerated.booleanValue() || (isTopicModerated.booleanValue() && getUiPermissionsManager().isModeratePostings(topicId, dForum.getIsLocked(), dForum.getIsDraft(), isTopicLocked, isTopicDraft, userId, siteId))) { unreadForum += getMessageManager().findUnreadMessageCountByTopicIdByUserId(topicId, userId); } else { // b/c topic is moderated and user does not have mod perm, user may only // see approved msgs or pending/denied msgs authored by user unreadForum += getMessageManager().findUnreadViewableMessageCountByTopicIdByUserId(topicId, userId); } } } } } } } } dcms.setUnreadForumsAmt(unreadForum); } return dcms; }